// ============================================================================
// ЗАЯВКИ v2 · Модал «Нова заявка» — 6 типів, поля підлаштовуються під тип
// ============================================================================
const { useState: lsnUseState } = React;

const LS_NEW_TYPES = [
  { ...LS_TYPES.product,  desc: "Клієнт хоче купити товар" },
  { ...LS_TYPES.warranty, desc: "Гарантійний випадок" },
  { ...LS_TYPES.return,   desc: "Клієнт повертає товар" },
  { ...LS_TYPES.question, desc: "Питання без товару" },
  { ...LS_INTERNAL_TYPES.docs, label: "Документ", desc: "На відправку керівником", internal: true },
  { ...LS_INTERNAL_TYPES.mgrq, label: "Питання керівнику", desc: "По замовленню чи цінах", internal: true },
];

function LsSourcePicker({ value, onChange }) {
  return (
    <div style={{ display: "flex", gap: 4 }}>
      {Object.entries(LS_SOURCES).map(([k, s]) => (
        <button key={k} onClick={() => onChange(k)} title={s.label} style={{
          height: 32, padding: "0 10px", borderRadius: 8, cursor: "pointer", fontFamily: "inherit",
          display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, fontWeight: 500,
          border: "1px solid " + (value === k ? "color-mix(in oklab, " + s.color + " 55%, transparent)" : "var(--border-default)"),
          background: value === k ? "color-mix(in oklab, " + s.color + " 13%, transparent)" : "var(--bg-raised)",
          color: value === k ? s.color : "var(--fg-muted)",
        }}><LsIcon name={s.icon} size={13}/>{s.label}</button>
      ))}
    </div>
  );
}

const LS_STATUS_MAPS = {
  product: LS_PRODUCT_STATUSES, warranty: LS_WARRANTY_STATUSES, return: LS_RETURN_STATUSES,
  question: LS_QUESTION_STATUSES, docs: LS_DOC_STATUSES, mgrq: LS_MGRQ_STATUSES,
};

// Поле «Товар» з пошуком по каталогу сайту (ціна/наявність) + кнопка «Уточнити наявність».
function LsProductField({ f, set, setF, userName }) {
  const [items, setItems] = lsnUseState([]);
  const [open, setOpen] = lsnUseState(false);
  const [avail, setAvail] = lsnUseState("");
  const [availLabel, setAvailLabel] = lsnUseState("");
  const tRef = React.useRef(null);
  const onType = (v) => {
    set("product")(v); setOpen(true); clearTimeout(tRef.current);
    if (!v || v.length < 2) { setItems([]); return; }
    tRef.current = setTimeout(() => lsCatalogSearch(v).then(setItems).catch(() => setItems([])), 300);
  };
  const pick = (p) => { setF(prev => ({ ...prev, product: p.name, sitePrice: p.price, siteCurrency: p.currency, sitePresence: p.presence })); setItems([]); setOpen(false); };
  const check = () => {
    if (!f.product) return;
    setAvail("loading");
    lsApi.checkAvail(f.product, userName, null, true).then(r => { setAvailLabel((r && (r.label || r.message)) || "—"); setAvail("done"); })
      .catch(e => { setAvailLabel(e.message || "Помилка"); setAvail("error"); });
  };
  const presLabel = p => p === "in" ? "в наявності" : p === "out" ? "немає" : "під замовлення";
  return (
    <LsField label="Товар">
      <div style={{ position: "relative" }}>
        <div style={{ display: "flex", gap: 8 }}>
          <div style={{ flex: 1, position: "relative" }}>
            <LsInput value={f.product || ""} onChange={onType} placeholder="Почніть вводити назву — пошук по сайту…"/>
            {open && items.length > 0 && (<React.Fragment>
              <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 69 }}></div>
              <div style={{ position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, zIndex: 70, background: "var(--bg-raised)", border: "1px solid var(--border-default)", borderRadius: 8, maxHeight: 240, overflowY: "auto", boxShadow: "0 8px 24px rgba(0,0,0,.5)" }}>
                {items.map((p, i) => (
                  <button key={i} onClick={() => pick(p)} style={{ display: "flex", justifyContent: "space-between", gap: 10, width: "100%", textAlign: "left", padding: "8px 10px", border: 0, background: "transparent", color: "var(--fg-secondary)", fontSize: 12.5, cursor: "pointer" }}>
                    <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</span>
                    <span style={{ color: p.presence === "out" ? "#FCA5A5" : "#6EE7B7", fontFamily: "var(--font-mono)", whiteSpace: "nowrap" }}>{p.price ? lsFmtUah(p.price) : "—"}</span>
                  </button>
                ))}
              </div>
            </React.Fragment>)}
          </div>
          <span onClick={check} style={{ display: "inline-flex" }}><LsButton variant="secondary" icon="package-search" style={{ height: 34, whiteSpace: "nowrap" }}>Уточнити</LsButton></span>
        </div>
        {f.sitePrice != null && <div style={{ fontSize: 11, marginTop: 6, color: "var(--fg-muted)" }}>На сайті: <span style={{ color: "var(--fg-secondary)", fontFamily: "var(--font-mono)" }}>{f.sitePrice ? lsFmtUah(f.sitePrice) : "—"}</span>{f.sitePresence ? " · " + presLabel(f.sitePresence) : ""}</div>}
        {avail === "loading" && <div style={{ fontSize: 11, marginTop: 6, color: "var(--fg-muted)" }}>Перевіряю в постачальника…</div>}
        {avail === "done" && <div style={{ fontSize: 11, marginTop: 6, color: "#6EE7B7" }}>{availLabel}</div>}
        {avail === "error" && <div style={{ fontSize: 11, marginTop: 6, color: "#FCA5A5" }}>{availLabel}</div>}
      </div>
    </LsField>
  );
}

