// App shell — sidebar nav, topbar, cmd-K, route handling
const { useState: uSh, useEffect: uEh, useMemo: uMh, useRef: uRh } = React;

// Routes
const NAV_GROUPS = [
  {
    label: "Operations",
    label_th: "หน้าร้าน",
    items: [
      { id: "home", icon: "Home", label: "Home", label_th: "หน้าหลัก", shortcut: "H" },
      { id: "intake", icon: "Car", label: "Intake", label_th: "รับรถ", shortcut: "I", badge: 0 },
      { id: "jobs", icon: "Wrench", label: "Job Cards", label_th: "ใบงาน", shortcut: "J", badge: 7 },
      { id: "dispatch", icon: "Dispatch", label: "Dispatch", label_th: "จัดคิวซ่อม", shortcut: "D" },
      { id: "pos", icon: "Receipt", label: "POS", label_th: "ขายหน้าร้าน", shortcut: "P" },
    ],
  },
  {
    label: "Sales & Money",
    label_th: "การขาย / การเงิน",
    items: [
      { id: "quotes", icon: "Quote", label: "Quotes", label_th: "ใบเสนอราคา" },
      { id: "billing", icon: "Invoice", label: "Invoices", label_th: "ใบเสร็จ" },
      { id: "payments", icon: "Money", label: "Payments", label_th: "การชำระ", badge: 0 },
      { id: "suppliers", icon: "Truck", label: "Suppliers", label_th: "ผู้ขาย" },
      { id: "tax", icon: "Coin", label: "Tax", label_th: "ภาษี" },
    ],
  },
  {
    label: "Records",
    label_th: "ฐานข้อมูล",
    items: [
      { id: "customers", icon: "Users", label: "Customers", label_th: "ลูกค้า" },
      { id: "inventory", icon: "Box", label: "Inventory", label_th: "สต๊อก", badge: 4 },
      { id: "parts", icon: "Layers", label: "Parts", label_th: "อะไหล่" },
      { id: "services", icon: "Wrench", label: "Services", label_th: "งานบริการ" },
      { id: "warranty", icon: "Shield", label: "Warranty", label_th: "รับประกัน" },
    ],
  },
  {
    label: "Operations Mgmt",
    label_th: "การจัดการ",
    items: [
      { id: "boss", icon: "Bell", label: "Issues", label_th: "รายงานปัญหา", badge: 6 },
      { id: "staff", icon: "Users", label: "Staff", label_th: "พนักงาน" },
      { id: "payroll", icon: "Wallet", label: "Payroll", label_th: "เงินเดือน" },
      { id: "reports", icon: "Chart", label: "Reports", label_th: "รายงาน" },
      { id: "admin", icon: "Settings", label: "Admin", label_th: "ตั้งค่า" },
    ],
  },
];

const ROUTE_META = {
  home: { title: "Home", title_th: "หน้าหลัก" },
  intake: { title: "Intake", title_th: "รับรถ" },
  jobs: { title: "Job Cards", title_th: "ใบงาน" },
  job_detail: { title: "Job Card", title_th: "ใบงาน" },
  dispatch: { title: "Dispatch board", title_th: "จัดคิวซ่อม" },
  pos: { title: "POS", title_th: "ขายหน้าร้าน" },
  quotes: { title: "Quotes", title_th: "ใบเสนอราคา" },
  billing: { title: "Invoices", title_th: "ใบเสร็จ" },
  payments: { title: "Payments", title_th: "การชำระเงิน" },
  payments_new: { title: "Receive payment", title_th: "รับชำระเงิน" },
  payments_aging: { title: "AR Aging", title_th: "ลูกหนี้คงค้าง" },
  suppliers: { title: "Suppliers", title_th: "ผู้ขาย" },
  suppliers_new: { title: "Add supplier", title_th: "เพิ่มผู้ขาย" },
  suppliers_aging: { title: "AP Aging", title_th: "เจ้าหนี้คงค้าง" },
  tax: { title: "Tax reports", title_th: "รายงานภาษี" },
  customers: { title: "Customers", title_th: "ลูกค้า" },
  customers_new: { title: "Add customer", title_th: "เพิ่มลูกค้า" },
  inventory: { title: "Inventory", title_th: "สต๊อก" },
  parts: { title: "Parts", title_th: "อะไหล่" },
  services: { title: "Services", title_th: "งานบริการ" },
  warranty: { title: "Warranty", title_th: "การรับประกัน" },
  warranty_policies: { title: "Warranty policies", title_th: "นโยบายการรับประกัน" },
  payroll: { title: "Payroll", title_th: "เงินเดือน" },
  payroll_rules: { title: "Commission rules", title_th: "ค่าคอมมิชชั่น" },
  staff: { title: "Staff", title_th: "พนักงาน" },
  staff_new: { title: "Add staff", title_th: "เพิ่มพนักงาน" },
  reports: { title: "Reports", title_th: "รายงาน" },
  admin: { title: "Admin", title_th: "ตั้งค่าระบบ" },
  boss: { title: "Boss Inbox", title_th: "รายงานปัญหาให้ลุงวุ้น" },
};

