/* X-REAL Stock System v5 — App Shell */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─── Nav config ───────────────────────────────────────────────────────
const NAV = [
  { id: "dashboard", icon: "dashboard",   label: "Dashboard",     mobile: true },
  { id: "in",        icon: "in",          label: "รับเข้า",        mobile: true },
  { id: "out",       icon: "out",         label: "จ่ายออก",        mobile: true },
  { id: "tr",        icon: "transfer",    label: "โอนคลัง",        mobile: true },
  { id: "quick",     icon: "zap",         label: "Quick Scan",    mobile: false, accent: true },
  { id: "repack",    icon: "repack",      label: "Re-pack",       mobile: false },
  { id: "reserve",   icon: "reserve",     label: "Reservations",  mobile: false },
  { id: "cons",      icon: "consign",     label: "Consignment",   mobile: false },
  { id: "forecast",  icon: "forecast",    label: "Forecast",      mobile: false },
  { id: "audit",     icon: "audit",       label: "Audit",         mobile: false },
  { id: "hist",      icon: "history",     label: "ประวัติ",         mobile: false },
  { id: "settings",  icon: "settings",    label: "ตั้งค่า",          mobile: false },
];

const PAGE_TITLES = {
  dashboard: "Dashboard",
  quick:     "Quick Scan",
  in:        "รับสินค้าเข้า",
  out:       "จ่ายสินค้าออก",
  tr:        "โอนย้ายคลัง",
  repack:    "Re-pack / แปลง SKU",
  reserve:   "Reservations",
  cons:      "Consignment Tracker",
  forecast:  "Forecast & Planning",
  audit:     "Stock Audit",
  hist:      "ประวัติการเคลื่อนไหว",
  settings:  "ตั้งค่าระบบ",
};

const PAGE_SUBS = {
  dashboard: "ภาพรวมสต็อค ทุกคลัง ทุก SKU",
  quick:     "สแกน → เลือก action → จบงาน",
  in:        "บันทึกรับสินค้าหลาย SKU ในครั้งเดียว",
  out:       "ตัดสต็อคขายตรงหรือรายงานยอดฝากขาย",
  tr:        "ย้ายระหว่างคลัง / คืนสต็อคกลับ",
  repack:    "แปลง SKU ใหญ่เป็น SKU ย่อยตามสัดส่วน",
  reserve:   "จองสินค้าล่วงหน้าสำหรับ event / order",
  cons:      "ติดตามสต็อคและยอดขายร้านฝาก",
  forecast:  "ทำนายความเคลื่อนไหวและแนะนำการเติมสต็อค",
  audit:     "นับสต็อคจริงเทียบกับยอดในระบบ",
  hist:      "ประวัติการทำรายการทั้งหมด",
  settings:  "หมวดหมู่ · สินค้า · คลัง · สูตร repack",
};

