/* global React, I, UI */
// =============== ค้นหากลาง (topbar) + ดัชนีเอกสารทั้งระบบ ===============
const { useState: useStateGS, useEffect: useEffectGS, useRef: useRefGS, useMemo: useMemoGS } = React;

// ---------- ดัชนีเอกสาร/ข้อมูลทั้งระบบ ----------
function gsBuildIndex() {
  const D = window.SSSData;
  const ix = [];
  const push = (no, title, sub, route, type, status) => { if (no) ix.push({ no: String(no), title: title || "", sub: sub || "", route, type, status: status || "" }); };
  const money = (n) => "฿" + (Number(n) || 0).toLocaleString();

  (D.Quotations || []).forEach(r => push(r.no, r.customer, `ใบเสนอราคา · ${money(r.amount)}`, "quotations/" + r.no, "ใบเสนอราคา", r.status));
  (D.Invoices || []).forEach(r => push(r.no, r.customer, `ใบแจ้งหนี้ · ${money(r.amount)}`, "invoices/" + r.no, "ใบแจ้งหนี้", r.status));
  (D.DeliveryNotes || []).forEach(r => push(r.no, r.customer, `ใบส่งสินค้า · ${r.items} รายการ`, "delivery-notes/" + r.no, "ใบส่งสินค้า", r.status));
  (D.TaxInvoices || []).forEach(r => push(r.no, r.customer, `ใบกำกับภาษี · ${money(r.amount)}`, "tax-invoices/" + r.no, "ใบกำกับภาษี", r.type));
  (D.BillingNotes || []).forEach(r => push(r.no, r.customer, `ใบวางบิล · ${money(r.amount)}`, "billing-notes/" + r.no, "ใบวางบิล", r.status));
  (D.Receipts || []).forEach(r => push(r.no, r.customer, `ใบเสร็จรับเงิน · ${money(r.amount)}`, "receipts/" + r.no, "ใบเสร็จรับเงิน", r.status));
  (D.PurchaseOrders || []).forEach(r => push(r.no, r.vendor, `ใบสั่งซื้อ · ${money(r.amount)}`, "purchase-orders/" + r.no, "ใบสั่งซื้อ", r.status));
  (D.Expenses || []).forEach(r => push(r.no, `${r.category} — ${r.vendor}`, `ค่าใช้จ่าย · ${money(r.amount)}`, "expenses", "ค่าใช้จ่าย", r.status));
  (D.PaymentVouchers || []).forEach(r => push(r.no, r.payee, `ใบสำคัญจ่าย · ${money(r.amount)}`, "payment-vouchers/" + r.no, "ใบสำคัญจ่าย", r.status));
  (D.CashAdvances || []).forEach(r => push(r.no, `${r.requester} — ${r.purpose}`, `เบิกเงินสด · ${money(r.amount)}`, "cash-advances", "เบิกเงินสด", r.status));
  (D.ReceiptVouchers || []).forEach(r => push(r.no, r.payee, `ใบสำคัญรับเงิน · ${money(r.amount)}`, "receipt-vouchers/" + r.no, "ใบสำคัญรับเงิน", r.status));
  (D.WHTCertificates || []).forEach(r => push(r.no, r.payee, `50 ทวิ · หัก ${money(r.wht)}`, "wht-certs", "50 ทวิ", r.status));

  // งานส่งของประจำวัน (รวมที่บันทึกใน localStorage)
  const dels = window.DeliveryStore ? window.DeliveryStore.load() : (D.DailyDeliveries || []);
  dels.forEach(d => push(d.no, d.customer, `ใบส่งของประจำวัน · ${window.DeliveryStore ? window.DeliveryStore.fmtThai(d.date) : d.date} ${d.time} น.`, "daily-delivery", "ใบส่งของ", d.status));

  (D.Customers || []).forEach(c => push(c.id, c.name, `ลูกค้า · ${c.contact} · ${c.phone}`, "customers", "ลูกค้า"));
  (D.Vendors || []).forEach(v => push(v.id, v.name, `ผู้ขาย · ${v.category}`, "vendors", "ผู้ขาย"));
  (D.Products || []).forEach(p => push(p.sku, p.name, `สินค้า · คงเหลือ ${p.stock} ${p.unit}`, "inventory", "สินค้า"));
  (D.Employees || []).forEach(e => push(e.id, e.name, `พนักงาน · ${e.role}`, "hr", "พนักงาน"));

  return ix;
}

function gsNorm(s) { return String(s || "").toLowerCase().replace(/[\s\-]/g, ""); }