function LsNewLeadModal({ onClose, onCreate, onSave, onDelete, initial, managers, userName }) {
  const editMode = !!initial;
  const [type, setType] = lsnUseState(initial ? initial.type : "product");
  const [f, setF] = lsnUseState(initial ? { ...initial } : { source: "telegram", channel: "email", docType: LS_DOC_TYPES[0], recipient: "fiz" });
  const set = (k) => (v) => setF(prev => ({ ...prev, [k]: v }));

  const create = () => {
    if (editMode) onSave && onSave(initial.id, f);
    else onCreate && onCreate(type, f);
    onClose();
  };
  const del = () => { if (window.confirm("Видалити цю заявку? Дію не можна скасувати.")) { onDelete && onDelete(initial.id); onClose(); } };

  const two = { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 };

  // Авто-заповнення з замовлення (гарантія/повернення): за № або телефоном → Клієнт/Товар/Телефон.
  const [lookup, setLookup] = lsnUseState("");
  const hint = { fontSize: 11, marginTop: 6 };
  const fillFromOrder = async () => {
    const orderId = (f.orderId || "").trim(), phone = (f.phone || "").replace(/\D/g, "");
    if (!orderId && !phone) { setLookup("need"); return; }
    setLookup("loading");
    try {
      const j = await lsApi.orderLookup(orderId ? { orderId } : { phone });
      if (!j.found || !j.order) { setLookup("notfound"); return; }
      const o = j.order;
      setF(p => ({ ...p,
        orderId: o.orderId || p.orderId,
        client: o.client || p.client,
        phone: o.phone || p.phone,
        product: (o.products || []).join(" · ") || p.product,
      }));
      setLookup("ok");
    } catch { setLookup("error"); }
  };
  const orderFillBlock = (
    <LsField label="Замовлення № / телефон — авто-заповнення">
      <div style={{ display: "flex", gap: 8 }}>
        <LsInput value={f.orderId || ""} onChange={set("orderId")} placeholder="№ замовлення, напр. 1247" mono/>
        <span onClick={fillFromOrder} style={{ display: "inline-flex" }}>
          <LsButton variant="secondary" icon="search" style={{ height: 34, whiteSpace: "nowrap" }}>Перевірити</LsButton>
        </span>
      </div>
      {lookup === "loading"  && <div style={{ ...hint, color: "var(--fg-muted)" }}>Шукаю замовлення…</div>}
      {lookup === "ok"       && <div style={{ ...hint, color: "#6EE7B7" }}>Знайдено — поля заповнено</div>}
      {lookup === "notfound" && <div style={{ ...hint, color: "#FBBF24" }}>Замовлення не знайдено</div>}
      {lookup === "need"     && <div style={{ ...hint, color: "#FBBF24" }}>Введіть № замовлення або телефон</div>}
      {lookup === "error"    && <div style={{ ...hint, color: "#FCA5A5" }}>Помилка пошуку</div>}
    </LsField>
  );

  // Телефон: модал на весь екран (інакше «плаваюче віконце», в якому нічого не видно).
  // ПК: для «Документ» ширше — там форма НП + ТТН-панель, у 560px все стискається.
  const narrow = typeof window !== "undefined" && window.innerWidth <= 768;
  return (
    <div style={{
      position: "absolute", inset: 0, background: "rgba(0,0,0,0.6)", zIndex: 50,
      display: "flex", alignItems: "center", justifyContent: "center",
    }}>
      <div style={narrow ? {
        width: "100%", height: "100%", maxHeight: "100%", background: "var(--bg-panel)", borderRadius: 0,
        display: "flex", flexDirection: "column",
      } : {
        width: type === "docs" ? "min(900px, 96vw)" : "min(560px, 96vw)",
        maxHeight: "92%", background: "var(--bg-panel)", borderRadius: 12, border: "1px solid var(--border-default)",
        boxShadow: "0 8px 24px rgba(0,0,0,.5), 0 24px 64px rgba(0,0,0,.4)", display: "flex", flexDirection: "column",
      }}>
        {/* Header */}
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
          <span style={{
            width: 30, height: 30, borderRadius: 8, display: "inline-flex", alignItems: "center", justifyContent: "center",
            background: "var(--accent-soft)", color: "var(--accent)",
          }}><LsIcon name="plus" size={15}/></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: "var(--fg-primary)" }}>{editMode ? "Редагувати заявку #" + initial.id : "Нова заявка"}</div>
            <div style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>{editMode ? "Змініть поля, статус або видаліть заявку" : "Зафіксуйте звернення — воно потрапить у свою вкладку"}</div>
          </div>
          <button onClick={onClose} style={{ width: 28, height: 28, border: 0, background: "transparent", color: "var(--fg-muted)", borderRadius: 6, cursor: "pointer" }}>
            <LsIcon name="x" size={16}/>
          </button>
        </div>

        <div style={{ padding: "16px 20px", overflowY: "auto", display: "flex", flexDirection: "column", gap: 14 }}>
          {/* У режимі редагування — статус замість вибору типу */}
          {editMode && (
            <LsField label="Статус">
              <LsStatusSelect map={LS_STATUS_MAPS[type] || {}} value={f.status} onChange={set("status")}/>
            </LsField>
          )}
          {/* Тип — 6 карток у 2 ряди (лише при створенні) */}
          {!editMode && (
          <div>
            <div style={{ fontSize: 11, fontWeight: 500, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)", marginBottom: 7 }}>Тип заявки</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 7 }}>
              {LS_NEW_TYPES.filter(t => !t.internal).map(t => {
                const active = type === t.key;
                return (
                  <button key={t.key} onClick={() => setType(t.key)} style={{
                    display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 6, padding: "10px 11px", textAlign: "left",
                    borderRadius: 9, cursor: "pointer", fontFamily: "inherit", minWidth: 0,
                    border: "1px solid " + (active ? "color-mix(in oklab, " + t.color + " 50%, transparent)" : "var(--border-default)"),
                    background: active ? "color-mix(in oklab, " + t.color + " 10%, transparent)" : "var(--bg-raised)",
                  }}>
                    <span style={{ color: active ? t.color : "var(--fg-muted)", display: "inline-flex" }}><LsIcon name={t.icon} size={15}/></span>
                    <span style={{ fontSize: 11.5, fontWeight: 600, color: active ? "var(--fg-primary)" : "var(--fg-secondary)", lineHeight: 1.2 }}>{t.short}</span>
                  </button>
                );
              })}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 7, marginTop: 7 }}>
              {LS_NEW_TYPES.filter(t => t.internal).map(t => {
                const active = type === t.key;
                return (
                  <button key={t.key} onClick={() => setType(t.key)} style={{
                    display: "flex", alignItems: "center", gap: 9, padding: "9px 12px", textAlign: "left",
                    borderRadius: 9, cursor: "pointer", fontFamily: "inherit", minWidth: 0,
                    border: "1px " + (active ? "solid color-mix(in oklab, " + t.color + " 50%, transparent)" : "dashed var(--border-strong)"),
                    background: active ? "color-mix(in oklab, " + t.color + " 10%, transparent)" : "transparent",
                  }}>
                    <span style={{ color: active ? t.color : "var(--fg-muted)", display: "inline-flex" }}><LsIcon name={t.icon} size={15}/></span>
                    <span style={{ minWidth: 0 }}>
                      <span style={{ display: "block", fontSize: 11.5, fontWeight: 600, color: active ? "var(--fg-primary)" : "var(--fg-secondary)" }}>{t.label}</span>
                      <span style={{ display: "block", fontSize: 10.5, color: "var(--fg-muted)" }}>{t.desc}</span>
                    </span>
                  </button>
                );
              })}
            </div>
          </div>
          )}

          {/* Поля — свої для кожного типу */}
          {type === "product" && (<React.Fragment>
            <LsProductField f={f} set={set} setF={setF} userName={userName}/>
            <div style={two}>
              <LsField label="Клієнт"><LsInput value={f.client || ""} onChange={set("client")} placeholder="Ім'я"/></LsField>
              <LsField label="Телефон"><LsInput value={f.phone || ""} onChange={set("phone")} placeholder="+38 0XX XXX XX XX" mono/></LsField>
            </div>
            <LsField label="Джерело"><LsSourcePicker value={f.source} onChange={set("source")}/></LsField>
            <LsField label="Коментар"><LsInput value={f.note || ""} onChange={set("note")} placeholder="Колір, конфігурація, побажання…"/></LsField>
            {/* Звʼязок із клієнтом: дзвінок/Viber/Telegram + шаблони відповідей (лише збережена заявка) */}
            {editMode && window.LsClientContact && (
              <LsField label="Звʼязок з клієнтом">
                <LsClientContact phone={f.phone} client={f.client} product={f.product}/>
              </LsField>
            )}
          </React.Fragment>)}

          {type === "warranty" && (<React.Fragment>
            {orderFillBlock}
            <LsField label="Товар"><LsInput value={f.product || ""} onChange={set("product")} placeholder="Напр.: Samsung S24 Ultra"/></LsField>
            <div style={two}>
              <LsField label="Серійний номер"><LsInput value={f.serial || ""} onChange={set("serial")} placeholder="SN…" mono/></LsField>
              <LsField label="Чек / документ"><LsInput value={f.docId || ""} onChange={set("docId")} placeholder="Чек №…" mono/></LsField>
            </div>
            <LsField label="ТТН (по якій клієнт надіслав нам товар)"><LsInput value={f.ttn || ""} onChange={set("ttn")} placeholder="Напр.: 20450000000000" mono/></LsField>
            <LsField label="Опис проблеми"><LsInput value={f.problem || ""} onChange={set("problem")} placeholder="Що сталося"/></LsField>
            <div style={two}>
              <LsField label="Клієнт"><LsInput value={f.client || ""} onChange={set("client")} placeholder="Ім'я"/></LsField>
              <LsField label="Телефон"><LsInput value={f.phone || ""} onChange={set("phone")} placeholder="+38 0XX XXX XX XX" mono/></LsField>
            </div>
            {window.LsLeadFiles && <LsField label="Фото проблеми"><LsLeadFiles f={f} setF={setF}/></LsField>}
          </React.Fragment>)}

          {type === "return" && (<React.Fragment>
            {orderFillBlock}
            <LsField label="Товар"><LsInput value={f.product || ""} onChange={set("product")} placeholder="Напр.: iPad Pro 11 M4 256"/></LsField>
            <div style={two}>
              <LsField label="Дата покупки"><LsInput value={f.purchased || ""} onChange={set("purchased")} placeholder="дд.мм.рррр" mono/></LsField>
              <LsField label="Сума до повернення"><LsInput value={f.refund || ""} onChange={set("refund")} placeholder="0 ₴" mono/></LsField>
            </div>
            <LsField label="Причина повернення"><LsInput value={f.reason || ""} onChange={set("reason")} placeholder="Чому повертає"/></LsField>
            <div style={two}>
              <LsField label="Клієнт"><LsInput value={f.client || ""} onChange={set("client")} placeholder="Ім'я"/></LsField>
              <LsField label="Телефон"><LsInput value={f.phone || ""} onChange={set("phone")} placeholder="+38 0XX XXX XX XX" mono/></LsField>
            </div>
          </React.Fragment>)}

          {type === "question" && (<React.Fragment>
            <LsField label="Питання клієнта"><LsInput value={f.question || ""} onChange={set("question")} placeholder="Сформулюйте питання"/></LsField>
            <div style={two}>
              <LsField label="Клієнт"><LsInput value={f.client || ""} onChange={set("client")} placeholder="Ім'я"/></LsField>
              <LsField label="Телефон"><LsInput value={f.phone || ""} onChange={set("phone")} placeholder="+38 0XX XXX XX XX" mono/></LsField>
            </div>
            <LsField label="Джерело"><LsSourcePicker value={f.source} onChange={set("source")}/></LsField>
          </React.Fragment>)}

          {/* ТТН — власник створює накладну за даними менеджера (лише збережена заявка, канал НП).
              Широкий ПК: форма документа зліва, ТТН-панель справа (двома колонками — у вузькому
              модалі панель була нечитабельна). Телефон/вузьке вікно: одна колонка. */}
          {type === "docs" && (() => {
            const ttnOn = editMode && f.channel === "nova_poshta" && localStorage.getItem("crm_user_role") === "owner";
            const fields = (
              <div style={{ display: "flex", flexDirection: "column", gap: 14, minWidth: 0 }}>
                <LsDocFields f={f} set={set} setF={setF}/>
              </div>
            );
            if (!ttnOn) return (
              <React.Fragment>
                {fields}
                {/* Менеджер: створена ТТН видна read-only (сірим) + копіювання номера */}
                {f.ttn && (
                  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 8, background: "var(--bg-raised)", border: "1px solid var(--border-default)", flexWrap: "wrap", flexShrink: 0 }}>
                    <LsIcon name="truck" size={13}/>
                    <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--fg-muted)" }}>ТТН</span>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 15, fontWeight: 700, color: "var(--fg-primary)" }}>{f.ttn}</span>
                    <button type="button" onClick={() => copyText(f.ttn)} title="Скопіювати номер" style={{ height: 24, width: 24, display: "inline-flex", alignItems: "center", justifyContent: "center", background: "transparent", border: "1px solid var(--border-default)", borderRadius: 5, cursor: "pointer", color: "var(--fg-muted)", flexShrink: 0 }}>
                      <LsIcon name="copy" size={12}/>
                    </button>
                    <span style={{ fontSize: 11, color: "var(--fg-muted)" }}>
                      {f.ttnSender ? f.ttnSender + " · " : ""}{f.ttnCost ? "доставка " + f.ttnCost + " ₴ · " : ""}{f.ttnEta ? "орієнтовно " + f.ttnEta : ""}
                    </span>
                  </div>
                )}
              </React.Fragment>
            );
            const twoCol = typeof window !== "undefined" && window.innerWidth > 980;
            return twoCol ? (
              <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 5fr) minmax(0, 6fr)", gap: 16, alignItems: "start" }}>
                {fields}
                <LsTtnPanel f={f} setF={setF} leadId={initial.id}/>
              </div>
            ) : (
              <React.Fragment>
                {fields}
                <LsTtnPanel f={f} setF={setF} leadId={initial.id}/>
              </React.Fragment>
            );
          })()}

          {type === "mgrq" && (<React.Fragment>
            <LsField label="Питання керівнику"><LsInput value={f.question || ""} onChange={set("question")} placeholder="Напр.: даємо знижку по №1249?"/></LsField>
            <div style={{ display: "grid", gridTemplateColumns: "140px 1fr", gap: 12 }}>
              <LsField label="Замовлення №"><LsInput value={f.orderId || ""} onChange={set("orderId")} placeholder="необов'язково" mono/></LsField>
              <div style={{ display: "flex", alignItems: "flex-end", paddingBottom: 8, fontSize: 11.5, color: "var(--fg-muted)", gap: 6 }}>
                <LsIcon name="bell" size={12}/> Керівник отримає сповіщення — питання не загубиться
              </div>
            </div>
          </React.Fragment>)}

          {/* Менеджер відмічає канали комунікації (списався у Viber/Telegram) */}
          {editMode && (
            <div style={{ borderTop: "1px solid var(--border-subtle)", paddingTop: 10 }}>
              <LsCommMarkers value={f.comm} onChange={arr => setF(o => ({ ...o, comm: arr }))} phone={f.phone}/>
            </div>
          )}

          {/* Повна історія дзвінків з клієнтом (тільки в редагуванні, якщо є телефон) */}
          {editMode && (f.phone || "").replace(/\D/g, "").length >= 9 && (
            <div style={{ borderTop: "1px solid var(--border-subtle)", paddingTop: 10 }}>
              <LsCallTimeline phone={f.phone} since={f.createdAt}/>
            </div>
          )}

          {/* Історія — хто/що/коли (тільки в редагуванні) */}
          {editMode && Array.isArray(f.history) && f.history.length > 0 && (
            <LsField label="Історія">
              <div style={{ display: "flex", flexDirection: "column", gap: 6, borderTop: "1px solid var(--border-subtle)", paddingTop: 8 }}>
                {f.history.slice().reverse().map((h, i) => (
                  <div key={i} style={{ display: "flex", gap: 8, fontSize: 11.5, alignItems: "baseline" }}>
                    <span style={{ color: "var(--fg-muted)", fontFamily: "var(--font-mono)", whiteSpace: "nowrap" }}>{new Date(h.t).toLocaleString("uk-UA", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span>
                    <span style={{ color: "var(--fg-secondary)", flex: 1 }}>{h.a}</span>
                    {h.u && <span style={{ color: "var(--fg-muted)" }}>{h.u}</span>}
                  </div>
                ))}
              </div>
            </LsField>
          )}
        </div>

        <div style={{ padding: narrow ? "14px 16px calc(14px + env(safe-area-inset-bottom, 0px))" : "14px 20px", borderTop: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 8, flexShrink: 0 }}>
          {editMode
            ? <LsButton variant="danger" icon="trash-2" style={{ height: 34 }} onClick={del}>Видалити</LsButton>
            : <span style={{ fontSize: 11.5, color: "var(--fg-muted)" }}>Потрапить у вкладку «{LS_NEW_TYPES.find(t => t.key === type)?.label}»</span>}
          <span style={{ flex: 1 }}></span>
          <LsButton variant="secondary" style={{ height: 34 }} onClick={onClose}>Скасувати</LsButton>
          <LsButton variant="primary" icon="check" style={{ height: 34 }} onClick={create}>{editMode ? "Зберегти" : "Створити заявку"}</LsButton>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LsNewLeadModal });