// Sidebar
function Sidebar({ route, setRoute, collapsed }) {
  return (
    <aside className="sidebar">
      <div className="sb-brand">
        <div className="sb-brand-mark"><img src="assets/logo.jpg" alt="" /></div>
        {!collapsed && (
          <div className="sb-brand-text">
            <div className="sb-brand-name">นายอะไหล่ยนต์</div>
            <div className="sb-brand-sub">Garage OS · v1.0</div>
          </div>
        )}
      </div>
      <nav className="sb-nav">
        {NAV_GROUPS.map(group => (
          <div key={group.label}>
            {!collapsed && <div className="sb-section-label">{group.label}</div>}
            {group.items.map(item => {
              const active = route.startsWith(item.id);
              const IconC = I[item.icon];
              return (
                <div
                  key={item.id}
                  className={"sb-item" + (active ? " active" : "")}
                  onClick={() => setRoute(item.id)}
                  title={collapsed ? item.label_th : ""}
                >
                  <span className="sb-item-icon"><IconC size={17} /></span>
                  <span className="sb-item-label">{item.label_th}</span>
                  {item.badge > 0 && <span className="sb-item-badge">{item.badge}</span>}
                  {item.shortcut && !item.badge && <span className="sb-item-shortcut">{item.shortcut}</span>}
                </div>
              );
            })}
          </div>
        ))}
      </nav>
      <div className="sb-foot">
        <div className="sb-avatar">น</div>
        {!collapsed && (
          <>
            <div className="sb-foot-text">
              <div className="sb-foot-name">ลุงวุ้น</div>
              <div className="sb-foot-role">Owner</div>
            </div>
            <button className="tb-iconbtn" style={{color:"var(--sb-ink-3)"}} title="ออกจากระบบ"><I.Logout size={16} /></button>
          </>
        )}
      </div>
    </aside>
  );
}

function Topbar({ route, setRoute, openCmdK, toggleNav }) {
  const meta = ROUTE_META[route] || ROUTE_META.home;
  return (
    <div className="topbar">
      <button className="tb-iconbtn" onClick={toggleNav} aria-label="toggle nav"><I.Menu size={18} /></button>
      <div className="tb-crumbs">
        <span style={{cursor:"pointer"}} onClick={() => setRoute("home")}>นายอะไหล่ยนต์</span>
        <span className="sep"><I.ChevronR size={12} /></span>
        <strong>{meta.title_th}</strong>
        <span className="muted t-xs mono" style={{marginLeft:8}}>{meta.title}</span>
      </div>
      <div className="tb-search" onClick={openCmdK}>
        <span className="tb-search-icon"><I.Search size={15} /></span>
        <span className="tb-search-text">ค้นหาลูกค้า / Job / อะไหล่ / ใบเสร็จ…</span>
        <span className="tb-search-kbd">⌘K</span>
      </div>
      <div className="tb-actions">
        <button className="tb-iconbtn" title="แจ้งเตือน"><I.Bell size={16} /><span className="dot"></span></button>
        <button className="tb-iconbtn" title="พิมพ์"><I.Print size={16} /></button>
        <button className="btn btn-accent btn-sm" onClick={() => setRoute("intake")}>
          <I.Plus size={14} /> รับรถใหม่
        </button>
      </div>
    </div>
  );
}

