/* app.jsx — shell, navigation, routing */
const { useState: appUseState } = React;

const NAV = [
  { id: "dashboard", label: "ภาพรวม", icon: "dashboard", group: "หลัก" },
  { id: "receive",   label: "รับเข้า", icon: "receive", group: "ดำเนินการ" },
  { id: "issue",     label: "จ่ายออก", icon: "issue", group: "ดำเนินการ" },
  { id: "quotes",    label: "ใบเสนอราคา", icon: "report", group: "ดำเนินการ" },
  { id: "items",     label: "ข้อมูลสต๊อกสินค้า", icon: "box", group: "คลัง" },
  { id: "locations", label: "ผังโลเคชั่น", icon: "grid", group: "คลัง" },
  { id: "report",    label: "รายงานคงเหลือ", icon: "report", group: "รายงาน" },
  { id: "moves",     label: "รายงานเคลื่อนไหว", icon: "activity", group: "รายงาน" },
  { id: "users",     label: "จัดการผู้ใช้", icon: "user", group: "ผู้ดูแลระบบ", admin: true },
  { id: "company",   label: "ตั้งค่าบริษัท", icon: "edit", group: "ผู้ดูแลระบบ", admin: true },
];

const TITLES = {
  dashboard: ["ภาพรวม", "หน้าหลัก"],
  receive: ["รับสินค้าเข้า", "ดำเนินการ"],
  issue: ["จ่ายสินค้าออก", "ดำเนินการ"],
  quotes: ["ใบเสนอราคา", "ดำเนินการ"],
  items: ["ข้อมูลสต๊อกสินค้า", "คลังสินค้า"],
  locations: ["ผังโลเคชั่น", "คลังสินค้า"],
  report: ["รายงานสินค้าคงเหลือ", "รายงาน"],
  moves: ["รายงานการเคลื่อนไหว", "รายงาน"],
  users: ["จัดการผู้ใช้งาน", "ผู้ดูแลระบบ"],
  company: ["ตั้งค่าบริษัท", "ผู้ดูแลระบบ"],
};

const MOBILE_TABS = ["dashboard", "items", "receive", "quotes", "moves"];

