// ============================================================================
// REQUESTS / ЗАЯВКИ — точний відтворення дизайну
// ============================================================================
const { useState, useEffect, useCallback, useRef } = React;

// ── Status config (наші назви зі Sheet → дизайн-стилі) ───────────
const LEAD_STATUSES = {
  "Нова":         { label: "Нова",         dot: "var(--accent)", fg: "var(--fg-primary)", bg: "var(--accent-soft)" },
  "В роботі":     { label: "В роботі",     dot: "#F59E0B",       fg: "#FBBF24",           bg: "rgba(245,158,11,.14)" },
  "Конвертовано": { label: "Конвертовано", dot: "#10B981",       fg: "#6EE7B7",           bg: "rgba(16,185,129,.14)" },
  "Закрита":      { label: "Закрита",      dot: "#6B7280",       fg: "var(--fg-muted)",   bg: "rgba(107,114,128,.12)" },
};
const STATUS_NAMES = Object.keys(LEAD_STATUSES);

// ── Bot replies ───────────────────────────────────────────────────
const BOT_REPLIES = {
  available: { label: "В наявності", color: "#10B981", bg: "rgba(16,185,129,.12)", icon: "check-circle" },
  awaiting:  { label: "Уточнюється", color: "#F59E0B", bg: "rgba(245,158,11,.14)", icon: "clock"        },
  out:       { label: "Немає",       color: "#EF4444", bg: "rgba(239,68,68,.14)",  icon: "x-circle"     },
  "—":       { label: "—",           color: "var(--fg-muted)", bg: "transparent",  icon: "minus"        },
};

function parseBotKey(supplier) {
  if (!supplier) return "—";
  if (String(supplier).startsWith("✅")) return "available";
  if (String(supplier).startsWith("⏳")) return "awaiting";
  if (String(supplier).startsWith("❌")) return "out";
  return "—";
}

// ── Sources ───────────────────────────────────────────────────────
const SOURCES = {
  telegram: { label: "Telegram", icon: "send",        color: "#229ED9" },
  viber:    { label: "Viber",    icon: "phone",       color: "#7360F2" },
  site:     { label: "CRM",      icon: "monitor",     color: "var(--fg-secondary)" },
  call:     { label: "Дзвінок",  icon: "phone-call",  color: "#10B981" },
  whatsapp: { label: "WhatsApp", icon: "message-circle", color: "#25D366" },
};

function mapSource(src) {
  const m = { "CRM": "site", "Дзвінок": "call", "Telegram": "telegram", "Viber": "viber" };
  return m[src] || "site";
}

// ── Age helpers ───────────────────────────────────────────────────
function parseReqDate(str) {
  if (!str) return null;
  const m = str.match(/(\d{1,2})\.(\d{2})\.(\d{4}),?\s*(\d{2}):(\d{2})/);
  if (!m) return null;
  return new Date(`${m[3]}-${m[2]}-${String(m[1]).padStart(2,"0")}T${m[4]}:${m[5]}:00`);
}
function calcAgeMin(str) {
  const d = parseReqDate(str);
  return d ? Math.max(0, Math.floor((Date.now() - d.getTime()) / 60000)) : 0;
}
function fmtAge(min) {
  if (min < 60)   return `${min} хв`;
  if (min < 1440) return `${Math.floor(min / 60)} год`;
  return `${Math.floor(min / 1440)} д`;
}
function ageTone(min, status) {
  if (status === "Конвертовано" || status === "Закрита") return "var(--fg-muted)";
  if (min < 15)  return "#10B981";
  if (min < 60)  return "var(--fg-secondary)";
  if (min < 240) return "#F59E0B";
  return "#EF4444";
}

// ── Adapt API row → lead shape ────────────────────────────────────
function toLeadShape(r) {
  const ageMin = calcAgeMin(r.date);
  return {
    _raw:       r,
    id:         r.id,
    ts:         r.date || "",
    source:     mapSource(r.source),
    product:    r.product || "",
    phone:      r.phone   || "",
    clientName: r.name    || "—",
    bot:        parseBotKey(r.supplier),
    manager:    r.manager || "—",
    status:     r.status  || "Нова",
    ageMin,
    note:       r.type !== "Запит товару" ? (r.desc || "") : (r.desc || ""),
    type:       r.type    || "",
    orderId:    r.orderId || null,
    comment:    r.comment || "",
    supplier:   r.supplier|| "",
  };
}

// ── Lead types for new modal ───────────────────────────────────────
const LEAD_TYPES = [
  { key: "Запит товару",  icon: "package",        desc: "Перевірити наявність SKU"  },
  { key: "Гарантія",      icon: "shield-check",   desc: "Гарантійний випадок"        },
  { key: "Повернення",    icon: "rotate-ccw",     desc: "Повернення або обмін"       },
  { key: "Питання",       icon: "message-circle", desc: "Загальне питання"           },
];