// ─── Sidebar (desktop) ────────────────────────────────────────────────
function Sidebar({ tab, setTab, username, onLogout, stocks, products, locations, reservations, onTweaks }) {
  // Quick stats for sidebar footer
  const expiring = stocks.filter(s => ["warn", "expired"].includes(expStatus(s.expDate))).length;
  const pending  = reservations.filter(r => r.status === "pending").length;

  return (
    <aside className="xr-sidebar xr-hide-mobile" style={{
      width: "var(--sidebar-w)", height: "100vh",
      background: "var(--surface)", borderRight: "1px solid var(--border)",
      display: "flex", flexDirection: "column", flexShrink: 0, position: "sticky", top: 0, zIndex: 50,
    }}>
      {/* Brand */}
      <div style={{
        padding: "18px 18px 14px", display: "flex", alignItems: "center", gap: 10,
        borderBottom: "1px solid var(--border-subtle)",
      }}>
        <XRealLogoMark size={36}/>
        <div>
          <div style={{ fontSize: 14, fontWeight: 800, letterSpacing: .5 }}>X-REAL</div>
          <div style={{ fontSize: 10, color: "var(--text-3)", letterSpacing: 1.4, fontWeight: 600 }}>STOCK · v5</div>
        </div>
      </div>

      {/* Nav */}
      <nav style={{ flex: 1, padding: 10, overflowY: "auto", display: "flex", flexDirection: "column", gap: 2 }}>
        {NAV.map(item => (
          <div key={item.id} onClick={() => setTab(item.id)}
            className={`xr-nav-item ${tab === item.id ? "xr-nav-item--active" : ""}`}>
            <Icon name={item.icon} size={16} style={{ flexShrink: 0 }}/>
            <span style={{ flex: 1 }}>{item.label}</span>
            {item.id === "reserve" && pending > 0 && (
              <span style={{
                fontSize: 10, fontWeight: 700, color: "var(--warn)", background: "var(--warn-bg)",
                borderRadius: 999, padding: "1px 6px", border: "1px solid var(--warn-border)",
              }}>{pending}</span>
            )}
            {item.id === "dashboard" && expiring > 0 && (
              <span style={{
                fontSize: 10, fontWeight: 700, color: "var(--danger)", background: "var(--danger-bg)",
                borderRadius: 999, padding: "1px 6px", border: "1px solid var(--danger-border)",
              }}>{expiring}</span>
            )}
          </div>
        ))}
      </nav>

      {/* User footer */}
      <div style={{ padding: 12, borderTop: "1px solid var(--border-subtle)" }}>
        <button onClick={onTweaks} className="xr-nav-item" style={{ width: "100%", marginBottom: 4 }}>
          <Icon name="sparkles" size={16}/>
          <span style={{ flex: 1, textAlign: "left" }}>ปรับธีม / Tweaks</span>
        </button>
        <div style={{
          display: "flex", alignItems: "center", gap: 10, padding: "8px 10px",
          borderRadius: "var(--r-md)", background: "var(--surface-2)",
        }}>
          <div style={{
            width: 30, height: 30, borderRadius: "50%",
            background: "linear-gradient(135deg, var(--accent), var(--accent-hover))",
            color: "#fff", fontSize: 12, fontWeight: 800,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>{username?.[0]?.toUpperCase() || "X"}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{username}</div>
            <button onClick={onLogout} style={{
              fontSize: 11, color: "var(--text-3)", padding: 0,
            }}>ออกจากระบบ</button>
          </div>
        </div>
      </div>
    </aside>
  );
}

// ─── Mobile bottom nav ────────────────────────────────────────────────
function MobileNav({ tab, setTab, onMore }) {
  const items = NAV.filter(i => i.mobile);
  return (
    <nav className="xr-hide-desktop" style={{
      position: "fixed", left: 0, right: 0, bottom: 0,
      height: "var(--mobile-nav-h)", zIndex: 100,
      background: "color-mix(in oklab, var(--surface) 92%, transparent)",
      backdropFilter: "blur(12px)",
      WebkitBackdropFilter: "blur(12px)",
      borderTop: "1px solid var(--border)",
      display: "flex", alignItems: "stretch", paddingBottom: "env(safe-area-inset-bottom)",
    }}>
      {items.map(item => (
        <button key={item.id} onClick={() => setTab(item.id)} style={{
          flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
          gap: 4, padding: "8px 4px",
          color: tab === item.id ? "var(--accent-hover)" : "var(--text-3)",
          fontSize: 10.5, fontWeight: 600, position: "relative",
          transition: "color var(--dur) var(--ease)",
        }}>
          {item.accent && tab !== item.id && (
            <span style={{
              position: "absolute", top: 6, right: "32%",
              width: 6, height: 6, borderRadius: 999, background: "var(--accent)",
              boxShadow: "0 0 8px var(--accent)",
            }}/>
          )}
          <Icon name={item.icon} size={20} strokeWidth={tab === item.id ? 2.4 : 1.8}/>
          <span>{item.label}</span>
        </button>
      ))}
      <button onClick={onMore} style={{
        flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
        gap: 4, padding: "8px 4px", color: "var(--text-3)", fontSize: 10.5, fontWeight: 600,
      }}>
        <Icon name="menu" size={20}/>
        <span>เพิ่มเติม</span>
      </button>
    </nav>
  );
}

// ─── Mobile More-menu sheet ───────────────────────────────────────────
function MobileMoreSheet({ open, onClose, tab, setTab, onTweaks, onLogout, username }) {
  if (!open) return null;
  const more = NAV.filter(i => !i.mobile);
  return (
    <div className="xr-modal-overlay xr-hide-desktop" onClick={onClose} style={{ alignItems: "flex-end", padding: 0 }}>
      <div onClick={e => e.stopPropagation()} className="xr-fade-up" style={{
        width: "100%", background: "var(--surface)",
        borderTopLeftRadius: "var(--r-xl)", borderTopRightRadius: "var(--r-xl)",
        padding: "16px 16px calc(24px + env(safe-area-inset-bottom))",
        maxHeight: "85vh", overflowY: "auto",
      }}>
        <div style={{
          width: 40, height: 4, background: "var(--border-strong)",
          borderRadius: 999, margin: "0 auto 16px",
        }}/>
        <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: .8, marginBottom: 10 }}>เมนูเพิ่มเติม</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginBottom: 18 }}>
          {more.map(item => (
            <button key={item.id} onClick={() => { setTab(item.id); onClose(); }} style={{
              padding: 14, borderRadius: "var(--r-md)",
              border: "1px solid var(--border)", background: tab === item.id ? "var(--accent-subtle)" : "var(--surface)",
              display: "flex", flexDirection: "column", alignItems: "center", gap: 8,
              color: tab === item.id ? "var(--accent-hover)" : "var(--text-1)",
            }}>
              <Icon name={item.icon} size={22}/>
              <span style={{ fontSize: 12, fontWeight: 600 }}>{item.label}</span>
            </button>
          ))}
        </div>
        <button onClick={() => { onTweaks(); onClose(); }} className="xr-btn" style={{ width: "100%", justifyContent: "flex-start", marginBottom: 8 }}>
          <Icon name="sparkles" size={16}/>
          <span>ปรับธีม / Tweaks</span>
        </button>
        <div style={{
          display: "flex", alignItems: "center", gap: 10, padding: "10px 12px",
          borderRadius: "var(--r-md)", background: "var(--surface-2)",
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: "50%",
            background: "linear-gradient(135deg, var(--accent), var(--accent-hover))",
            color: "#fff", fontSize: 14, fontWeight: 800,
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>{username?.[0]?.toUpperCase() || "X"}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{username}</div>
            <div style={{ fontSize: 11, color: "var(--text-3)" }}>ผู้ใช้งาน</div>
          </div>
          <Btn variant="ghost" size="sm" onClick={onLogout} icon="logout">ออก</Btn>
        </div>
      </div>
    </div>
  );
}