function gsSearch(q, limit = 10) {
  const ix = gsBuildIndex();
  const nq = gsNorm(q);
  if (!nq) return [];
  const scored = [];
  ix.forEach(item => {
    const hayNo = gsNorm(item.no);
    const hayAll = gsNorm(item.no + item.title + item.sub + item.type);
    let score = -1;
    if (hayNo === nq) score = 100;
    else if (hayNo.includes(nq)) score = 80;
    else if (gsNorm(item.title).includes(nq)) score = 60;
    else if (hayAll.includes(nq)) score = 40;
    if (score >= 0) scored.push({ ...item, score });
  });
  return scored.sort((a, b) => b.score - a.score).slice(0, limit);
}

function gsFindByNo(no) {
  const n = gsNorm(no);
  return gsBuildIndex().find(d => gsNorm(d.no) === n) || null;
}

window.SSSSearch = { buildIndex: gsBuildIndex, search: gsSearch, findByNo: gsFindByNo };

// ---------- คอมโพเนนต์ค้นหาบน topbar ----------
function GlobalSearch({ navigate }) {
  const { Badge } = window.UI;
  const [q, setQ] = useStateGS("");
  const [open, setOpen] = useStateGS(false);
  const [sel, setSel] = useStateGS(0);
  const inputRef = useRefGS(null);

  const results = useMemoGS(() => q.trim().length >= 2 ? gsSearch(q) : [], [q]);

  useEffectGS(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && (e.key === "k" || e.key === "K")) {
        e.preventDefault();
        inputRef.current && inputRef.current.focus();
        setOpen(true);
      }
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  const go = (item) => {
    if (!item) return;
    setOpen(false); setQ(""); setSel(0);
    if (navigate) navigate(item.route);
    else window.location.hash = "#/" + item.route;
  };

  const onKeyDown = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setSel(s => Math.min(s + 1, results.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setSel(s => Math.max(s - 1, 0)); }
    else if (e.key === "Enter") { e.preventDefault(); go(results[sel] || results[0]); }
    else if (e.key === "Escape") { setOpen(false); inputRef.current && inputRef.current.blur(); }
  };

  return (
    <div style={{position: "relative"}}>
      <div className="search">
        <I.search size={14}/>
        <input ref={inputRef} placeholder="ค้นหาเอกสาร, ลูกค้า, สินค้า…" value={q}
          onChange={e => { setQ(e.target.value); setOpen(true); setSel(0); }}
          onFocus={() => setOpen(true)}
          onKeyDown={onKeyDown}/>
        <span className="kbd">⌘K</span>
      </div>

      {open && q.trim().length >= 2 && (
        <>
          <div onClick={() => setOpen(false)} style={{position: "fixed", inset: 0, zIndex: 60}}></div>
          <div style={{position: "absolute", top: "calc(100% + 6px)", left: 0, width: 420, maxWidth: "calc(100vw - 40px)", zIndex: 61,
            background: "var(--surface)", border: "1px solid var(--line-strong)", borderRadius: 10,
            boxShadow: "var(--shadow-lg)", overflow: "hidden"}}>
            <div style={{padding: "8px 12px", borderBottom: "1px solid var(--line)", fontSize: 11, color: "var(--ink-3)", display: "flex", justifyContent: "space-between"}}>
              <span>ผลการค้นหา "{q}"</span>
              <span>{results.length} รายการ · ↑↓ เลือก, Enter เปิด</span>
            </div>
            {results.length === 0 && (
              <div style={{padding: "18px 14px", textAlign: "center", fontSize: 12.5, color: "var(--ink-3)"}}>
                ไม่พบ "{q}" — ลองค้นด้วยเลขที่เอกสาร, ชื่อลูกค้า, ชื่อสินค้า หรือ SKU
              </div>
            )}
            <div style={{maxHeight: 380, overflow: "auto"}}>
              {results.map((r, i) => (
                <div key={r.type + r.no + i} onClick={() => go(r)} onMouseEnter={() => setSel(i)}
                  style={{display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", cursor: "pointer",
                    background: i === sel ? "var(--surface-2)" : "transparent",
                    borderBottom: i < results.length - 1 ? "1px solid var(--line-soft)" : "none"}}>
                  <span className="badge outline" style={{fontSize: 9.5, flexShrink: 0, minWidth: 64, justifyContent: "center"}}>{r.type}</span>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 12.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>
                      <span className="mono" style={{color: "var(--ink-3)", fontWeight: 500}}>{r.no}</span> · {r.title}
                    </div>
                    <div style={{fontSize: 11, color: "var(--ink-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>{r.sub}</div>
                  </div>
                  {r.status && <Badge>{r.status}</Badge>}
                </div>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

window.GlobalSearch = GlobalSearch;