function Shell() {
  const s = useStore();
  const { user, logout } = useAuth();
  const [route, setRoute] = appUseState("dashboard");
  const [navOpen, setNavOpen] = appUseState(false);
  const [search, setSearch] = appUseState("");
  const [menuOpen, setMenuOpen] = appUseState(false);

  const go = (r) => { setRoute(r); setNavOpen(false); document.querySelector(".scroll-area")?.scrollTo({ top: 0 }); };

  const isAdmin = user?.role === "admin";
  const { pendingCount } = useAuth();
  const visibleNav = NAV.filter(n => !n.admin || isAdmin);

  /* จัดกลุ่ม nav */
  const groups = visibleNav.reduce((acc, n) => { (acc[n.group] = acc[n.group] || []).push(n); return acc; }, {});

  const renderPage = () => {
    switch (route) {
      case "dashboard": return <Dashboard go={go} />;
      case "receive":   return <TxnPage mode="in" go={go} key="in" />;
      case "issue":     return <TxnPage mode="out" go={go} key="out" />;
      case "quotes":    return <Quotations go={go} />;
      case "items":     return <Items go={go} query={search} />;
      case "locations": return <Locations go={go} />;
      case "report":    return <Reports tab="report" go={go} />;
      case "moves":     return <Reports tab="moves" go={go} />;
      case "users":     return isAdmin ? <UserManagement /> : <Dashboard go={go} />;
      case "company":   return isAdmin ? <CompanySettings /> : <Dashboard go={go} />;
      default:          return <Dashboard go={go} />;
    }
  };

  const [title, crumb] = TITLES[route] || ["", ""];

  return (
    <div className={`app ${navOpen ? "nav-open" : ""}`}>
      <div className="sidebar-scrim" onClick={() => setNavOpen(false)}></div>

      {/* Sidebar */}
      <aside className="sidebar">
        <div className="brand">
          <span className="logo"><Icons.layers size={21}/></span>
          <div>
            <div className="b-name">คลังวัสดุ</div>
            <div className="b-sub">Inventory Management</div>
          </div>
        </div>
        <nav className="nav">
          {Object.entries(groups).map(([g, items]) => (
            <div key={g}>
              <div className="nav-label">{g}</div>
              {items.map(n => {
                const Icon = Icons[n.icon];
                return (
                  <div key={n.id} className={`nav-item ${route === n.id ? "active" : ""}`} onClick={() => go(n.id)}>
                    <Icon size={19}/>{n.label}
                    {n.id === "report" && s.lowStock.length > 0 && <span className="badge-count">{s.lowStock.length}</span>}
                    {n.id === "users" && pendingCount > 0 && <span className="badge-count" style={{ background: "var(--amber)", color: "#fff" }}>{pendingCount}</span>}
                  </div>
                );
              })}
            </div>
          ))}
        </nav>
        <div className="side-foot">
          <div className="user-chip" onClick={() => setMenuOpen(o => !o)} style={{ position: "relative" }}>
            <span className="avatar">{(user?.name || "ผู้ใช้").trim().charAt(0)}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{user?.name || "ผู้ใช้"}</div>
              <div style={{ fontSize: 11.5, color: "var(--muted-2)" }}>{roleLabel(user?.role)}</div>
            </div>
            <Icons.chevD size={16} style={{ color: "var(--muted-2)", transform: menuOpen ? "rotate(180deg)" : "none", transition: "transform .18s" }}/>
            {menuOpen && (
              <div style={{ position: "absolute", bottom: "calc(100% + 8px)", left: 0, right: 0, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, boxShadow: "var(--sh-3)", padding: 6, zIndex: 60 }} onClick={e => e.stopPropagation()}>
                <div style={{ padding: "8px 10px", fontSize: 12, color: "var(--muted-2)" }}>เข้าใช้งานเป็น <b className="num">@{user?.username}</b></div>
                <div className="nav-item" style={{ color: "var(--red)", padding: "9px 10px" }} onClick={logout}>
                  <Icons.arrowUp size={18} style={{ transform: "rotate(90deg)" }}/>ออกจากระบบ
                </div>
              </div>
            )}
          </div>
        </div>
      </aside>

      {/* Main */}
      <div className="main">
        <header className="topbar">
          <button className="icon-btn menu-btn" onClick={() => setNavOpen(true)}><Icons.menu size={20}/></button>
          <div className="topbar-title">
            <div className="crumb">{crumb}</div>
            <h1>{title}</h1>
          </div>
          <div className="topbar-spacer"></div>
          <div className="search">
            <Icons.search size={17}/>
            <input placeholder="ค้นหาสินค้า…" value={search}
              onChange={e => setSearch(e.target.value)}
              onFocus={() => route !== "items" && go("items")} />
          </div>
          <button className="icon-btn" onClick={() => go("report")}><Icons.bell size={19}/>{s.lowStock.length > 0 && <span className="dot"></span>}</button>
          <button className="btn btn-primary" onClick={() => go("receive")} style={{ }}><Icons.plus size={17}/><span className="hide-sm">สร้างรายการ</span></button>
        </header>

        <div className="scroll-area">
          {renderPage()}
        </div>
      </div>

      {/* Mobile tab bar */}
      <nav className="mobile-tabbar">
        {MOBILE_TABS.map(id => {
          const n = NAV.find(x => x.id === id);
          const Icon = Icons[n.icon];
          return (
            <div key={id} className={`mtab ${route === id ? "active" : ""}`} onClick={() => go(id)}>
              <Icon size={21}/>{n.label}
            </div>
          );
        })}
      </nav>

      <Toasts />
    </div>
  );
}

function BootSplash() {
  return (
    <div style={{ height: "100%", display: "grid", placeItems: "center", background: "var(--bg)" }}>
      <div className="spin" style={{ width: 44, height: 44, borderRadius: "50%", border: "3px solid var(--line)", borderTopColor: "var(--primary-600)" }}></div>
    </div>
  );
}

function Gate() {
  const { user, ready } = useAuth();
  if (!ready) return <BootSplash />;          // กำลังตรวจสอบเซสชัน
  if (!user) return <AuthScreen />;
  return <StoreProvider><Shell /></StoreProvider>;
}

function App() {
  return <AuthProvider><Gate /></AuthProvider>;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