// ─── Topbar ───────────────────────────────────────────────────────────
function Topbar({ title, sub, expiringCount, pendingCount, tab, setTab, theme, onToggleTheme }) {
  return (
    <header style={{
      height: "var(--topbar-h)", padding: "0 22px",
      borderBottom: "1px solid var(--border)",
      display: "flex", alignItems: "center", justifyContent: "space-between",
      background: "color-mix(in oklab, var(--surface) 90%, transparent)",
      backdropFilter: "blur(12px)", WebkitBackdropFilter: "blur(12px)",
      position: "sticky", top: 0, zIndex: 40, flexShrink: 0,
    }}>
      {/* Mobile brand */}
      <div className="xr-hide-desktop" style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <XRealLogoMark size={32}/>
        <div>
          <div style={{ fontSize: 14, fontWeight: 800 }}>{title}</div>
          <div style={{ fontSize: 10.5, color: "var(--text-3)" }}>{sub}</div>
        </div>
      </div>
      {/* Desktop title */}
      <div className="xr-hide-mobile">
        <div style={{ fontSize: 17, fontWeight: 700, lineHeight: 1.2 }}>{title}</div>
        <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 1 }}>{sub}</div>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        {expiringCount > 0 && (
          <Pill variant="warn" icon="alert" style={{ cursor: "pointer" }}
            onClick={() => setTab("audit")}>
            {expiringCount} ใกล้หมดอายุ
          </Pill>
        )}
        {pendingCount > 0 && (
          <Pill variant="info" icon="reserve" style={{ cursor: "pointer" }}
            onClick={() => setTab("reserve")}>
            <span className="xr-hide-mobile">{pendingCount} reservation</span>
            <span className="xr-hide-desktop">{pendingCount}</span>
          </Pill>
        )}
        <button onClick={onToggleTheme} className="xr-btn xr-btn--icon" title={theme === "dark" ? "Light mode" : "Dark mode"}>
          <Icon name={theme === "dark" ? "sun" : "moon"} size={16}/>
        </button>
        <div className="xr-pill xr-pill--success xr-hide-mobile">
          <span className="xr-dot"/>LIVE
        </div>
      </div>
    </header>
  );
}

Object.assign(window, { NAV, PAGE_TITLES, PAGE_SUBS, Sidebar, MobileNav, MobileMoreSheet, Topbar });
