// tow-kit.jsx — AIDAPP Tow Assistance: data, accent system, shared UI atoms.
// Reuses C / Icon / StatusBar / SubHeader / Phone from ui.jsx.

// ── Accent / branding ────────────────────────────────────────────────
// Accent drives primary actions, active states, selected pins. Default = AIDAPP navy.
const AccentCtx = React.createContext({ accent: 'rgb(24,32,87)' });
window.AccentCtx = AccentCtx;
const useAccent = () => React.useContext(window.AccentCtx).accent;
window.useAccent = useAccent;

function hexToRgb(hex) {
  let h = String(hex).replace('#', '');
  if (h.length === 3) h = h.replace(/./g, c => c + c);
  const n = parseInt(h, 16);
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
// Accept rgb(...) or #hex → "r,g,b"
function rgbTriplet(color) {
  if (color.startsWith('rgb')) return color.replace(/rgba?\(([^)]+)\)/, '$1').split(',').slice(0, 3).map(s => s.trim()).join(',');
  return hexToRgb(color).join(',');
}
function tint(color, a) { return `rgba(${rgbTriplet(color)},${a})`; }
window.tint = tint;

function fmtTg(n) { return n.toLocaleString('ru-RU').replace(/,/g, ' ') + ' ₸'; }
window.fmtTg = fmtTg;

// ── Extra icons (delegates to window.Icon for the shared set) ─────────
const EXTRA_PATHS = {
  'lock': <><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></>,
  'eye-off': <><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 10 8 10 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><path d="M6.61 6.61A18.45 18.45 0 0 0 2 12s3 8 10 8a9.12 9.12 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></>,
  'zap': <><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></>,
  'tag': <><path d="M20.59 13.41 13.42 20.6a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></>,
  'refresh': <><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></>,
  'shield-check': <><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11.5 14.5 16 9.5"/></>,
  'plus': <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
  'minus': <><line x1="5" y1="12" x2="19" y2="12"/></>,
  'flag': <><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></>,
  'headset': <><path d="M3 14v-2a9 9 0 0 1 18 0v2"/><path d="M21 14v3a3 3 0 0 1-3 3h-3"/><rect x="2" y="13" width="4" height="7" rx="1.5"/><rect x="18" y="13" width="4" height="7" rx="1.5"/></>,
  'route': <><circle cx="6" cy="19" r="3"/><circle cx="18" cy="5" r="3"/><path d="M9 19h6a3 3 0 0 0 0-6H9a3 3 0 0 1 0-6h0"/></>,
  'user': <><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></>,
  'thumbs-up': <><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></>,
  'pin': <><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></>,
};
function TIcon({ name, size = 20, color = 'currentColor', strokeWidth = 1.8, style }) {
  if (EXTRA_PATHS[name]) {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
        stroke={color} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round"
        style={{ display: 'block', flexShrink: 0, ...style }}>
        {EXTRA_PATHS[name]}
      </svg>
    );
  }
  return <window.Icon name={name} size={size} color={color} strokeWidth={strokeWidth} style={style} />;
}
window.TIcon = TIcon;

// ── Domain data ──────────────────────────────────────────────────────
const TOW_TYPES = {
  platform:    { label: 'Платформа',  sub: 'Полная погрузка' },
  partial:     { label: 'Частичная',  sub: 'Сцепка / буксир' },
  manipulator: { label: 'Манипулятор', sub: 'Кран-погрузка' },
  sliding:     { label: 'Сдвижная',   sub: 'Ломаная платформа' },
};
window.TOW_TYPES = TOW_TYPES;

// x/y are map coords inside the 375×440 map viewport
const TOWS = [
  { id: 1, name: 'Эвакуатор 24',     driver: 'Арман Т.',  rating: 4.9, orders: 1842, eta: 8,  dist: 1.2, price: 9000,  type: 'platform',    verified: true,  tone: 'a', x: 232, y: 150 },
  { id: 2, name: 'АвтоСпас Алматы',  driver: 'Данияр К.', rating: 4.8, orders: 2310, eta: 12, dist: 2.1, price: 8500,  type: 'partial',     verified: true,  tone: 'b', x: 96,  y: 210 },
  { id: 3, name: 'GoTow',            driver: 'Сергей М.', rating: 4.9, orders: 1205, eta: 10, dist: 1.8, price: 11000, type: 'sliding',     verified: true,  tone: 'c', x: 286, y: 250 },
  { id: 4, name: 'Барыс Эвакуатор',  driver: 'Ержан А.',  rating: 4.7, orders: 640,  eta: 15, dist: 3.0, price: 10000, type: 'manipulator', verified: true,  tone: 'd', x: 70,  y: 320 },
  { id: 5, name: 'Эвакуатор Алатау', driver: 'Бекзат С.', rating: 4.6, orders: 410,  eta: 19, dist: 4.4, price: 7500,  type: 'platform',    verified: false, tone: 'e', x: 318, y: 360 },
  { id: 6, name: 'Tau Service',      driver: 'Олжас Н.',  rating: 4.8, orders: 980,  eta: 22, dist: 5.6, price: 9500,  type: 'manipulator', verified: true,  tone: 'f', x: 150, y: 392 },
];
window.TOWS = TOWS;