// Cmd-K palette
function CmdK({ open, onClose, setRoute }) {
  const [q, setQ] = uSh("");
  const [active, setActive] = uSh(0);
  const inputRef = uRh(null);
  uEh(() => { if (open && inputRef.current) inputRef.current.focus(); }, [open]);

  const items = uMh(() => {
    const all = [];
    NAV_GROUPS.forEach(g => g.items.forEach(item => {
      all.push({ kind: "page", id: item.id, label: `${item.label_th} · ${item.label}`, icon: item.icon, group: "หน้า / Pages" });
    }));
    GS.JOBS.forEach(j => {
      const c = GS.CUSTOMERS.find(c => c.id === j.custId);
      all.push({ kind: "job", id: j.id, label: `${j.id} — ${c?.name || ""} · ${j.plate}`, icon: "Wrench", group: "Job", route: "jobs" });
    });
    GS.CUSTOMERS.slice(0, 8).forEach(c => {
      all.push({ kind: "cust", id: c.id, label: `${c.name} · ${c.phone}`, icon: "User", group: "ลูกค้า / Customers", route: "customers" });
    });
    GS.INVOICES.forEach(inv => {
      all.push({ kind: "inv", id: inv.id, label: `${inv.id} · ${GS.fmtMoney(inv.total)}`, icon: "Invoice", group: "Invoice", route: "billing" });
    });
    GS.PARTS.slice(0, 6).forEach(p => {
      all.push({ kind: "part", id: p.code, label: `${p.code} — ${p.name}`, icon: "Box", group: "อะไหล่ / Parts", route: "parts" });
    });
    if (!q) return all.slice(0, 14);
    const lq = q.toLowerCase();
    return all.filter(x => x.label.toLowerCase().includes(lq) || x.id.toLowerCase().includes(lq)).slice(0, 20);
  }, [q]);

  const grouped = uMh(() => {
    const g = {};
    items.forEach(it => { if (!g[it.group]) g[it.group] = []; g[it.group].push(it); });
    return g;
  }, [items]);

  uEh(() => { setActive(0); }, [q]);
  uEh(() => {
    const onKey = (e) => {
      if (!open) return;
      if (e.key === "ArrowDown") { e.preventDefault(); setActive(a => Math.min(a + 1, items.length - 1)); }
      else if (e.key === "ArrowUp") { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); }
      else if (e.key === "Enter" && items[active]) {
        const it = items[active];
        setRoute(it.route || it.id);
        onClose();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, items, active, onClose, setRoute]);

  if (!open) return null;
  let idx = -1;
  return (
    <div className="scrim" onClick={onClose}>
      <div className="cmdk" onClick={e => e.stopPropagation()}>
        <div className="cmdk-search">
          <I.Search size={18} stroke="var(--ink-3)" />
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="พิมพ์เพื่อค้นหา…   ลูกค้า, Job, อะไหล่, เลขที่ใบเสร็จ" />
          <span className="kbd" style={{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--ink-4)"}}>ESC</span>
        </div>
        <div className="cmdk-list">
          {Object.keys(grouped).length === 0 && <div className="empty"><div className="empty-title">ไม่พบผลลัพธ์</div></div>}
          {Object.entries(grouped).map(([gname, gitems]) => (
            <div key={gname}>
              <div className="cmdk-group-label">{gname}</div>
              {gitems.map(it => {
                idx++;
                const IconC = I[it.icon];
                const isActive = idx === active;
                return (
                  <div key={it.id} className={"cmdk-item" + (isActive ? " active" : "")}
                    onClick={() => { setRoute(it.route || it.id); onClose(); }}>
                    <span className="icon"><IconC size={15} /></span>
                    <span>{it.label}</span>
                    {isActive && <span className="kbd">↵</span>}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.AppShell = { Sidebar, Topbar, CmdK, NAV_GROUPS, ROUTE_META };
