// ============================================================================
// ЗАЯВКИ — РОЗДІЛЕНІ ВКЛАДКИ · столи за типами
// Кожна вкладка має СВОЇ колонки під свій робочий процес
// ============================================================================

// Дія в рядку запиту товару: «Уточнити наявність» (пінг постачальнику через бота) або № замовлення.
function LsProductAction({ lead, userName }) {
  const { useState } = React;
  const [state, setState] = useState("");          // "", loading, done, error
  const [label, setLabel] = useState("");
  const done = lead.status === "converted" || lead.status === "lost";
  if (done) {
    return lead.orderId
      ? <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 500, color: "#6EE7B7" }}><LsIcon name="check" size={12}/>№{lead.orderId}</span>
      : <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>—</span>;
  }
  if (state === "done") {
    return <span title={label} style={{ fontSize: 11.5, color: "var(--fg-secondary)", lineHeight: 1.3, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{label}</span>;
  }
  const check = async (e) => {
    e.stopPropagation();
    if (!lead.product) { setLabel("Немає товару"); setState("done"); return; }
    setState("loading");
    try { const r = await lsApi.checkAvail(lead.product, userName, lead.id); setLabel((r && (r.label || r.message)) || "Запит надіслано"); setState("done"); }
    catch (err) { setLabel(err.message || "Помилка"); setState("error"); }
  };
  return (
    <button className="ls-cta" onClick={check} disabled={state === "loading"} style={{
      display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6, height: 28, width: "100%",
      border: "1px solid " + (state === "error" ? "rgba(244,63,94,.5)" : "var(--accent-ring)"), borderRadius: 7,
      background: state === "error" ? "rgba(244,63,94,.12)" : "var(--accent-soft)",
      color: state === "error" ? "#FCA5A5" : "#C7D2FE", fontFamily: "inherit", fontSize: 11.5, fontWeight: 500,
      cursor: state === "loading" ? "default" : "pointer", whiteSpace: "nowrap",
    }}>
      <LsIcon name={state === "loading" ? "loader" : "package-search"} size={12}/> {state === "loading" ? "Перевіряю…" : "Уточнити"}
    </button>
  );
}

// ── 1. ЗАПИТИ ТОВАРУ — мета: швидко конвертувати в замовлення ──────────────
function LsProductTable({ leads, onEdit, selectedId, userName, onStatus }) {
  const grid = "60px 56px minmax(0,2fr) 104px 88px minmax(0,1.2fr) 128px 40px minmax(150px,0.9fr)";
  return (
    <div style={{ minWidth: 1000 }}>
      <LsTHead grid={grid} cols={["ID", "Час", "Товар", "Наявність", ">Ціна сайту", "Клієнт", "Статус", "Мен.", "Дія"]}/>
      {leads.map(l => {
        const done = l.status === "converted" || l.status === "lost";
        const sel = selectedId === l.id;
        return (
          <div key={l.id} onClick={() => onEdit && onEdit(l)} className="ls-row" style={{
            display: "grid", gridTemplateColumns: grid, gap: 12, alignItems: "center",
            padding: "13px 18px 13px 12px", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer",
            background: sel ? "var(--bg-active)" : "transparent",
            borderLeft: "3px solid " + (sel ? "var(--accent)" : "transparent"),
          }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)" }}>#{l.id}</span>
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <LsAge min={l.ageMin} done={done}/>
              <span style={{ fontSize: 10, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{l.ts}</span>
            </div>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                <LsSource source={l.source}/>
                <span style={{ flex: 1, minWidth: 0, fontSize: 13.5, fontWeight: 600, color: "var(--fg-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.product}</span>
              </div>
              {l.note && <div style={{ fontSize: 11.5, color: "var(--fg-muted)", marginTop: 3, marginLeft: 28, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.note}</div>}
            </div>
            <LsBotPill reply={l.bot}/>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--fg-secondary)", textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{lsFmtUah(l.price)}</span>
            <div style={{ display: "flex", flexDirection: "column", gap: 3, minWidth: 0 }}>
              <LsClientCell client={l.client} phone={l.phone}/>
              <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                <LsCallBadge phone={l.phone} since={l.createdAt}/>
                <LsCommBadge comm={l.comm}/>
              </div>
            </div>
            <LsStatusSelect map={LS_PRODUCT_STATUSES} value={l.status} onChange={s => onStatus && onStatus(l.id, s)}/>
            <LsManager name={l.manager}/>
            <div onClick={e => e.stopPropagation()} style={{ minWidth: 0 }}>
              <LsProductAction lead={l} userName={userName}/>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ── 2. ГАРАНТІЯ — мета: вести кейс через сервісний центр ───────────────────
// Скільки днів товар у нас; після «Передано в СЦ» — 14-денний відлік від inScDate.
function LsWarrantyBar({ lead }) {
  const daysHere = lead.createdAt ? Math.max(0, Math.floor((Date.now() - lead.createdAt) / 86400000)) : 0;
  const inSc = lead.inScDate && (lead.status === "in_sc" || lead.status === "wait_return");
  if (inSc) {
    const dayN = Math.max(1, Math.floor((Date.now() - lead.inScDate) / 86400000) + 1);
    const pct = Math.max(0, Math.min(1, dayN / 14));
    const tone = dayN <= 7 ? "#10B981" : dayN <= 11 ? "#F59E0B" : "#EF4444";
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 4, minWidth: 0 }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
          <span style={{ fontSize: 11, color: "var(--fg-muted)" }}>в СЦ</span>
          <span style={{ fontSize: 11, fontWeight: 600, color: tone, whiteSpace: "nowrap" }}>день {dayN} із 14</span>
        </div>
        <div style={{ height: 4, borderRadius: 2, background: "var(--bg-raised)", overflow: "hidden" }}>
          <div style={{ width: (pct * 100) + "%", height: "100%", borderRadius: 2, background: tone }}></div>
        </div>
      </div>
    );
  }
  return <span style={{ fontSize: 12.5, color: "var(--fg-secondary)", fontWeight: 600, whiteSpace: "nowrap" }}>{daysHere} дн у нас</span>;
}

function LsWarrantyTable({ leads, onStatus, onEdit }) {
  const grid = "60px 56px minmax(0,1.5fr) minmax(0,1.7fr) 132px 156px minmax(0,1.1fr) 40px";
  return (
    <div>
      <LsTHead grid={grid} cols={["ID", "Час", "Товар", "Проблема", "Стан / днів", "Сервісний центр", "Клієнт", "Мен."]}/>
      {leads.map(l => (
        <div key={l.id} onClick={() => onEdit && onEdit(l)} className="ls-row" style={{
          display: "grid", gridTemplateColumns: grid, gap: 12, alignItems: "center",
          padding: "13px 18px 13px 15px", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer",
        }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)" }}>#{l.id}</span>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <LsAge min={l.ageMin} done={l.status === "closed"}/>
            <span style={{ fontSize: 10, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{l.ts}</span>
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
              <LsSource source={l.source}/>
              <span style={{ flex: 1, minWidth: 0, fontSize: 13.5, fontWeight: 600, color: "var(--fg-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.product}</span>
            </div>
            <div style={{ fontSize: 11, color: "var(--fg-muted)", marginTop: 3, marginLeft: 28, fontFamily: "var(--font-mono)" }}>SN {l.serial || "—"} · {l.docId || "—"}{l.ttn ? " · ТТН " + l.ttn : ""}</div>
          </div>
          <span style={{ fontSize: 12.5, color: "var(--fg-secondary)", lineHeight: 1.45, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{l.problem}</span>
          <LsWarrantyBar lead={l}/>
          <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-start", minWidth: 0 }}>
            <LsStatusSelect map={LS_WARRANTY_STATUSES} value={l.status} onChange={s => onStatus && onStatus(l.id, s)}/>
            {l.scDays != null && <span style={{ fontSize: 10.5, color: "var(--fg-muted)" }}>в СЦ {l.scDays} дн</span>}
            {l.verdict && <span style={{ fontSize: 10.5, color: "#6EE7B7", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: "100%" }}>{l.verdict}</span>}
          </div>
          <LsClientCell client={l.client} phone={l.phone}/>
          <LsManager name={l.manager}/>
        </div>
      ))}
    </div>
  );
}

// ── 3. ПОВЕРНЕННЯ — мета: вкластись у 14 днів і повернути кошти ────────────
function LsReturnDeadline({ day }) {
  if (day == null) return <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>—</span>;
  const pct = day / 14;
  const tone = day <= 7 ? "#10B981" : day <= 11 ? "#F59E0B" : "#EF4444";
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4, minWidth: 0 }}>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
        <span style={{ fontSize: 11.5, fontWeight: 600, color: tone, fontVariantNumeric: "tabular-nums" }}>день {day} із 14</span>
        {day >= 12 && <LsIcon name="alert-triangle" size={12} color={tone}/>}
      </div>
      <div style={{ height: 4, borderRadius: 2, background: "var(--bg-raised)", overflow: "hidden" }}>
        <div style={{ width: (pct * 100) + "%", height: "100%", borderRadius: 2, background: tone }}></div>
      </div>
    </div>
  );
}

function LsReturnTable({ leads, onStatus, onEdit }) {
  const grid = "60px 56px minmax(0,1.5fr) minmax(0,1.6fr) 110px 110px 150px minmax(0,1.1fr)";
  return (
    <div>
      <LsTHead grid={grid} cols={["ID", "Час", "Товар", "Причина", "Строк (14 дн)", ">До повернення", "Статус", "Клієнт"]}/>
      {leads.map(l => (
        <div key={l.id} onClick={() => onEdit && onEdit(l)} className="ls-row" style={{
          display: "grid", gridTemplateColumns: grid, gap: 12, alignItems: "center",
          padding: "13px 18px 13px 15px", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer",
        }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)" }}>#{l.id}</span>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <LsAge min={l.ageMin} done={l.status === "refunded"}/>
            <span style={{ fontSize: 10, color: "var(--fg-muted)", fontVariantNumeric: "tabular-nums" }}>{l.ts}</span>
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
              <LsSource source={l.source}/>
              <span style={{ flex: 1, minWidth: 0, fontSize: 13.5, fontWeight: 600, color: "var(--fg-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.product}</span>
            </div>
            <div style={{ fontSize: 11, color: l.complete ? "var(--fg-muted)" : "#FBBF24", marginTop: 3, marginLeft: 28, display: "flex", alignItems: "center", gap: 5 }}>
              <LsIcon name={l.complete ? "check" : "alert-circle"} size={11}/>
              {l.complete ? "Повна комплектація" : "Неповна комплектація"}
            </div>
          </div>
          <span style={{ fontSize: 12.5, color: "var(--fg-secondary)", lineHeight: 1.45, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{l.reason}</span>
          <LsReturnDeadline day={l.day}/>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "#F43F5E", textAlign: "right", fontVariantNumeric: "tabular-nums" }}>−{lsFmtUah(l.refund)}</span>
          <LsStatusSelect map={LS_RETURN_STATUSES} value={l.status} onChange={s => onStatus && onStatus(l.id, s)}/>
          <LsClientCell client={l.client} phone={l.phone}/>
        </div>
      ))}
    </div>
  );
}

// ── 4. ПИТАННЯ — інбокс: питання крупно + швидка відповідь у рядку ─────────
function LsQuestionInbox({ leads, onStatus, onEdit }) {
  const { useState } = React;
  const [openId, setOpenId] = useState(leads.find(l => l.status === "open")?.id ?? null);
  const canned = ["Так, є самовивіз: Київ, склад №2 (вул. Васильківська, 34)", "Уточню на складі й повернусь протягом 15 хв", "Надішлю рахунок-фактуру на email"];
  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {leads.map(l => {
        const open = openId === l.id;
        const answered = l.status !== "open";
        return (
          <div key={l.id} onClick={() => setOpenId(open ? null : l.id)} className={open ? "" : "ls-row"} style={{
            padding: "14px 18px 14px 15px", borderBottom: "1px solid var(--border-subtle)", cursor: "pointer",
            background: open ? "var(--bg-active)" : "transparent",
            borderLeft: "3px solid " + (open ? "#10B981" : "transparent"),
          }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
              <LsSource source={l.source}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 500, color: "var(--fg-primary)", lineHeight: 1.4 }}>«{l.question}»</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 5, fontSize: 11.5, color: "var(--fg-muted)" }}>
                  <span style={{ color: "var(--fg-secondary)" }}>{l.client}</span>
                  <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" }}>{lsFmtPhone(l.phone)}</span>
                  <span style={{ fontFamily: "var(--font-mono)", color: "var(--fg-muted)" }}>#{l.id}</span>
                  {l.note && <span>· {l.note}</span>}
                </div>
                {answered && l.reply && (
                  <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 7, fontSize: 12, color: "#6EE7B7" }}>
                    <LsIcon name="corner-down-right" size={12}/>
                    <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.reply}</span>
                    <span style={{ color: "var(--fg-muted)" }}>— {l.manager}</span>
                  </div>
                )}
              </div>
              <div onClick={e => e.stopPropagation()} style={{ display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
                <LsAge min={l.ageMin} done={answered}/>
                <LsStatusSelect map={LS_QUESTION_STATUSES} value={l.status} onChange={s => onStatus && onStatus(l.id, s)}/>
                <button onClick={() => onEdit && onEdit(l)} title="Редагувати" style={{ width: 26, height: 26, border: "1px solid var(--border-default)", background: "var(--bg-raised)", color: "var(--fg-muted)", borderRadius: 6, cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  <LsIcon name="pencil" size={13}/>
                </button>
              </div>
            </div>

            {open && !answered && (
              <div onClick={e => e.stopPropagation()} style={{ marginTop: 12, marginLeft: 32, display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {canned.map((c, i) => (
                    <button key={i} style={{
                      height: 26, padding: "0 10px", borderRadius: 999, border: "1px solid var(--border-default)",
                      background: "var(--bg-raised)", color: "var(--fg-secondary)", fontFamily: "inherit",
                      fontSize: 11.5, cursor: "pointer", maxWidth: 360, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                    }}>{c}</button>
                  ))}
                </div>
                <div style={{ display: "flex", gap: 8 }}>
                  <div style={{
                    flex: 1, display: "flex", alignItems: "center", height: 34, padding: "0 12px",
                    background: "var(--bg-raised)", border: "1px solid var(--border-default)", borderRadius: 8,
                    color: "var(--fg-muted)", fontSize: 12.5,
                  }}>Написати відповідь клієнту…</div>
                  <LsButton variant="primary" icon="send" style={{ height: 34 }}>Відповісти</LsButton>
                  <LsButton variant="secondary" icon="arrow-right" style={{ height: 34 }}>В заявку товару</LsButton>
                </div>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { LsProductTable, LsWarrantyTable, LsReturnTable, LsQuestionInbox });