const AVATAR_TONES = {
  a: ['#1f2a5e', '#36459c'], b: ['#0e5b46', '#149a6f'], c: ['#7a3d12', '#c2701f'],
  d: ['#5a1f6e', '#9a3bb0'], e: ['#1f4d6e', '#2f86b8'], f: ['#6e1f2a', '#b03b49'],
};
window.AVATAR_TONES = AVATAR_TONES;

// Status pipeline (ordered)
const STATUS_FLOW = ['created', 'searching', 'offers', 'accepted', 'assigned', 'arriving', 'completed'];
const STATUS_META = {
  created:   { label: 'Заявка создана',        hint: 'Заявка зарегистрирована' },
  searching: { label: 'Идёт поиск',            hint: 'Отправляем ближайшим эвакуаторам' },
  offers:    { label: 'Предложения получены',  hint: 'Эвакуаторы откликнулись' },
  accepted:  { label: 'Эвакуатор выбран',      hint: 'Вы выбрали исполнителя' },
  assigned:  { label: 'Эвакуатор назначен',    hint: 'Водитель подтвердил и выехал' },
  arriving:  { label: 'Подъезжает к вам',      hint: 'Эвакуатор почти на месте' },
  completed: { label: 'Завершено',             hint: 'Автомобиль доставлен' },
  cancelled: { label: 'Заявка отменена',       hint: 'Поиск остановлен' },
};
window.STATUS_FLOW = STATUS_FLOW;
window.STATUS_META = STATUS_META;

// ── Atoms ────────────────────────────────────────────────────────────
function TowAvatar({ tone = 'a', size = 52, radius = 14, online = true, icon = 'truck' }) {
  const [c1, c2] = AVATAR_TONES[tone] || AVATAR_TONES.a;
  return (
    <div style={{ position: 'relative', flexShrink: 0 }}>
      <div style={{
        width: size, height: size, borderRadius: radius,
        background: `linear-gradient(135deg, ${c1}, ${c2})`,
        display: 'grid', placeItems: 'center', overflow: 'hidden',
      }}>
        <window.Icon name={icon} size={Math.round(size * 0.5)} color="rgba(255,255,255,0.95)" strokeWidth={1.7}/>
      </div>
      {online && (
        <span style={{
          position: 'absolute', right: -2, bottom: -2, width: 14, height: 14, borderRadius: 999,
          background: C.greenSolid, border: '2.5px solid #fff',
        }}/>
      )}
    </div>
  );
}
window.TowAvatar = TowAvatar;

function TypeChip({ type, accent }) {
  const t = TOW_TYPES[type];
  if (!t) return null;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '3px 8px', borderRadius: 999, background: tint(accent, 0.08),
      fontSize: 11, fontWeight: 600, color: accent, fontFamily: 'Inter', whiteSpace: 'nowrap',
    }}>
      <window.Icon name="truck" size={11} color={accent} strokeWidth={2}/>
      {t.label}
    </span>
  );
}
window.TypeChip = TypeChip;

function Rating({ value, orders, size = 12 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, color: C.textMuted, fontFamily: 'Inter', whiteSpace: 'nowrap' }}>
      <window.Icon name="star" size={size} color={C.yellow}/>
      <b style={{ color: C.text, fontWeight: 700 }}>{value.toFixed(1)}</b>
      {orders != null && <span style={{ color: C.textFaint, whiteSpace: 'nowrap' }}>· {orders.toLocaleString('ru-RU')} заказов</span>}
    </span>
  );
}
window.Rating = Rating;

// Verified badge
function Verified({ accent }) {
  return (
    <span title="Проверенный исполнитель" style={{
      display: 'inline-grid', placeItems: 'center', width: 16, height: 16, borderRadius: 999,
      background: tint(accent, 0.12), flexShrink: 0,
    }}>
      <window.TIcon name="shield-check" size={11} color={accent} strokeWidth={2.4}/>
    </span>
  );
}
window.Verified = Verified;

// Anti-spam / number protection banner — the core selling point
function ProtectBanner({ unlocked = false, compact = false }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: compact ? '9px 12px' : '11px 14px', borderRadius: 14,
      background: unlocked ? C.greenBgSoft : C.surface,
      border: `1px solid ${unlocked ? 'rgba(20,174,92,0.25)' : C.hairline}`,
    }}>
      <div style={{
        width: 30, height: 30, borderRadius: 9, flexShrink: 0,
        background: unlocked ? 'rgba(20,174,92,0.14)' : '#fff',
        display: 'grid', placeItems: 'center',
      }}>
        <window.TIcon name={unlocked ? 'shield-check' : 'lock'} size={16}
          color={unlocked ? C.greenText : C.text} strokeWidth={2}/>
      </div>
      <div style={{ flex: 1, fontFamily: 'Inter', minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 700, color: unlocked ? C.greenText : C.text, lineHeight: 1.25 }}>
          {unlocked ? 'Контакт открыт выбранному эвакуатору' : 'Ваш номер скрыт'}
        </div>
        {!compact && (
          <div style={{ fontSize: 11.5, color: unlocked ? C.greenText : C.textMuted, opacity: unlocked ? 0.8 : 1, marginTop: 1 }}>
            {unlocked ? 'Связь только с тем, кого вы выбрали' : 'Звонки появятся только после вашего выбора'}
          </div>
        )}
      </div>
    </div>
  );
}
window.ProtectBanner = ProtectBanner;