// ─────────────────────────────────────────────────────────────────
// KPI strip
// ─────────────────────────────────────────────────────────────────
function LeadsKPI({ leads }) {
  const total        = leads.length;
  const newCount     = leads.filter(l => l.status === "Нова").length;
  const waiting      = leads.filter(l => l.status === "В роботі").length;
  const converted    = leads.filter(l => l.status === "Конвертовано").length;
  const conversion   = total > 0 ? Math.round((converted / total) * 100) : 0;
  const oldUnhandled = leads.filter(l =>
    (l.status === "Нова" || l.status === "В роботі") && l.ageMin > 60
  ).length;

  // Менеджери: групуємо кількість активних заявок по імені
  const mgrMap = {};
  leads.filter(l => l.status !== "Закрита" && l.status !== "Конвертовано").forEach(l => {
    const m = l.manager === "—" ? "Не призначено" : (l.manager || "Не призначено");
    mgrMap[m] = (mgrMap[m] || 0) + 1;
  });
  const mgrEntries = Object.entries(mgrMap).sort((a, b) => b[1] - a[1]);

  return (
    <div style={{ display: "flex", flexDirection: "column", borderBottom: "1px solid var(--border-subtle)", flexShrink: 0 }}>
      {/* Stat cards row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 1, background: "var(--border-subtle)" }}>
        {[
          { label: "Всього",        value: total,           sub: "",                          tone: "var(--fg-primary)" },
          { label: "Нові",          value: newCount,        sub: "Потребують відповіді",      tone: "var(--accent)",  pulse: newCount > 0 },
          { label: "В роботі",      value: waiting,         sub: "Уточнення наявності",       tone: "#F59E0B" },
          { label: "Прострочені",   value: oldUnhandled,    sub: "> 1 год без відповіді",     tone: oldUnhandled > 0 ? "#EF4444" : "var(--fg-muted)" },
          { label: "Конверсія",     value: conversion + "%", sub: `${converted} в замовленні`, tone: "#10B981" },
        ].map((s, i) => (
          <div key={i} style={{ background: "var(--bg-base)", padding: "14px 18px", display: "flex", flexDirection: "column", gap: 4 }}>
            <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", display: "flex", alignItems: "center", gap: 6 }}>
              {s.pulse && <span className="lead-pulse" style={{ width: 6, height: 6, borderRadius: "50%", background: s.tone, display: "inline-block" }}/>}
              {s.label}
            </div>
            <div style={{ fontSize: 24, fontWeight: 600, color: s.tone, fontVariantNumeric: "tabular-nums", lineHeight: 1.1 }}>{s.value}</div>
            {s.sub && <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>{s.sub}</div>}
          </div>
        ))}
      </div>
      {/* Менеджери row */}
      {mgrEntries.length > 0 && (
        <div style={{ padding: "8px 18px", background: "var(--bg-base)", display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap", borderTop: "1px solid var(--border-subtle)" }}>
          <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-muted)", marginRight: 4 }}>Відповідальні:</span>
          {mgrEntries.map(([name, count]) => (
            <span key={name} style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 24, padding: "0 10px", borderRadius: 999, background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", fontSize: 12 }}>
              <Avatar name={name} size={16}/>
              <span style={{ color: "var(--fg-primary)", fontWeight: 500 }}>{name}</span>
              <span style={{ color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{count}</span>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// KPI strip mobile
// ─────────────────────────────────────────────────────────────────
function LeadsKPIM({ leads }) {
  const newCount = leads.filter(l => l.status === "Нова").length;
  const overdue  = leads.filter(l => (l.status === "Нова" || l.status === "В роботі") && l.ageMin > 30).length;
  const today    = leads.filter(l => l.ageMin < 1440).length;
  return (
    <div style={{ padding: "10px 16px 4px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, flexShrink: 0 }}>
      {[
        { label: "Нові",        value: newCount, tone: "#3B82F6" },
        { label: "Прострочені", value: overdue,  tone: "#EF4444" },
        { label: "За добу",     value: today,    tone: "#10B981" },
      ].map(k => (
        <div key={k.label} style={{ padding: "10px 12px", borderRadius: 10, background: "var(--bg-panel)", border: "1px solid var(--border-subtle)" }}>
          <div style={{ fontSize: 9, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 2 }}>{k.label}</div>
          <div style={{ fontSize: 20, fontWeight: 700, color: k.tone, fontVariantNumeric: "tabular-nums" }}>{k.value}</div>
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Filter chips
// ─────────────────────────────────────────────────────────────────
function FilterChips({ filter, onChange, leads }) {
  const counts = {
    all: leads.length,
    ...Object.fromEntries(STATUS_NAMES.map(s => [s, leads.filter(l => l.status === s).length])),
  };
  const chips = [
    { key: "all", label: "Усі" },
    ...STATUS_NAMES.map(s => ({ key: s, label: LEAD_STATUSES[s].label, dot: LEAD_STATUSES[s].dot })),
  ];
  return (
    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
      {chips.map(c => {
        const active = filter === c.key;
        return (
          <button key={c.key} onClick={() => onChange(c.key)} style={{
            display: "inline-flex", alignItems: "center", gap: 7, height: 30, padding: "0 12px",
            border: "1px solid " + (active ? "var(--accent)" : "var(--border-default)"),
            background: active ? "var(--accent-soft)" : "var(--bg-raised)",
            color: active ? "var(--fg-primary)" : "var(--fg-secondary)",
            borderRadius: 999, fontFamily: "inherit", fontSize: 12, fontWeight: 500, cursor: "pointer",
          }}>
            {c.dot && <span style={{ width: 6, height: 6, borderRadius: "50%", background: c.dot }}/>}
            {c.label}
            <span style={{ color: "var(--fg-muted)", fontWeight: 400, fontVariantNumeric: "tabular-nums" }}>{counts[c.key] ?? 0}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Pills
// ─────────────────────────────────────────────────────────────────
function SourcePill({ source }) {
  const s = SOURCES[source] || SOURCES.site;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 22, padding: "0 7px", borderRadius: 6, background: "var(--bg-raised)", border: "1px solid var(--border-subtle)", fontSize: 11, fontWeight: 500, color: "var(--fg-secondary)", whiteSpace: "nowrap" }}>
      <span style={{ color: s.color, display: "inline-flex" }}><Icon name={s.icon} size={11}/></span>
      {s.label}
    </span>
  );
}

function BotPill({ bot }) {
  const r = BOT_REPLIES[bot] || BOT_REPLIES["—"];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 22, padding: "0 7px", borderRadius: 6, background: r.bg, color: r.color, whiteSpace: "nowrap", fontSize: 11, fontWeight: 500 }}>
      <Icon name={r.icon} size={11}/>
      {r.label}
    </span>
  );
}

function StatusDot({ status }) {
  const s = LEAD_STATUSES[status] || LEAD_STATUSES["Нова"];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 22, padding: "0 9px 0 8px", borderRadius: 999, background: s.bg, color: s.fg, whiteSpace: "nowrap", fontSize: 11, fontWeight: 500 }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: s.dot }}/>
      {s.label}
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────
// Lead row (desktop)
// ─────────────────────────────────────────────────────────────────
function LeadRow({ lead, selected, onSelect, onStatusChange }) {
  const [showStatus, setShowStatus] = useState(false);
  const tone    = ageTone(lead.ageMin, lead.status);
  const isHot   = lead.ageMin < 15 && lead.status !== "Конвертовано" && lead.status !== "Закрита";
  const isStale = lead.ageMin > 60 && (lead.status === "Нова" || lead.status === "В роботі");
  const isSel   = selected?.id === lead.id;

  return (
    <div onClick={() => onSelect(lead)} className="lead-row" style={{
      display: "grid",
      gridTemplateColumns: "36px 70px minmax(0,1.5fr) minmax(0,1.1fr) 100px 110px 110px 90px",
      alignItems: "center", gap: 10, padding: "12px 18px",
      borderBottom: "1px solid var(--border-subtle)", cursor: "pointer",
      background: isSel ? "var(--bg-active)" : (isStale ? "rgba(239,68,68,.025)" : "transparent"),
      borderLeft: "3px solid " + (isSel ? "var(--accent)" : (isHot ? "#10B981" : (isStale ? "#EF4444" : "transparent"))),
      paddingLeft: 17,
    }}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>#{lead.id}</span>

      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        <span style={{ fontSize: 13, fontWeight: 500, color: tone, fontVariantNumeric: "tabular-nums" }}>{fmtAge(lead.ageMin)}</span>
        <span style={{ fontSize: 10, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{lead.ts.slice(-5) || "—"}</span>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 3, minWidth: 0 }}>
        <span style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {lead.product || lead.note || "—"}
        </span>
        {(lead.note && lead.product) && (
          <span style={{ fontSize: 11, color: "var(--fg-muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {lead.note}
          </span>
        )}
        {lead.type && <span style={{ fontSize: 10, color: "var(--fg-muted)" }}>{lead.type}</span>}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 3, minWidth: 0 }}>
        <span style={{ fontSize: 13, color: "var(--fg-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{lead.clientName}</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{fmtPhone(lead.phone)}</span>
      </div>

      <div><SourcePill source={lead.source}/></div>
      <div><BotPill bot={lead.bot}/></div>

      <div style={{ position: "relative" }}>
        <button onClick={e => { e.stopPropagation(); setShowStatus(s => !s); }} style={{ background: "transparent", border: "none", padding: 0, cursor: "pointer" }}>
          <StatusDot status={lead.status}/>
        </button>
        {showStatus && (
          <>
            <div style={{ position: "fixed", inset: 0, zIndex: 49 }} onClick={e => { e.stopPropagation(); setShowStatus(false); }}/>
            <div style={{ position: "absolute", top: "100%", left: 0, zIndex: 50, marginTop: 4, background: "var(--bg-panel)", border: "1px solid var(--border-default)", borderRadius: 10, boxShadow: "var(--shadow-2)", overflow: "hidden", minWidth: 160 }}>
              {STATUS_NAMES.map(s => (
                <button key={s} onClick={e => { e.stopPropagation(); onStatusChange(lead.id, s); setShowStatus(false); }} style={{ display: "block", width: "100%", padding: "10px 14px", border: 0, background: s === lead.status ? "var(--accent-soft)" : "transparent", color: s === lead.status ? "var(--accent)" : "var(--fg-primary)", fontSize: 13, cursor: "pointer", fontFamily: "inherit", textAlign: "left" }}>{s}</button>
              ))}
            </div>
          </>
        )}
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
        {lead.manager === "—" ? (
          <span style={{ fontSize: 11, color: "var(--fg-muted)", fontStyle: "italic" }}>не призначено</span>
        ) : (
          <>
            <Avatar name={lead.manager} size={20}/>
            <span style={{ fontSize: 12, color: "var(--fg-secondary)" }}>{lead.manager}</span>
          </>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Detail rail (right panel, desktop)
// ─────────────────────────────────────────────────────────────────
function LeadDetail({ lead, onClose, onConvert, onCollapse, onEdit }) {
  if (!lead) {
    return (
      <div style={{ width: 280, borderLeft: "1px solid var(--border-subtle)", background: "var(--bg-panel)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", color: "var(--fg-muted)", padding: 32, textAlign: "center", gap: 10, flexShrink: 0, position: "relative" }}>
        <button onClick={onCollapse} title="Сховати панель" style={{ position: "absolute", top: 10, right: 10, width: 26, height: 26, border: 0, background: "var(--bg-raised)", color: "var(--fg-secondary)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="panel-right-close" size={14}/>
        </button>
        <div style={{ width: 48, height: 48, borderRadius: 12, background: "var(--bg-raised)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--fg-muted)" }}>
          <Icon name="mouse-pointer-click" size={20}/>
        </div>
        <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-secondary)" }}>Виберіть заявку</div>
        <div style={{ fontSize: 12, color: "var(--fg-muted)", maxWidth: 240, lineHeight: 1.5 }}>
          Натисніть на рядок ліворуч, щоб переглянути деталі
        </div>
      </div>
    );
  }

  const tone = ageTone(lead.ageMin, lead.status);
  const mainText = lead.type === "Запит товару" ? lead.product : (lead.note || lead.product);

  return (
    <div style={{ width: 320, borderLeft: "1px solid var(--border-subtle)", background: "var(--bg-panel)", display: "flex", flexDirection: "column", flexShrink: 0 }}>
      {/* Header */}
      <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>#{lead.id}</span>
        <StatusDot status={lead.status}/>
        <div style={{ flex: 1 }}/>
        <button onClick={() => onEdit && onEdit(lead._raw)} style={{ width: 28, height: 28, border: "1px solid var(--border-default)", borderRadius: 6, background: "transparent", color: "var(--fg-secondary)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="pencil" size={13}/>
        </button>
        <button onClick={onClose} style={{ width: 28, height: 28, border: 0, background: "transparent", color: "var(--fg-muted)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="x" size={16}/>
        </button>
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: "18px" }}>
        {/* SLA */}
        <div style={{ padding: "10px 12px", borderRadius: 8, background: `color-mix(in srgb, ${tone} 12%, transparent)`, border: `1px solid color-mix(in srgb, ${tone} 28%, transparent)`, marginBottom: 16, display: "flex", alignItems: "center", gap: 10 }}>
          <Icon name="clock" size={16} style={{ color: tone }}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 500, color: tone }}>{fmtAge(lead.ageMin)} тому</div>
            <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>{lead.ts}</div>
          </div>
        </div>

        {/* Запит */}
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>
            {lead.type === "Запит товару" ? "Артикул / товар" : "Суть заявки"}
          </div>
          <div style={{ fontSize: 15, fontWeight: 500, color: "var(--fg-primary)", marginBottom: 8 }}>{mainText || "—"}</div>
          {lead.comment && (
            <div style={{ fontSize: 12, color: "var(--fg-secondary)", lineHeight: 1.5, padding: "10px 12px", background: "var(--bg-raised)", borderRadius: 8, border: "1px solid var(--border-subtle)" }}>
              {lead.comment}
            </div>
          )}
        </div>

        {/* Відповідь бота */}
        {lead.type === "Запит товару" && (
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>Відповідь Telegram-бота</div>
            <BotPill bot={lead.bot}/>
          </div>
        )}

        {/* Клієнт */}
        <div style={{ marginBottom: 18 }}>
          <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 8 }}>Клієнт</div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", background: "var(--bg-raised)", borderRadius: 8, border: "1px solid var(--border-subtle)", marginBottom: 8 }}>
            <Avatar name={lead.clientName} size={32}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-primary)" }}>{lead.clientName}</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{fmtPhone(lead.phone)}</div>
            </div>
          </div>
        </div>

        {/* Джерело + Менеджер */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>Джерело</div>
            <SourcePill source={lead.source}/>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>Менеджер</div>
            {lead.manager === "—" ? (
              <span style={{ fontSize: 12, color: "var(--fg-muted)", fontStyle: "italic" }}>не призначено</span>
            ) : (
              <div style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <Avatar name={lead.manager} size={20}/>
                <span style={{ fontSize: 12, color: "var(--fg-secondary)" }}>{lead.manager}</span>
              </div>
            )}
          </div>
        </div>

        {/* Пов'язане замовлення */}
        {lead.orderId && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", background: "rgba(16,185,129,.08)", border: "1px solid rgba(16,185,129,.2)", borderRadius: 8, marginBottom: 18 }}>
            <Icon name="check-circle" size={16} style={{ color: "#10B981" }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 500, color: "#6EE7B7" }}>Пов'язане замовлення</div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-muted)" }}>#{lead.orderId}</div>
            </div>
          </div>
        )}
      </div>

      {/* Footer */}
      {lead.status !== "Конвертовано" && lead.status !== "Закрита" && (
        <div style={{ padding: "12px 16px", borderTop: "1px solid var(--border-subtle)", display: "flex", flexDirection: "column", gap: 8 }}>
          <Button variant="primary" size="md" leftIcon="check" style={{ justifyContent: "center" }} onClick={() => onConvert && onConvert(lead)}>
            Конвертувати в замовлення
          </Button>
          <Button variant="danger" size="md" leftIcon="x" style={{ justifyContent: "center" }} onClick={() => onEdit && onEdit({ ...lead._raw, status: "Закрита" })}>
            Позначити закритою
          </Button>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// New lead modal
// ─────────────────────────────────────────────────────────────────
function NewLeadModal({ open, onClose, onSave, prefill, userName, isEdit }) {
  if (!open) return null;
  const [type,      setType]      = useState(prefill?.type    || "Запит товару");
  const [sku,       setSku]       = useState(prefill?.sku     || "");
  const [phone,     setPhone]     = useState(prefill?.phone   || "");
  const [name,      setName]      = useState(prefill?.name    || "");
  const [source,    setSource]    = useState(prefill?.source  || "call");
  const [note,      setNote]      = useState(prefill?.note    || "");
  const [comment,   setComment]   = useState(prefill?.comment || "");
  const [orderId,   setOrderId]   = useState(prefill?.orderId || "");
  const [checking,  setChecking]  = useState(false);
  const [checkResult, setCheckResult] = useState(null); // { label, supplierValue, autoConfirmed, ok }
  const [supplier,  setSupplier]  = useState(prefill?.supplier || "");
  const [draftId,   setDraftId]   = useState(prefill?.id || null);

  const isOrderRequired = type === "Гарантія" || type === "Повернення";
  const isValid = type === "Запит товару" ? sku.trim() : (note.trim() && (isOrderRequired ? orderId.trim() : true));

  const handleCheck = async () => {
    if (!sku.trim()) return;
    setChecking(true);
    setCheckResult(null);
    try {
      let reqId = draftId;
      if (!reqId && !isEdit) {
        const draft = await API.createRequest({ type: "Запит товару", product: sku.trim(), manager: userName || "", skipAutoFind: true });
        reqId = draft.id;
        setDraftId(reqId);
      }
      const result = await API.checkAvailability(sku.trim(), userName, reqId);
      setCheckResult(result);
      if (result.supplierValue) setSupplier(result.supplierValue);
      if (result.article && !sku.trim().includes(result.article)) setSku(result.article);
    } catch {
      setCheckResult({ ok: false, label: "❌ Помилка зв'язку з ботом" });
    } finally {
      setChecking(false);
    }
  };

  const submit = (e) => {
    e?.preventDefault();
    if (!isValid) return;
    onSave({ type, sku, phone, name, source, note, comment, orderId, supplier, manager: userName || "", draftId });
    onClose();
  };

  const kbd = { display: "inline-block", padding: "1px 5px", border: "1px solid var(--border-default)", borderRadius: 4, background: "var(--bg-panel)", fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--fg-secondary)" };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.6)", backdropFilter: "blur(4px)", zIndex: 200, display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
      <form onClick={e => e.stopPropagation()} onSubmit={submit} style={{ width: 560, maxHeight: "90vh", background: "var(--bg-raised)", border: "1px solid var(--border-default)", borderRadius: 12, boxShadow: "0 30px 80px rgba(0,0,0,.5)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        {/* Header */}
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="plus" size={16}/>
          </div>
          <div>
            <h2 style={{ fontSize: 16, fontWeight: 600, color: "var(--fg-primary)", margin: 0 }}>{isEdit ? "Редагувати заявку" : "Нова заявка"}</h2>
            <div style={{ fontSize: 12, color: "var(--fg-muted)", marginTop: 2 }}>{isEdit ? `#${prefill?.id}` : "Зафіксуйте звернення клієнта"}</div>
          </div>
          <div style={{ flex: 1 }}/>
          <button type="button" onClick={onClose} style={{ width: 30, height: 30, border: 0, background: "var(--bg-panel)", color: "var(--fg-secondary)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="x" size={16}/>
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: "20px 22px", overflowY: "auto", flex: 1 }}>
          {/* Type cards */}
          <ModalLabel>Тип заявки</ModalLabel>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 18 }}>
            {LEAD_TYPES.map(lt => {
              const active = type === lt.key;
              return (
                <button key={lt.key} type="button" onClick={() => setType(lt.key)} style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "10px 12px", borderRadius: 8, cursor: "pointer", textAlign: "left", fontFamily: "inherit", background: active ? "var(--accent-soft)" : "var(--bg-panel)", border: "1px solid " + (active ? "var(--accent)" : "var(--border-subtle)") }}>
                  <div style={{ width: 28, height: 28, borderRadius: 6, flexShrink: 0, background: active ? "var(--accent)" : "var(--bg-raised)", color: active ? "#fff" : "var(--fg-secondary)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <Icon name={lt.icon} size={14}/>
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-primary)" }}>{lt.key}</div>
                    <div style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 2, lineHeight: 1.4 }}>{lt.desc}</div>
                  </div>
                </button>
              );
            })}
          </div>

          {/* SKU + check button for product */}
          {type === "Запит товару" && (
            <div style={{ marginBottom: 14 }}>
              <ModalLabel>Артикул або назва товару</ModalLabel>
              <div style={{ display: "flex", gap: 8 }}>
                <div style={{ position: "relative", flex: 1 }}>
                  <Icon name="search" size={14} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--fg-muted)" }}/>
                  <input value={sku} onChange={e => { setSku(e.target.value); setCheckResult(null); }} placeholder="Напр. iPhone 15 Pro Max 256GB" autoFocus
                    onKeyDown={e => e.key === "Enter" && handleCheck()}
                    style={{ width: "100%", height: 38, boxSizing: "border-box", padding: "0 12px 0 36px", background: "var(--bg-panel)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 8, fontSize: 13, outline: "none", fontFamily: "inherit" }}/>
                </div>
                <button type="button" onClick={handleCheck} disabled={!sku.trim() || checking} style={{ height: 38, padding: "0 16px", border: 0, borderRadius: 8, background: sku.trim() && !checking ? "var(--accent)" : "var(--bg-raised)", color: sku.trim() && !checking ? "#fff" : "var(--fg-muted)", fontSize: 13, fontWeight: 600, cursor: !sku.trim() || checking ? "not-allowed" : "pointer", fontFamily: "inherit", flexShrink: 0, display: "inline-flex", alignItems: "center", gap: 6, whiteSpace: "nowrap" }}>
                  {checking ? <><Icon name="loader" size={13}/>Перевірка…</> : <><Icon name="zap" size={13}/>Перевірити</>}
                </button>
              </div>

              {/* Check result */}
              {checkResult && (
                <div style={{ marginTop: 8, padding: "10px 12px", borderRadius: 8, display: "flex", alignItems: "center", gap: 8, background: checkResult.ok && checkResult.autoConfirmed ? "rgba(16,185,129,.1)" : checkResult.ok ? "rgba(245,158,11,.1)" : "rgba(239,68,68,.1)", border: `1px solid ${checkResult.ok && checkResult.autoConfirmed ? "rgba(16,185,129,.3)" : checkResult.ok ? "rgba(245,158,11,.3)" : "rgba(239,68,68,.3)"}` }}>
                  <Icon name={checkResult.ok && checkResult.autoConfirmed ? "check-circle" : checkResult.ok ? "clock" : "x-circle"} size={15} style={{ color: checkResult.ok && checkResult.autoConfirmed ? "#10B981" : checkResult.ok ? "#F59E0B" : "#EF4444", flexShrink: 0 }}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-primary)" }}>{checkResult.label}</div>
                    {checkResult.title && checkResult.title !== sku && <div style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 2 }}>{checkResult.title}</div>}
                  </div>
                  {checkResult.ok && <span style={{ fontSize: 11, color: "var(--fg-muted)", flexShrink: 0 }}>Повідомлення відправлено ✓</span>}
                </div>
              )}
            </div>
          )}

          {/* Phone + Name */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 14 }}>
            <div>
              <ModalLabel>Телефон</ModalLabel>
              <ModalInput value={phone} onChange={setPhone} placeholder="+380..." mono/>
            </div>
            <div>
              <ModalLabel>Ім'я клієнта</ModalLabel>
              <ModalInput value={name} onChange={setName} placeholder="Ім'я"/>
            </div>
          </div>

          {/* Order + Product (not for product request) */}
          {type !== "Запит товару" && (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 14 }}>
              <div>
                <ModalLabel>№ замовлення{isOrderRequired ? " *" : ""}</ModalLabel>
                <ModalInput value={orderId} onChange={setOrderId} placeholder={isOrderRequired ? "Обов'язково" : "необов'язково"} mono/>
              </div>
              <div>
                <ModalLabel>Товар</ModalLabel>
                <ModalInput value={sku} onChange={setSku} placeholder="Назва товару"/>
              </div>
            </div>
          )}

          {/* Source */}
          <div style={{ marginBottom: 14 }}>
            <ModalLabel>Джерело</ModalLabel>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {Object.entries(SOURCES).map(([key, s]) => {
                const active = source === key;
                return (
                  <button key={key} type="button" onClick={() => setSource(key)} style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 32, padding: "0 12px", background: active ? "var(--accent-soft)" : "var(--bg-panel)", border: "1px solid " + (active ? "var(--accent)" : "var(--border-default)"), color: active ? "var(--fg-primary)" : "var(--fg-secondary)", borderRadius: 8, fontSize: 12, fontWeight: 500, cursor: "pointer", fontFamily: "inherit" }}>
                    <span style={{ color: s.color, display: "inline-flex" }}><Icon name={s.icon} size={13}/></span>
                    {s.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Note */}
          <div style={{ marginBottom: 14 }}>
            <ModalLabel>{type === "Запит товару" ? "Деталі запиту" : "Суть заявки"}</ModalLabel>
            <textarea value={note} onChange={e => setNote(e.target.value)} placeholder="Що саме питає клієнт..." rows={3} style={{ width: "100%", boxSizing: "border-box", padding: "10px 12px", background: "var(--bg-panel)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 8, fontSize: 13, outline: "none", fontFamily: "inherit", resize: "vertical", minHeight: 70 }}/>
          </div>

          {/* Comment */}
          <div>
            <ModalLabel>Внутрішній коментар <span style={{ color: "var(--fg-muted)", fontWeight: 400, textTransform: "none", letterSpacing: 0 }}>· необов'язково</span></ModalLabel>
            <ModalInput value={comment} onChange={setComment} placeholder="Видно лише менеджерам"/>
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: "14px 22px", borderTop: "1px solid var(--border-subtle)", display: "flex", gap: 10, alignItems: "center" }}>
          <div style={{ flex: 1, fontSize: 11, color: "var(--fg-muted)" }}>
            <kbd style={kbd}>Esc</kbd> закрити &nbsp; <kbd style={kbd}>Enter</kbd> зберегти
          </div>
          <Button variant="secondary" size="md" onClick={onClose}>Скасувати</Button>
          <Button variant="primary" size="md" leftIcon="check" onClick={submit} disabled={!isValid}>{isEdit ? "Зберегти" : "Створити заявку"}</Button>
        </div>
      </form>
    </div>
  );
}

function ModalLabel({ children }) {
  return <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>{children}</div>;
}
function ModalInput({ value, onChange, placeholder, mono }) {
  return (
    <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} style={{ width: "100%", height: 38, boxSizing: "border-box", padding: "0 12px", background: "var(--bg-panel)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 8, fontSize: 13, outline: "none", fontFamily: mono ? "var(--font-mono)" : "inherit", fontVariantNumeric: mono ? "tabular-nums" : "normal" }}/>
  );
}

// ─────────────────────────────────────────────────────────────────
// Webhook / incoming call popup (desktop — top right slide in)
// ─────────────────────────────────────────────────────────────────
function callOrderStatusStyle(status) {
  const s = (status || '').toLowerCase();
  if (s.includes('нов')) return { bg: 'rgba(16,185,129,.15)', color: '#10B981' };
  if (s.includes('скасов') || s.includes('відмов') || s.includes('поверн')) return { bg: 'rgba(239,68,68,.15)', color: '#F87171' };
  if (s.includes('відправ') || s.includes('у дорозі')) return { bg: 'rgba(168,85,247,.15)', color: '#C084FC' };
  if (s.includes('виконан') || s.includes('доставлен')) return { bg: 'rgba(100,116,139,.15)', color: '#94A3B8' };
  return { bg: 'rgba(99,102,241,.15)', color: '#818CF8' };
}

function fmtLtv(n) {
  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ' ') + ' ₴';
}

function WebhookPopup({ caller, manager, onClose, onCreateLead, onOpenOrders, orders, loadingOrders }) {
  const clientName   = orders?.length ? (orders[0].delivery_name || null) : null;
  const initials     = clientName ? clientName.split(/\s+/).slice(0, 2).map(w => (w[0] || '').toUpperCase()).join('') : null;
  const ltv          = (orders || []).reduce((s, o) => s + (o.total_default || 0) + (o.payment_price || 0), 0);
  const lastRaw      = orders?.length ? orders[0].stat_created : null;
  const lastDaysAgo  = lastRaw ? Math.floor((Date.now() - new Date(lastRaw.replace(' ', 'T'))) / 86400000) : null;
  const isVip        = ltv >= 30000;
  const isRegular    = (orders?.length || 0) >= 3;

  return (
    <div style={{ position: "fixed", top: 76, right: 24, width: 384, maxHeight: "calc(100vh - 96px)", background: "var(--bg-raised)", border: "1px solid var(--border-default)", borderRadius: 14, boxShadow: "0 24px 60px rgba(0,0,0,.55)", zIndex: 150, display: "flex", flexDirection: "column", overflow: "hidden", animation: "webhookSlide 220ms cubic-bezier(.2,0,0,1)" }}>
      <style>{`
        @keyframes webhookSlide { from { transform: translateX(20px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
        @keyframes ringPulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(16,185,129,.5); } 50% { box-shadow: 0 0 0 9px rgba(16,185,129,0); } }
        .wh-pulse { animation: ringPulse 1.5s ease-in-out infinite; }
      `}</style>

      {/* Header */}
      <div style={{ padding: "14px 16px", background: "linear-gradient(135deg, rgba(16,185,129,.2), rgba(16,185,129,.06))", borderBottom: "1px solid rgba(16,185,129,.18)", display: "flex", alignItems: "center", gap: 10 }}>
        <div className="wh-pulse" style={{ width: 36, height: 36, borderRadius: "50%", background: "#10B981", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <Icon name="phone-incoming" size={16} color="#fff"/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "#6EE7B7" }}>Вхідний дзвінок</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 15, fontWeight: 700, color: "var(--fg-primary)", fontVariantNumeric: "tabular-nums" }}>{fmtPhone(caller)}</div>
          {manager && <div style={{ fontSize: 11, color: "rgba(110,231,183,.7)", marginTop: 1 }}>З'єднано з: {manager}</div>}
        </div>
        <button onClick={onClose} style={{ width: 28, height: 28, border: 0, background: "rgba(0,0,0,.2)", color: "rgba(255,255,255,.6)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="x" size={14}/>
        </button>
      </div>

      <div style={{ flex: 1, overflowY: "auto" }}>
        {/* Client card */}
        {loadingOrders ? (
          <div style={{ padding: "18px 16px", display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 42, height: 42, borderRadius: "50%", background: "var(--bg-panel)", flexShrink: 0 }}/>
            <div style={{ flex: 1 }}>
              <div style={{ height: 13, width: "55%", background: "var(--bg-panel)", borderRadius: 4, marginBottom: 7 }}/>
              <div style={{ height: 10, width: "80%", background: "var(--bg-panel)", borderRadius: 4 }}/>
            </div>
          </div>
        ) : clientName ? (
          <div style={{ padding: "14px 16px", borderBottom: "1px solid var(--border-subtle)" }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
              <div style={{ width: 42, height: 42, borderRadius: "50%", background: "linear-gradient(135deg,#6366F1,#8B5CF6)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, fontWeight: 700, color: "#fff", flexShrink: 0 }}>
                {initials || '?'}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-primary)", marginBottom: 5 }}>{clientName}</div>
                <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 4, marginBottom: 10 }}>
                  {isVip && <span style={{ display: "inline-block", padding: "2px 7px", borderRadius: 4, fontSize: 10, fontWeight: 700, background: "rgba(245,158,11,.18)", color: "#F59E0B" }}>VIP</span>}
                  {isRegular && <span style={{ display: "inline-block", padding: "2px 7px", borderRadius: 4, fontSize: 10, fontWeight: 600, background: "rgba(99,102,241,.15)", color: "#818CF8" }}>Постійний клієнт</span>}
                  {lastDaysAgo !== null && <span style={{ fontSize: 11, color: "var(--fg-muted)" }}>· {lastDaysAgo === 0 ? 'остання заявка сьогодні' : `останнє замовлення ${lastDaysAgo} дн. тому`}</span>}
                </div>
                <div style={{ display: "flex", gap: 16 }}>
                  <div>
                    <div style={{ fontSize: 16, fontWeight: 700, color: "var(--fg-primary)", fontVariantNumeric: "tabular-nums" }}>{orders.length}</div>
                    <div style={{ fontSize: 10, color: "var(--fg-muted)" }}>Замовлень</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 16, fontWeight: 700, color: "var(--fg-primary)", fontVariantNumeric: "tabular-nums" }}>{fmtLtv(ltv)}</div>
                    <div style={{ fontSize: 10, color: "var(--fg-muted)" }}>LTV</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div style={{ padding: "16px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ width: 42, height: 42, borderRadius: "50%", background: "var(--bg-panel)", border: "1px dashed var(--border-default)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name="user" size={18} style={{ color: "var(--fg-muted)" }}/>
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-secondary)" }}>Новий клієнт</div>
              <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>Замовлень не знайдено</div>
            </div>
          </div>
        )}

        {/* Orders list */}
        {!loadingOrders && orders !== null && orders.length > 0 && (
          <div>
            {orders.slice(0, 4).map(o => {
              const prod = (o.products?.[0]?.title || '—');
              const prodShort = prod.length > 28 ? prod.slice(0, 28) + '…' : prod;
              const st = callOrderStatusStyle(o._status);
              return (
                <div key={o.order_id} style={{ padding: "10px 16px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums", minWidth: 38, flexShrink: 0 }}>#{o.order_id}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 500, color: "var(--fg-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{prodShort}</div>
                    <div style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 1 }}>{fmtDate(o.stat_created)}</div>
                  </div>
                  <span style={{ display: "inline-block", padding: "2px 7px", borderRadius: 4, fontSize: 10, fontWeight: 600, background: st.bg, color: st.color, flexShrink: 0, maxWidth: 90, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o._status || '—'}</span>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Actions */}
      <div style={{ padding: "12px 16px", borderTop: "1px solid var(--border-subtle)", display: "flex", flexDirection: "column", gap: 8 }}>
        <button onClick={onCreateLead} style={{ width: "100%", height: 40, border: 0, borderRadius: 10, background: "var(--accent)", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7 }}>
          <Icon name="plus" size={14}/> Створити заявку
        </button>
        <div style={{ display: "flex", gap: 6 }}>
          <button onClick={onOpenOrders} style={{ flex: 1, height: 34, border: "1px solid var(--border-default)", borderRadius: 8, background: "var(--bg-panel)", color: "var(--fg-primary)", cursor: "pointer", fontFamily: "inherit", fontSize: 12, fontWeight: 500, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 5 }}>
            <Icon name="user" size={13}/> Картка клієнта
          </button>
          <button onClick={onClose} style={{ flex: 1, height: 34, border: "1px solid var(--border-default)", borderRadius: 8, background: "var(--bg-panel)", color: "var(--fg-secondary)", cursor: "pointer", fontFamily: "inherit", fontSize: 12, fontWeight: 500, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 5 }}>
            <Icon name="phone-off" size={13}/> Скинути
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Mobile card
// ─────────────────────────────────────────────────────────────────
function LeadCardM({ lead, onOpen }) {
  const s = LEAD_STATUSES[lead.status] || LEAD_STATUSES["Нова"];
  const src = SOURCES[lead.source] || SOURCES.site;
  const tone = ageTone(lead.ageMin, lead.status);
  return (
    <div onClick={() => onOpen(lead)} style={{ padding: "12px 14px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 12, display: "flex", flexDirection: "column", gap: 8, cursor: "pointer" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>#{lead.id}</span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "2px 7px", borderRadius: 4, fontSize: 10, fontWeight: 600, background: `color-mix(in srgb, ${s.dot} 18%, transparent)`, color: s.dot }}>
          <span style={{ width: 5, height: 5, borderRadius: "50%", background: s.dot }}/>
          {s.label}
        </span>
        <div style={{ flex: 1 }}/>
        <span style={{ fontSize: 11, color: tone, fontWeight: 500 }}>{fmtAge(lead.ageMin)} тому</span>
      </div>
      <div style={{ fontSize: 14, fontWeight: 500, color: "var(--fg-primary)", lineHeight: 1.3 }}>
        {lead.type === "Запит товару" ? lead.product : lead.note || lead.product || "—"}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
        <span style={{ color: src.color, display: "inline-flex" }}><Icon name={src.icon} size={12}/></span>
        <span style={{ color: "var(--fg-secondary)" }}>{lead.clientName}</span>
        {lead.phone && <><span style={{ color: "var(--fg-muted)" }}>·</span><span style={{ fontFamily: "var(--font-mono)", color: "var(--fg-muted)", fontSize: 11 }}>{fmtPhone(lead.phone)}</span></>}
      </div>
      {lead.type === "Запит товару" && lead.bot !== "—" && (
        <div style={{ paddingTop: 4, borderTop: "1px solid var(--border-subtle)" }}>
          <BotPill bot={lead.bot}/>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Mobile detail bottom sheet
// ─────────────────────────────────────────────────────────────────
function LeadDetailSheetM({ lead, onClose, onEdit }) {
  if (!lead) return null;
  const s = LEAD_STATUSES[lead.status] || LEAD_STATUSES["Нова"];
  const src = SOURCES[lead.source] || SOURCES.site;
  const tone = ageTone(lead.ageMin, lead.status);

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.6)", zIndex: 50, display: "flex", alignItems: "flex-end" }}>
      <div onClick={e => e.stopPropagation()} style={{ width: "100%", background: "var(--bg-base)", borderTopLeftRadius: 20, borderTopRightRadius: 20, maxHeight: "92%", display: "flex", flexDirection: "column", animation: "slideUp 240ms cubic-bezier(.2,0,0,1)" }}>
        <div style={{ display: "flex", justifyContent: "center", padding: "8px 0 4px" }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--border-default)" }}/>
        </div>
        <div style={{ padding: "8px 18px 14px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg-muted)" }}>#{lead.id}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "3px 8px", borderRadius: 4, fontSize: 11, fontWeight: 600, background: `color-mix(in srgb, ${s.dot} 18%, transparent)`, color: s.dot }}>
            <span style={{ width: 6, height: 6, borderRadius: "50%", background: s.dot }}/>
            {s.label}
          </span>
          <div style={{ flex: 1 }}/>
          <button onClick={() => onEdit(lead._raw)} style={{ width: 30, height: 30, border: "1px solid var(--border-default)", borderRadius: 6, background: "transparent", color: "var(--fg-secondary)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="pencil" size={14}/>
          </button>
          <button onClick={onClose} style={{ width: 30, height: 30, border: 0, background: "var(--bg-panel)", color: "var(--fg-secondary)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="x" size={16}/>
          </button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "16px 18px 24px" }}>
          {/* SLA */}
          <div style={{ padding: "12px 14px", borderRadius: 10, marginBottom: 16, background: `color-mix(in srgb, ${tone} 12%, transparent)`, border: `1px solid color-mix(in srgb, ${tone} 28%, transparent)`, display: "flex", alignItems: "center", gap: 10 }}>
            <Icon name="clock" size={16} style={{ color: tone }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: tone }}>{fmtAge(lead.ageMin)} тому</div>
              <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>{lead.ts}</div>
            </div>
          </div>

          {/* Запит */}
          <div style={{ marginBottom: 16 }}>
            <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>
              {lead.type === "Запит товару" ? "Артикул" : "Суть"}
            </div>
            <div style={{ padding: "12px 14px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 10, fontSize: 14, fontWeight: 500, color: "var(--fg-primary)", lineHeight: 1.4 }}>
              {lead.type === "Запит товару" ? lead.product : lead.note || "—"}
            </div>
          </div>

          {/* Bot */}
          {lead.type === "Запит товару" && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>Бот</div>
              <div style={{ padding: "10px 12px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 10 }}>
                <BotPill bot={lead.bot}/>
              </div>
            </div>
          )}

          {/* Клієнт */}
          {(lead.phone || lead.clientName !== "—") && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>Клієнт</div>
              <div style={{ padding: "12px 14px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 10 }}>
                <div style={{ fontSize: 14, fontWeight: 500, color: "var(--fg-primary)", marginBottom: 4 }}>{lead.clientName}</div>
                {lead.phone && <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{fmtPhone(lead.phone)}</div>}
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 10 }}>
                {[{ icon: "phone", label: "Дзвінок", color: "#10B981" }, { icon: "send", label: "Telegram", color: "#229ED9" }, { icon: "message-circle", label: "Viber", color: "#7B519D" }].map(b => (
                  <button key={b.label} style={{ height: 56, border: "1px solid var(--border-subtle)", borderRadius: 10, background: "var(--bg-panel)", cursor: "pointer", fontFamily: "inherit", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 4, color: "var(--fg-secondary)" }}>
                    <Icon name={b.icon} size={18} style={{ color: b.color }}/>
                    <span style={{ fontSize: 11, fontWeight: 500 }}>{b.label}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Джерело + Менеджер */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>Джерело</div>
              <div style={{ padding: "10px 12px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 10, display: "inline-flex", alignItems: "center", gap: 8, width: "100%", boxSizing: "border-box" }}>
                <Icon name={src.icon} size={14} style={{ color: src.color }}/>
                <span style={{ fontSize: 13, color: "var(--fg-primary)" }}>{src.label}</span>
              </div>
            </div>
            <div>
              <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>Менеджер</div>
              <div style={{ padding: "10px 12px", background: "var(--bg-panel)", border: "1px solid var(--border-subtle)", borderRadius: 10, fontSize: 13, color: lead.manager === "—" ? "var(--fg-muted)" : "var(--fg-primary)" }}>
                {lead.manager === "—" ? "Не призначено" : lead.manager}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Mobile new lead sheet
// ─────────────────────────────────────────────────────────────────
function NewLeadSheetM({ open, onClose, onSave, prefill, userName }) {
  if (!open) return null;
  const [type,        setType]        = useState(prefill?.type   || "Запит товару");
  const [sku,         setSku]         = useState(prefill?.sku    || "");
  const [phone,       setPhone]       = useState(prefill?.phone  || "");
  const [name,        setName]        = useState(prefill?.name   || "");
  const [source,      setSource]      = useState(prefill?.source || "call");
  const [note,        setNote]        = useState(prefill?.note   || "");
  const [orderId,     setOrderId]     = useState(prefill?.orderId|| "");
  const [supplier,    setSupplier]    = useState("");
  const [checking,    setChecking]    = useState(false);
  const [checkResult, setCheckResult] = useState(null);
  const [draftId,     setDraftId]     = useState(prefill?.id || null);
  const isOrderRequired = type === "Гарантія" || type === "Повернення";
  const isValid = type === "Запит товару" ? sku.trim() : (note.trim() && (isOrderRequired ? orderId.trim() : true));

  const handleCheck = async () => {
    if (!sku.trim()) return;
    setChecking(true); setCheckResult(null);
    try {
      let reqId = draftId;
      if (!reqId) {
        const draft = await API.createRequest({ type: "Запит товару", product: sku.trim(), manager: userName || "", skipAutoFind: true });
        reqId = draft.id;
        setDraftId(reqId);
      }
      const result = await API.checkAvailability(sku.trim(), userName, reqId);
      setCheckResult(result);
      if (result.supplierValue) setSupplier(result.supplierValue);
      if (result.article) setSku(result.article);
    } catch {
      setCheckResult({ ok: false, label: "❌ Помилка зв'язку з ботом" });
    } finally { setChecking(false); }
  };

  const submit = () => {
    if (!isValid) return;
    onSave({ type, sku, phone, name, source, note, orderId, supplier, manager: userName || "", draftId });
    onClose();
  };


  const inp = { width: "100%", height: 42, boxSizing: "border-box", padding: "0 12px", background: "var(--bg-panel)", color: "var(--fg-primary)", border: "1px solid var(--border-subtle)", borderRadius: 10, fontSize: 14, outline: "none", fontFamily: "inherit" };
  const lbl = (text) => <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 6 }}>{text}</div>;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.6)", zIndex: 60, display: "flex", alignItems: "flex-end" }}>
      <div onClick={e => e.stopPropagation()} style={{ width: "100%", background: "var(--bg-base)", borderTopLeftRadius: 20, borderTopRightRadius: 20, maxHeight: "92%", display: "flex", flexDirection: "column", animation: "slideUp 240ms cubic-bezier(.2,0,0,1)" }}>
        <div style={{ display: "flex", justifyContent: "center", padding: "8px 0 4px" }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--border-default)" }}/>
        </div>
        <div style={{ padding: "8px 18px 14px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: "var(--accent-soft)", color: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="plus" size={15}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg-primary)" }}>Нова заявка</div>
            <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>Зафіксуйте звернення</div>
          </div>
          <button onClick={onClose} style={{ width: 30, height: 30, border: 0, background: "var(--bg-panel)", color: "var(--fg-secondary)", borderRadius: 6, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={16}/></button>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: "16px 18px 12px" }}>
          {lbl("Тип заявки")}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 16 }}>
            {LEAD_TYPES.map(lt => {
              const on = type === lt.key;
              return (
                <button key={lt.key} onClick={() => setType(lt.key)} style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 12px", borderRadius: 10, cursor: "pointer", fontFamily: "inherit", background: on ? "var(--accent-soft)" : "var(--bg-panel)", border: "1px solid " + (on ? "var(--accent)" : "var(--border-subtle)"), color: on ? "var(--fg-primary)" : "var(--fg-secondary)", fontSize: 12, fontWeight: 500 }}>
                  <Icon name={lt.icon} size={14} style={{ color: on ? "var(--accent)" : "var(--fg-muted)" }}/>
                  {lt.key}
                </button>
              );
            })}
          </div>
          {type === "Запит товару" && (
            <div style={{ marginBottom: 14 }}>
              {lbl("Артикул / назва товару")}
              <div style={{ display: "flex", gap: 8 }}>
                <input value={sku} onChange={e => { setSku(e.target.value); setCheckResult(null); }} placeholder="iPhone 15 Pro Max 256GB" style={{ ...inp, flex: 1 }}/>
                <button type="button" onClick={handleCheck} disabled={!sku.trim() || checking} style={{ height: 42, padding: "0 14px", border: 0, borderRadius: 10, background: sku.trim() && !checking ? "var(--accent)" : "var(--bg-raised)", color: sku.trim() && !checking ? "#fff" : "var(--fg-muted)", fontSize: 13, fontWeight: 600, cursor: !sku.trim() || checking ? "not-allowed" : "pointer", fontFamily: "inherit", flexShrink: 0, display: "inline-flex", alignItems: "center", gap: 5 }}>
                  <Icon name={checking ? "loader" : "zap"} size={13}/>
                  {checking ? "…" : "Перевірити"}
                </button>
              </div>
              {checkResult && (
                <div style={{ marginTop: 8, padding: "10px 12px", borderRadius: 10, display: "flex", alignItems: "center", gap: 8, background: checkResult.ok && checkResult.autoConfirmed ? "rgba(16,185,129,.1)" : checkResult.ok ? "rgba(245,158,11,.1)" : "rgba(239,68,68,.1)", border: `1px solid ${checkResult.ok && checkResult.autoConfirmed ? "rgba(16,185,129,.3)" : checkResult.ok ? "rgba(245,158,11,.3)" : "rgba(239,68,68,.3)"}` }}>
                  <Icon name={checkResult.ok && checkResult.autoConfirmed ? "check-circle" : checkResult.ok ? "clock" : "x-circle"} size={15} style={{ color: checkResult.ok && checkResult.autoConfirmed ? "#10B981" : checkResult.ok ? "#F59E0B" : "#EF4444", flexShrink: 0 }}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-primary)" }}>{checkResult.label}</div>
                    {checkResult.title && <div style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 1 }}>{checkResult.title}</div>}
                  </div>
                </div>
              )}
            </div>
          )}
          {type !== "Запит товару" && (
            <>{lbl("№ замовлення" + (isOrderRequired ? " *" : ""))}
            <input value={orderId} onChange={e => setOrderId(e.target.value)} placeholder={isOrderRequired ? "Обов'язково" : "необов'язково"} style={{ ...inp, fontFamily: "var(--font-mono)", marginBottom: 12 }}/>
            </>
          )}
          {lbl("Телефон")}
          <input value={phone} onChange={e => setPhone(e.target.value)} placeholder="+380..." style={{ ...inp, fontFamily: "var(--font-mono)", marginBottom: 12 }} inputMode="tel"/>
          {lbl("Ім'я клієнта")}
          <input value={name} onChange={e => setName(e.target.value)} placeholder="Ім'я" style={{ ...inp, marginBottom: 12 }}/>
          {lbl("Джерело")}
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 12 }}>
            {Object.entries(SOURCES).map(([k, s]) => {
              const on = source === k;
              return (
                <button key={k} onClick={() => setSource(k)} style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 32, padding: "0 12px", background: on ? "var(--accent-soft)" : "var(--bg-panel)", border: "1px solid " + (on ? "var(--accent)" : "var(--border-subtle)"), color: on ? "var(--fg-primary)" : "var(--fg-secondary)", borderRadius: 999, fontSize: 12, fontWeight: 500, cursor: "pointer", fontFamily: "inherit" }}>
                  <Icon name={s.icon} size={12} style={{ color: s.color }}/>{s.label}
                </button>
              );
            })}
          </div>
          {lbl(type === "Запит товару" ? "Деталі" : "Суть заявки")}
          <textarea value={note} onChange={e => setNote(e.target.value)} placeholder="Що саме питає клієнт..." rows={3} style={{ ...inp, height: "auto", paddingTop: 10, paddingBottom: 10, resize: "none", minHeight: 70 }}/>
        </div>
        <div style={{ padding: "12px 18px 24px", borderTop: "1px solid var(--border-subtle)", display: "flex", gap: 8 }}>
          <button onClick={onClose} style={{ flex: 1, height: 44, border: "1px solid var(--border-default)", borderRadius: 10, background: "var(--bg-panel)", color: "var(--fg-primary)", fontSize: 14, fontWeight: 500, cursor: "pointer", fontFamily: "inherit" }}>Скасувати</button>
          <button onClick={submit} disabled={!isValid} style={{ flex: 1.4, height: 44, border: 0, borderRadius: 10, background: isValid ? "var(--accent)" : "var(--bg-raised)", color: isValid ? "#fff" : "var(--fg-muted)", fontSize: 14, fontWeight: 600, cursor: isValid ? "pointer" : "not-allowed", fontFamily: "inherit", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
            <Icon name="check" size={16}/>Створити
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// Mobile webhook bottom sheet
// ─────────────────────────────────────────────────────────────────
function WebhookSheetM({ open, caller, manager, onClose, onCreateLead, onOpenOrders, orders, loadingOrders }) {
  if (!open) return null;
  const clientName  = orders?.length ? (orders[0].delivery_name || null) : null;
  const initials    = clientName ? clientName.split(/\s+/).slice(0, 2).map(w => (w[0] || '').toUpperCase()).join('') : null;
  const ltv         = (orders || []).reduce((s, o) => s + (o.total_default || 0) + (o.payment_price || 0), 0);
  const lastRaw     = orders?.length ? orders[0].stat_created : null;
  const lastDaysAgo = lastRaw ? Math.floor((Date.now() - new Date(lastRaw.replace(' ', 'T'))) / 86400000) : null;
  const isVip       = ltv >= 30000;
  const isRegular   = (orders?.length || 0) >= 3;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.6)", zIndex: 70, display: "flex", alignItems: "flex-end" }}>
      <style>{`@keyframes ringPulseM{0%,100%{box-shadow:0 0 0 0 rgba(16,185,129,.5)}50%{box-shadow:0 0 0 10px rgba(16,185,129,0)}}.ring-pulse-m{animation:ringPulseM 1.4s ease-in-out infinite}`}</style>
      <div onClick={e => e.stopPropagation()} style={{ width: "100%", background: "var(--bg-base)", borderTopLeftRadius: 20, borderTopRightRadius: 20, maxHeight: "92%", display: "flex", flexDirection: "column", animation: "slideUp 240ms cubic-bezier(.2,0,0,1)" }}>

        {/* Header */}
        <div style={{ padding: "16px 18px 14px", background: "linear-gradient(135deg, rgba(16,185,129,.2), rgba(16,185,129,.04))", borderTopLeftRadius: 20, borderTopRightRadius: 20, display: "flex", alignItems: "center", gap: 12 }}>
          <div className="ring-pulse-m" style={{ width: 40, height: 40, borderRadius: "50%", background: "#10B981", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="phone-incoming" size={18} color="#fff"/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "#6EE7B7" }}>Вхідний дзвінок</div>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 17, fontWeight: 700, color: "var(--fg-primary)", fontVariantNumeric: "tabular-nums" }}>{fmtPhone(caller)}</div>
            {manager && <div style={{ fontSize: 11, color: "rgba(110,231,183,.75)", marginTop: 1 }}>З'єднано з: {manager}</div>}
          </div>
          <button onClick={onClose} style={{ width: 32, height: 32, border: 0, background: "rgba(0,0,0,.25)", color: "rgba(255,255,255,.6)", borderRadius: 8, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="x" size={16}/></button>
        </div>

        <div style={{ flex: 1, overflowY: "auto" }}>
          {/* Client card */}
          {loadingOrders ? (
            <div style={{ padding: "16px 18px", display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: "50%", background: "var(--bg-panel)", flexShrink: 0 }}/>
              <div style={{ flex: 1 }}>
                <div style={{ height: 14, width: "50%", background: "var(--bg-panel)", borderRadius: 4, marginBottom: 8 }}/>
                <div style={{ height: 11, width: "75%", background: "var(--bg-panel)", borderRadius: 4 }}/>
              </div>
            </div>
          ) : clientName ? (
            <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)" }}>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                <div style={{ width: 46, height: 46, borderRadius: "50%", background: "linear-gradient(135deg,#6366F1,#8B5CF6)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 15, fontWeight: 700, color: "#fff", flexShrink: 0 }}>
                  {initials || '?'}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg-primary)", marginBottom: 5 }}>{clientName}</div>
                  <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 5, marginBottom: 10 }}>
                    {isVip && <span style={{ padding: "2px 8px", borderRadius: 4, fontSize: 10, fontWeight: 700, background: "rgba(245,158,11,.18)", color: "#F59E0B" }}>VIP</span>}
                    {isRegular && <span style={{ padding: "2px 8px", borderRadius: 4, fontSize: 10, fontWeight: 600, background: "rgba(99,102,241,.15)", color: "#818CF8" }}>Постійний клієнт</span>}
                    {lastDaysAgo !== null && <span style={{ fontSize: 12, color: "var(--fg-muted)" }}>· {lastDaysAgo === 0 ? 'остання заявка сьогодні' : `останнє замовлення ${lastDaysAgo} дн. тому`}</span>}
                  </div>
                  <div style={{ display: "flex", gap: 20 }}>
                    <div>
                      <div style={{ fontSize: 17, fontWeight: 700, color: "var(--fg-primary)", fontVariantNumeric: "tabular-nums" }}>{orders.length}</div>
                      <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>Замовлень</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 17, fontWeight: 700, color: "var(--fg-primary)", fontVariantNumeric: "tabular-nums" }}>{fmtLtv(ltv)}</div>
                      <div style={{ fontSize: 11, color: "var(--fg-muted)" }}>LTV</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 46, height: 46, borderRadius: "50%", background: "var(--bg-panel)", border: "1px dashed var(--border-default)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Icon name="user" size={20} style={{ color: "var(--fg-muted)" }}/>
              </div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, color: "var(--fg-secondary)" }}>Новий клієнт</div>
                <div style={{ fontSize: 12, color: "var(--fg-muted)" }}>Замовлень не знайдено</div>
              </div>
            </div>
          )}

          {/* Orders list */}
          {!loadingOrders && orders?.length > 0 && orders.slice(0, 4).map(o => {
            const prod = (o.products?.[0]?.title || '—');
            const prodShort = prod.length > 28 ? prod.slice(0, 28) + '…' : prod;
            const st = callOrderStatusStyle(o._status);
            return (
              <div key={o.order_id} style={{ padding: "11px 18px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums", minWidth: 40, flexShrink: 0 }}>#{o.order_id}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "var(--fg-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{prodShort}</div>
                  <div style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 1 }}>{fmtDate(o.stat_created)}</div>
                </div>
                <span style={{ padding: "2px 8px", borderRadius: 4, fontSize: 10, fontWeight: 600, background: st.bg, color: st.color, flexShrink: 0, maxWidth: 90, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{o._status || '—'}</span>
              </div>
            );
          })}
        </div>

        {/* Actions */}
        <div style={{ padding: "12px 18px 28px", borderTop: "1px solid var(--border-subtle)", display: "flex", flexDirection: "column", gap: 8 }}>
          <button onClick={onCreateLead} style={{ width: "100%", height: 48, border: 0, borderRadius: 12, background: "var(--accent)", color: "#fff", fontSize: 15, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
            <Icon name="plus" size={16}/>Створити заявку
          </button>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={onOpenOrders} style={{ flex: 1, height: 42, border: "1px solid var(--border-default)", borderRadius: 10, background: "var(--bg-panel)", color: "var(--fg-primary)", fontSize: 13, fontWeight: 500, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
              <Icon name="user" size={14}/>Картка клієнта
            </button>
            <button onClick={onClose} style={{ flex: 1, height: 42, border: "1px solid var(--border-default)", borderRadius: 10, background: "var(--bg-panel)", color: "var(--fg-secondary)", fontSize: 13, fontWeight: 500, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
              <Icon name="phone-off" size={14}/>Скинути
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────
// IncomingCallPopup — wrapper (exported to App)
// ─────────────────────────────────────────────────────────────────
function IncomingCallPopup({ caller, manager, onClose, onOpenRequests, onOpenOrders, showToast, userName, isMobile }) {
  const [orders,        setOrders]        = useState(null);
  const [loadingOrders, setLoadingOrders] = useState(true);
  const [newOpen,       setNewOpen]       = useState(false);

  useEffect(() => {
    if (!caller) return;
    setLoadingOrders(true);
    API.searchOrdersByPhone(caller)
      .then(({ orders }) => setOrders(orders || []))
      .catch(() => setOrders([]))
      .finally(() => setLoadingOrders(false));
  }, [caller]);

  const handleCreateLead = async (form) => {
    try {
      await API.createRequest({ ...form, phone: caller, source: "Дзвінок", manager: form.manager || userName });
      showToast("Заявку створено");
      setNewOpen(false);
      onOpenRequests();
    } catch { showToast("Помилка створення заявки", "error"); }
  };

  if (isMobile) {
    return (
      <>
        <WebhookSheetM open={!newOpen} caller={caller} manager={manager} onClose={onClose} onCreateLead={() => setNewOpen(true)} onOpenOrders={onOpenOrders} orders={orders} loadingOrders={loadingOrders}/>
        <NewLeadSheetM open={newOpen} onClose={() => setNewOpen(false)} onSave={handleCreateLead} prefill={{ phone: caller }} userName={userName}/>
      </>
    );
  }

  return (
    <>
      {!newOpen && (
        <WebhookPopup caller={caller} manager={manager} onClose={onClose} onCreateLead={() => setNewOpen(true)} onOpenOrders={onOpenOrders} orders={orders} loadingOrders={loadingOrders}/>
      )}
      {newOpen && (
        <NewLeadModal open={true} onClose={() => setNewOpen(false)} onSave={handleCreateLead} prefill={{ phone: caller, source: "call" }} userName={userName}/>
      )}
    </>
  );
}

// ─────────────────────────────────────────────────────────────────
// Main Requests page
// ─────────────────────────────────────────────────────────────────
function Requests({ isMobile, showToast, userName }) {
  const [leads,     setLeads]     = useState([]);
  const [loading,       setLoading]       = useState(true);
  const [filter,        setFilter]        = useState("all");
  const [typeFilter,    setTypeFilter]    = useState("all");
  const [managerFilter, setManagerFilter] = useState("all");
  const [query,         setQuery]         = useState("");
  const [selected,      setSelected]      = useState(null);
  const [panelOpen,     setPanelOpen]     = useState(true);
  const [sort,          setSort]          = useState("newest");
  const [newOpen,       setNewOpen]       = useState(false);
  const [detailOpen,    setDetailOpen]    = useState(false);
  const [editData,      setEditData]      = useState(null);
  const [dropMgr,       setDropMgr]       = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const { requests } = await API.getRequests();
      setLeads((requests || []).map(toLeadShape));
    } catch { showToast("Помилка завантаження заявок", "error"); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  const managers = [...new Set(leads.map(l => l.manager).filter(m => m && m !== "—"))].sort();

  const filtered = leads
    .filter(l => filter        === "all" || l.status  === filter)
    .filter(l => typeFilter    === "all" || l.type    === typeFilter)
    .filter(l => managerFilter === "all" || l.manager === managerFilter)
    .filter(l => {
      if (!query) return true;
      const q = query.toLowerCase();
      return (l.product + " " + l.note + " " + l.clientName + " " + l.phone).toLowerCase().includes(q);
    })
    .sort((a, b) => sort === "newest" ? a.ageMin - b.ageMin : b.ageMin - a.ageMin);

  const handleSelect = (lead) => { setSelected(lead); setPanelOpen(true); if (isMobile) setDetailOpen(true); };

  const handleStatusChange = async (id, status) => {
    try {
      await API.updateRequest(id, { status });
      setLeads(ls => ls.map(l => l.id == id ? { ...l, status } : l));
      if (selected?.id == id) setSelected(s => s ? { ...s, status } : s);
      showToast("Статус оновлено");
    } catch { showToast("Помилка", "error"); }
  };

  const handleSaveNew = async (form) => {
    try {
      const data = {
        type:     form.type,
        product:  form.sku || form.product || "",
        phone:    form.phone,
        name:     form.name,
        source:   SOURCES[form.source]?.label || "CRM",
        desc:     form.note || "",
        comment:  form.comment || "",
        orderId:  form.orderId || "",
        manager:  form.manager || userName || "",
        supplier: form.supplier || "",
      };
      if (form.draftId) {
        await API.updateRequest(form.draftId, data);
      } else {
        await API.createRequest(data);
      }
      showToast("Заявку створено");
      setNewOpen(false);
      load();
    } catch { showToast("Помилка збереження", "error"); }
  };

  // Source reverse-map для редагування
  const sourceReverse = Object.fromEntries(Object.entries(SOURCES).map(([k, v]) => [v.label, k]));

  // ── Mobile ────────────────────────────────────────────────────
  // Кількість активних фільтрів (для бейджа)
  const activeFiltersCount = (filter !== "all" ? 1 : 0) + (typeFilter !== "all" ? 1 : 0) + (managerFilter !== "all" ? 1 : 0);
  const [filterSheetOpen, setFilterSheetOpen] = useState(false);

  const handleSaveEdit = async (form) => {
    if (!editData) return;
    try {
      const data = {
        type:    form.type,
        product: form.sku || "",
        phone:   form.phone,
        name:    form.name,
        source:  SOURCES[form.source]?.label || editData.source || "CRM",
        desc:    form.note || "",
        comment: form.comment || "",
        orderId: form.orderId || "",
        manager: form.manager || userName || "",
        status:  editData.status,
      };
      await API.updateRequest(editData.id, data);
      showToast("Заявку оновлено");
      setEditData(null);
      load();
    } catch { showToast("Помилка збереження", "error"); }
  };

  if (isMobile) {
    return (
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", position: "relative" }}>
        <style>{`
          @keyframes leadPulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.4;transform:scale(.85)}}
          .lead-pulse{animation:leadPulse 1.6s ease-in-out infinite}
          @keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}
          .no-scrollbar::-webkit-scrollbar{display:none}.no-scrollbar{scrollbar-width:none}
        `}</style>

        <LeadsKPIM leads={leads}/>

        {/* Search + filter button + refresh */}
        <div style={{ padding: "8px 16px", flexShrink: 0, display: "flex", gap: 8 }}>
          <div style={{ position: "relative", flex: 1 }}>
            <Icon name="search" size={13} style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--fg-muted)" }}/>
            <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Пошук заявок..." style={{ width: "100%", height: 36, boxSizing: "border-box", padding: "0 10px 0 30px", background: "var(--bg-panel)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 8, fontSize: 13, outline: "none", fontFamily: "inherit" }}/>
          </div>
          {/* Filter button with badge */}
          <button onClick={() => setFilterSheetOpen(true)} style={{ position: "relative", width: 36, height: 36, border: "1px solid " + (activeFiltersCount > 0 ? "var(--accent)" : "var(--border-default)"), borderRadius: 8, background: activeFiltersCount > 0 ? "var(--accent-soft)" : "var(--bg-panel)", color: activeFiltersCount > 0 ? "var(--accent)" : "var(--fg-secondary)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="sliders-horizontal" size={16}/>
            {activeFiltersCount > 0 && <span style={{ position: "absolute", top: -4, right: -4, width: 16, height: 16, borderRadius: "50%", background: "var(--accent)", color: "#fff", fontSize: 10, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{activeFiltersCount}</span>}
          </button>
          {/* Refresh in toolbar */}
          <button onClick={load} style={{ width: 36, height: 36, border: "1px solid var(--border-default)", borderRadius: 8, background: "var(--bg-panel)", color: "var(--fg-secondary)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="refresh-cw" size={15}/>
          </button>
        </div>

        {/* Active filter tags */}
        {activeFiltersCount > 0 && (
          <div style={{ padding: "0 16px 6px", display: "flex", gap: 6, overflowX: "auto", flexShrink: 0 }} className="no-scrollbar">
            {filter !== "all" && (
              <button onClick={() => setFilter("all")} style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 24, padding: "0 8px", background: "var(--accent-soft)", border: "1px solid var(--accent)", color: "var(--accent)", borderRadius: 999, fontSize: 11, fontWeight: 500, cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap" }}>
                {filter} <Icon name="x" size={11}/>
              </button>
            )}
            {typeFilter !== "all" && (
              <button onClick={() => setTypeFilter("all")} style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 24, padding: "0 8px", background: "var(--accent-soft)", border: "1px solid var(--accent)", color: "var(--accent)", borderRadius: 999, fontSize: 11, fontWeight: 500, cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap" }}>
                {typeFilter} <Icon name="x" size={11}/>
              </button>
            )}
            {managerFilter !== "all" && (
              <button onClick={() => setManagerFilter("all")} style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 24, padding: "0 8px", background: "var(--accent-soft)", border: "1px solid var(--accent)", color: "var(--accent)", borderRadius: 999, fontSize: 11, fontWeight: 500, cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap" }}>
                {managerFilter} <Icon name="x" size={11}/>
              </button>
            )}
          </div>
        )}

        <div style={{ flex: 1, overflowY: "auto", padding: "8px 16px 88px", display: "flex", flexDirection: "column", gap: 8 }}>
          {loading ? (
            <div style={{ padding: 40, textAlign: "center", color: "var(--fg-muted)", fontSize: 14 }}>Завантаження…</div>
          ) : filtered.length === 0 ? (
            <div style={{ padding: 40, textAlign: "center", color: "var(--fg-muted)", fontSize: 14 }}>{leads.length === 0 ? "Заявок ще немає" : "Заявок не знайдено"}</div>
          ) : (
            filtered.map(l => <LeadCardM key={l.id} lead={l} onOpen={handleSelect}/>)
          )}
        </div>

        {/* FAB — тільки нова заявка */}
        <button onClick={() => setNewOpen(true)} style={{ position: "fixed", right: 16, bottom: "calc(var(--tabbar-total) + 16px)", width: 56, height: 56, borderRadius: "50%", border: 0, background: "var(--accent)", boxShadow: "0 6px 18px rgba(99,102,241,.45)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", zIndex: 40 }}>
          <Icon name="plus" size={24}/>
        </button>

        {/* Filter bottom sheet */}
        {filterSheetOpen && (
          <div onClick={() => setFilterSheetOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.5)", zIndex: 100, display: "flex", alignItems: "flex-end" }}>
            <div onClick={e => e.stopPropagation()} style={{ width: "100%", background: "var(--bg-base)", borderTopLeftRadius: 20, borderTopRightRadius: 20, padding: "0 0 calc(16px + env(safe-area-inset-bottom,0px))", animation: "slideUp 200ms cubic-bezier(.2,0,0,1)" }}>
              <div style={{ display: "flex", justifyContent: "center", padding: "12px 0 8px" }}>
                <div style={{ width: 36, height: 4, borderRadius: 2, background: "var(--border-default)" }}/>
              </div>
              <div style={{ padding: "0 18px 4px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <span style={{ fontSize: 16, fontWeight: 600, color: "var(--fg-primary)" }}>Фільтри</span>
                {activeFiltersCount > 0 && (
                  <button onClick={() => { setFilter("all"); setTypeFilter("all"); setManagerFilter("all"); }} style={{ height: 28, padding: "0 10px", border: "1px solid var(--border-default)", borderRadius: 8, background: "transparent", color: "var(--fg-secondary)", fontSize: 12, cursor: "pointer", fontFamily: "inherit" }}>Скинути всі</button>
                )}
              </div>
              <div style={{ padding: "12px 18px", display: "flex", flexDirection: "column", gap: 18 }}>
                {/* Статус */}
                <div>
                  <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 8 }}>Статус</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                    {[{ key: "all", label: "Всі статуси" }, ...STATUS_NAMES.map(s => ({ key: s, label: LEAD_STATUSES[s].label, dot: LEAD_STATUSES[s].dot }))].map(c => (
                      <button key={c.key} onClick={() => setFilter(c.key)} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", border: "1px solid " + (filter === c.key ? "var(--accent)" : "var(--border-subtle)"), borderRadius: 10, background: filter === c.key ? "var(--accent-soft)" : "var(--bg-panel)", cursor: "pointer", fontFamily: "inherit" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          {c.dot && <span style={{ width: 8, height: 8, borderRadius: "50%", background: c.dot }}/>}
                          <span style={{ fontSize: 14, color: filter === c.key ? "var(--accent)" : "var(--fg-primary)", fontWeight: filter === c.key ? 600 : 400 }}>{c.label}</span>
                        </div>
                        {filter === c.key && <Icon name="check" size={16} style={{ color: "var(--accent)" }}/>}
                      </button>
                    ))}
                  </div>
                </div>
                {/* Тип */}
                <div>
                  <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 8 }}>Тип заявки</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                    {[{ key: "all", label: "Всі типи" }, ...LEAD_TYPES.map(lt => ({ key: lt.key, label: lt.key, icon: lt.icon }))].map(t => (
                      <button key={t.key} onClick={() => setTypeFilter(t.key)} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", border: "1px solid " + (typeFilter === t.key ? "var(--accent)" : "var(--border-subtle)"), borderRadius: 10, background: typeFilter === t.key ? "var(--accent-soft)" : "var(--bg-panel)", cursor: "pointer", fontFamily: "inherit" }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          {t.icon && <Icon name={t.icon} size={15} style={{ color: typeFilter === t.key ? "var(--accent)" : "var(--fg-muted)" }}/>}
                          <span style={{ fontSize: 14, color: typeFilter === t.key ? "var(--accent)" : "var(--fg-primary)", fontWeight: typeFilter === t.key ? 600 : 400 }}>{t.label}</span>
                        </div>
                        {typeFilter === t.key && <Icon name="check" size={16} style={{ color: "var(--accent)" }}/>}
                      </button>
                    ))}
                  </div>
                </div>
                {/* Менеджер */}
                {managers.length > 0 && (
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 8 }}>Відповідальний</div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                      {[{ key: "all", label: "Всі менеджери" }, ...managers.map(m => ({ key: m, label: m }))].map(m => (
                        <button key={m.key} onClick={() => setManagerFilter(m.key)} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", border: "1px solid " + (managerFilter === m.key ? "var(--accent)" : "var(--border-subtle)"), borderRadius: 10, background: managerFilter === m.key ? "var(--accent-soft)" : "var(--bg-panel)", cursor: "pointer", fontFamily: "inherit" }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                            {m.key !== "all" && <Avatar name={m.label} size={22}/>}
                            <span style={{ fontSize: 14, color: managerFilter === m.key ? "var(--accent)" : "var(--fg-primary)", fontWeight: managerFilter === m.key ? 600 : 400 }}>{m.label}</span>
                          </div>
                          {managerFilter === m.key && <Icon name="check" size={16} style={{ color: "var(--accent)" }}/>}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
              <div style={{ padding: "4px 18px 0" }}>
                <button onClick={() => setFilterSheetOpen(false)} style={{ width: "100%", height: 50, border: 0, borderRadius: 12, background: "var(--accent)", color: "#fff", fontSize: 15, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>
                  Застосувати {filtered.length > 0 ? `(${filtered.length})` : ""}
                </button>
              </div>
            </div>
          </div>
        )}

        {detailOpen && selected && <LeadDetailSheetM lead={selected} onClose={() => setDetailOpen(false)} onEdit={(raw) => { setDetailOpen(false); setEditData(raw); }}/>}
        <NewLeadSheetM open={newOpen} onClose={() => setNewOpen(false)} onSave={handleSaveNew} userName={userName}/>
        {editData && (
          <NewLeadSheetM
            open={true}
            onClose={() => setEditData(null)}
            onSave={handleSaveEdit}
            prefill={{ id: editData.id, type: editData.type, sku: editData.product, phone: editData.phone, name: editData.name, source: sourceReverse[editData.source] || "site", note: editData.desc, orderId: editData.orderId }}
            userName={userName}
          />
        )}
      </div>
    );
  }

  // ── Desktop ───────────────────────────────────────────────────
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, minHeight: 0 }}>
      <style>{`
        .lead-row:hover { background: var(--bg-hover) !important; }
        @keyframes leadPulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .4; transform: scale(.85); } }
        .lead-pulse { animation: leadPulse 1.6s ease-in-out infinite; }
      `}</style>

      <LeadsKPI leads={leads}/>

      <div style={{ display: "flex", flex: 1, minHeight: 0 }}>
        {/* Left: list */}
        <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
          {/* Toolbar — row 1: status chips */}
          <div style={{ padding: "12px 20px 0", borderBottom: "none", display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <FilterChips filter={filter} onChange={setFilter} leads={leads}/>
          </div>

          {/* Toolbar — row 2: type + manager + search + actions */}
          <div style={{ padding: "8px 20px 12px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            {/* Type chips */}
            <div style={{ display: "flex", gap: 5 }}>
              {["all", ...LEAD_TYPES.map(lt => lt.key)].map(t => {
                const on = typeFilter === t;
                return (
                  <button key={t} onClick={() => setTypeFilter(t)} style={{ height: 26, padding: "0 10px", border: "1px solid " + (on ? "var(--accent)" : "var(--border-subtle)"), background: on ? "var(--accent-soft)" : "transparent", color: on ? "var(--accent)" : "var(--fg-muted)", borderRadius: 999, fontSize: 11, fontWeight: 500, cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap" }}>
                    {t === "all" ? "Всі типи" : t}
                  </button>
                );
              })}
            </div>

            <div style={{ width: 1, height: 20, background: "var(--border-subtle)", flexShrink: 0 }}/>

            {/* Manager filter */}
            <div style={{ position: "relative" }}>
              <button onClick={() => setDropMgr(d => !d)} style={{ height: 26, padding: "0 10px", border: "1px solid " + (managerFilter !== "all" ? "var(--accent)" : "var(--border-subtle)"), background: managerFilter !== "all" ? "var(--accent-soft)" : "transparent", color: managerFilter !== "all" ? "var(--accent)" : "var(--fg-muted)", borderRadius: 999, fontSize: 11, fontWeight: 500, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 5 }}>
                <Icon name="user" size={12}/>
                {managerFilter === "all" ? "Всі менеджери" : managerFilter}
              </button>
              {dropMgr && (
                <>
                  <div style={{ position: "fixed", inset: 0, zIndex: 49 }} onClick={() => setDropMgr(false)}/>
                  <div style={{ position: "absolute", top: "calc(100% + 4px)", left: 0, minWidth: 180, background: "var(--bg-raised)", border: "1px solid var(--border-default)", borderRadius: 8, padding: 4, boxShadow: "var(--shadow-1)", zIndex: 50 }}>
                    {["all", ...managers].map(m => (
                      <button key={m} onClick={() => { setManagerFilter(m); setDropMgr(false); }} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%", padding: "8px 10px", border: 0, borderRadius: 6, cursor: "pointer", background: managerFilter === m ? "var(--bg-active)" : "transparent", color: "var(--fg-primary)", fontSize: 13, fontFamily: "inherit" }}>
                        {m === "all" ? "Всі менеджери" : m}
                        {managerFilter === m && <Icon name="check" size={13} color="var(--accent)"/>}
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>

            <div style={{ flex: 1 }}/>

            <div style={{ position: "relative", width: 190 }}>
              <Icon name="search" size={13} style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--fg-muted)" }}/>
              <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Пошук заявок..." style={{ width: "100%", height: 28, boxSizing: "border-box", padding: "0 10px 0 28px", background: "var(--bg-raised)", color: "var(--fg-primary)", border: "1px solid var(--border-default)", borderRadius: 6, fontSize: 12, outline: "none", fontFamily: "inherit" }}/>
            </div>
            <Button variant="secondary" size="sm" leftIcon="arrow-up-down" onClick={() => setSort(s => s === "newest" ? "oldest" : "newest")}>
              {sort === "newest" ? "Новіші" : "Старіші"}
            </Button>
            <Button variant="secondary" size="sm" leftIcon="refresh-cw" onClick={load}>Оновити</Button>
            <Button variant="primary" size="sm" leftIcon="plus" onClick={() => setNewOpen(true)}>Нова заявка</Button>
          </div>

          {/* Column headers */}
          <div style={{ display: "grid", gridTemplateColumns: "36px 70px minmax(0,1.5fr) minmax(0,1.1fr) 100px 110px 110px 90px", alignItems: "center", gap: 10, padding: "10px 18px", borderBottom: "1px solid var(--border-subtle)", background: "var(--bg-panel)", fontSize: 10, fontWeight: 500, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg-muted)" }}>
            <span>ID</span><span>Час</span><span>Запит</span><span>Клієнт</span><span>Джерело</span><span>Бот</span><span>Статус</span><span>Менеджер</span>
          </div>

          {/* Rows */}
          <div style={{ flex: 1, overflowY: "auto" }}>
            {loading ? (
              <div style={{ padding: 60, textAlign: "center", color: "var(--fg-muted)", fontSize: 13 }}>Завантаження…</div>
            ) : filtered.length === 0 ? (
              <div style={{ padding: 60, textAlign: "center", color: "var(--fg-muted)", fontSize: 13 }}>Заявок не знайдено</div>
            ) : (
              filtered.map(lead => (
                <LeadRow key={lead.id} lead={lead} selected={selected} onSelect={handleSelect} onStatusChange={handleStatusChange}/>
              ))
            )}
          </div>

          {/* Footer */}
          <div style={{ padding: "8px 20px", borderTop: "1px solid var(--border-subtle)", fontSize: 11, color: "var(--fg-muted)", display: "flex", justifyContent: "space-between" }}>
            <span>Показано {filtered.length} з {leads.length}</span>
            <span>Оновлено щойно</span>
          </div>
        </div>

        {/* Right: detail panel (collapsible) */}
        {panelOpen ? (
          <LeadDetail
            lead={selected}
            onClose={() => setSelected(null)}
            onCollapse={() => setPanelOpen(false)}
            onEdit={(raw) => setEditData(raw)}
            onConvert={(l) => handleStatusChange(l.id, "Конвертовано")}
          />
        ) : (
          <button onClick={() => setPanelOpen(true)} title="Показати панель деталей" style={{ width: 32, borderLeft: "1px solid var(--border-subtle)", background: "var(--bg-panel)", border: 0, borderLeft: "1px solid var(--border-subtle)", color: "var(--fg-secondary)", cursor: "pointer", flexShrink: 0, display: "flex", alignItems: "flex-start", justifyContent: "center", paddingTop: 16 }}>
            <Icon name="panel-right-open" size={16}/>
          </button>
        )}
      </div>

      <NewLeadModal open={newOpen} onClose={() => setNewOpen(false)} onSave={handleSaveNew} userName={userName}/>
      {editData && (
        <NewLeadModal
          open={true}
          onClose={() => setEditData(null)}
          onSave={handleSaveEdit}
          prefill={{ id: editData.id, type: editData.type, sku: editData.product, phone: editData.phone, name: editData.name, source: sourceReverse[editData.source] || "site", note: editData.desc, comment: editData.comment, orderId: editData.orderId }}
          userName={userName}
          isEdit
        />
      )}
    </div>
  );
}

window.Requests = Requests;
window.IncomingCallPopup = IncomingCallPopup;
