// App shell: responsive nav (desktop sidebar / mobile bottom-tabs + More sheet),
// hash router, theme, ROLE system (RBAC), command palette trigger, toast.
(function () {
  const { useState, useEffect } = React;
  const IC = window.IC,D = window.DATA;

  // ---- media query hook ----
  window.useIsMobile = function () {
    const [m, setM] = useState(typeof window !== "undefined" ? window.innerWidth < 1000 : false);
    useEffect(() => {
      const mq = window.matchMedia("(max-width:999px)");
      const fn = () => setM(mq.matches);
      fn();mq.addEventListener("change", fn);
      return () => mq.removeEventListener("change", fn);
    }, []);
    return m;
  };

  // ---- hash router ----
  function parseHash() {
    const h = (window.location.hash || "#/dashboard").replace(/^#\//, "");
    const parts = h.split("/").filter(Boolean);
    return { screen: parts[0] || "dashboard", id: parts[1] || null, tab: parts[2] || null };
  }
  window.navigate = function (path) {
    window.location.hash = "#/" + path.replace(/^#?\/?/, "");
    document.documentElement.scrollTop = 0;document.body.scrollTop = 0;
    const sc = document.querySelector(".app-main");if (sc) sc.scrollTop = 0;
  };
  window.useRoute = function () {
    const [r, setR] = useState(parseHash());
    useEffect(() => {
      const fn = () => setR(parseHash());
      window.addEventListener("hashchange", fn);
      return () => window.removeEventListener("hashchange", fn);
    }, []);
    return r;
  };

  // ---- theme (light/dark, persisted) ----
  window.useTheme = function () {
    const [theme, setTheme] = useState(() => {
      try {return localStorage.getItem("nexus-theme") || "light";} catch (e) {return "light";}
    });
    useEffect(() => {
      document.documentElement.setAttribute("data-theme", theme);
      try {localStorage.setItem("nexus-theme", theme);} catch (e) {}
    }, [theme]);
    return [theme, () => setTheme((t) => t === "dark" ? "light" : "dark")];
  };

  // ---- ROLE (2 levels) + ADMIN AUTH (session-gated) ----
  function getAuthed() {try {return sessionStorage.getItem("bp-admin") === "1";} catch (e) {return false;}}
  window.__adminAuthed = getAuthed();
  try {window.__role = localStorage.getItem("nexus-role") || "executive";} catch (e) {window.__role = "executive";}
  // a fresh session always starts read-only until admin logs in again
  if (window.__role === "admin" && !window.__adminAuthed) window.__role = "executive";

  function applyRole(r) {
    window.__role = r;
    try {localStorage.setItem("nexus-role", r);} catch (e) {}
    window.dispatchEvent(new CustomEvent("role-change", { detail: r }));
  }
  window.useRole = function () {
    const [role, setRoleS] = useState(window.__role);
    useEffect(() => {
      const fn = (e) => setRoleS(e.detail);
      window.addEventListener("role-change", fn);
      return () => window.removeEventListener("role-change", fn);
    }, []);
    const setRole = (r) => {
      if (r === "admin" && !window.__adminAuthed) {window.dispatchEvent(new CustomEvent("open-login"));return;}
      applyRole(r);
    };
    return [role, setRole];
  };
  window.sha256Hex = async function (str) {
    const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str));
    return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
  };
  window.adminLogin = async function (user, pass) {
    if (user !== D.adminCreds.user) return false;
    let h;
    try { h = await window.sha256Hex(pass); } catch (e) { return false; }
    if (h === D.adminCreds.passHash) {
      window.__adminAuthed = true;
      try {sessionStorage.setItem("bp-admin", "1");} catch (e) {}
      applyRole("admin");
      return true;
    }
    return false;
  };
  window.logoutAdmin = function () {
    window.__adminAuthed = false;
    try {sessionStorage.removeItem("bp-admin");} catch (e) {}
    applyRole("executive");
    window.toast("ออกจากโหมดผู้ดูแลระบบแล้ว");
  };
  // non-hook accessor for screens
  window.currentRole = function () {return D.roles[window.__role] || D.roles.executive;};
  window.can = function (cap) {return !!window.currentRole().caps[cap];};

  // ---- toast ----
  window.toast = function (msg) {window.dispatchEvent(new CustomEvent("app-toast", { detail: msg }));};
  function Toast() {
    const [msg, setMsg] = useState(null);
    useEffect(() => {
      let t;
      const fn = (e) => {setMsg(e.detail);clearTimeout(t);t = setTimeout(() => setMsg(null), 2600);};
      window.addEventListener("app-toast", fn);
      return () => {window.removeEventListener("app-toast", fn);clearTimeout(t);};
    }, []);
    return <div className={"toast" + (msg ? " show" : "")}>{msg && <>{IC.check}<span>{msg}</span></>}</div>;
  }

  const NAV = [
  { grp: "หลัก", items: [
    { id: "dashboard", label: "ภาพรวมองค์กร", icon: "grid" },
    { id: "projects", label: "โครงการ", icon: "folder" },
    { id: "updates", label: "อัปเดตโครงการ", icon: "trend" },
    { id: "timeline", label: "Timeline", icon: "gantt" },
    { id: "meetings", label: "การประชุม", icon: "meet" }]
  },
  { grp: "การกำกับดูแล", items: [
    { id: "decisions", label: "Decision Log", icon: "dec" },
    { id: "documents", label: "เอกสาร", icon: "doc" },
    { id: "reports", label: "รายงาน", icon: "rep" }]
  },
  { grp: "ระบบ", items: [
    { id: "settings", label: "ตั้งค่า & สิทธิ์", icon: "settings" }]
  }];

  const MOBILE_NAV = [
  { id: "dashboard", label: "หน้าหลัก", icon: "grid" },
  { id: "projects", label: "โครงการ", icon: "folder" },
  { id: "updates", label: "อัปเดต", icon: "trend" },
  { id: "meetings", label: "ประชุม", icon: "meet" },
  { id: "__more", label: "เพิ่มเติม", icon: "menu" }];

  // ---- Role switcher popover ----
  function RoleSwitcher({ role, setRole, open, onClose, anchor }) {
    if (!open) return null;
    const pos = anchor === "mobile" ?
    { position: "fixed", inset: 0, zIndex: 70, background: "rgba(35,33,27,.32)", backdropFilter: "blur(2px)", display: "flex", alignItems: "flex-end" } :
    { position: "fixed", inset: 0, zIndex: 70 };
    const panel = anchor === "mobile" ?
    { width: "100%", background: "var(--surface)", borderRadius: "20px 20px 0 0", padding: "10px 14px 26px", boxShadow: "var(--shadow-lg)" } :
    { position: "absolute", left: 14, bottom: 78, width: 268, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 14, padding: 8, boxShadow: "var(--shadow-lg)" };
    return (
      <div style={pos} onClick={onClose}>
        <div style={panel} onClick={(e) => e.stopPropagation()}>
          {anchor === "mobile" && <div style={{ width: 40, height: 4, borderRadius: 99, background: "var(--line-strong)", margin: "8px auto 12px" }} />}
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--faint)", padding: "6px 10px 8px" }}>เลือกโหมดการใช้งาน</div>
          {Object.values(D.roles).map((r) =>
          <button key={r.id} className={"role-opt" + (role === r.id ? " on" : "")} onClick={() => {setRole(r.id);if (!(r.id === "admin" && !window.__adminAuthed)) onClose();}}>
              <span className={"role-dot " + r.color} />
              <span style={{ flex: 1, textAlign: "left" }}>
                <span className="ro-n">{r.name}{r.locked && <span className="ro-lock">{IC.lock}</span>}</span>
                <span className="ro-d">{r.scope}</span>
              </span>
              {role === r.id && <span style={{ color: "var(--accent)" }}>{IC.check}</span>}
            </button>
          )}
          {role === "admin" && window.__adminAuthed &&
          <button className="role-opt" onClick={() => {window.logoutAdmin();onClose();}} style={{ borderTop: "1px solid var(--line-soft)", marginTop: 4, paddingTop: 12, color: "var(--danger)" }}>
              <span style={{ color: "var(--danger)" }}>{IC.logout}</span>
              <span style={{ flex: 1, textAlign: "left", fontSize: 14, fontWeight: 600 }}>ออกจากโหมด Admin</span>
            </button>
          }
        </div>
      </div>);

  }

  function roleAvatar(r) {return r.id === "admin" ? "AD" : "ผบ";}

  function Sidebar({ screen, role, setRole }) {
    const r = D.roles[role];
    const [swOpen, setSwOpen] = useState(false);
    return (
      <nav className="sidebar">
        <a className="brand" href="#/dashboard">
          <div className="mark" style={{ fontSize: "15px", backgroundColor: "rgb(248, 0, 0)", color: "rgb(255, 255, 255)" }}>BT</div>
          <div className="bn"><b>BANK PROJECT</b><small>Project by thankrit pornaummarin</small></div>
        </a>
        {NAV.map((g) => {
          const items = g.items.filter((it) => r.nav.includes(it.id));
          if (items.length === 0) return null;
          return (
            <React.Fragment key={g.grp}>
              <div className="grp">{g.grp}</div>
              {items.map((it) =>
              <a key={it.id} className={"nav" + (screen === it.id ? " on" : "")} href={"#/" + it.id}>
                  {IC[it.icon]}<span>{it.label}</span>{it.ct != null && <span className="ct">{it.ct}</span>}
                </a>
              )}
            </React.Fragment>);

        })}
        <button className="side-foot" onClick={() => setSwOpen(true)} title="สลับโหมด">
          <span className={"avatar md role-av " + r.color} style={{ color: "rgb(255, 255, 255)", backgroundColor: "rgb(0, 99, 162)" }}>{roleAvatar(r)}</span>
          <div className="ot">
            <b style={{ color: "rgb(255, 255, 255)" }}>{r.id === "admin" ? "โหมดผู้ดูแลระบบ" : "โหมดผู้บริหาร"}</b>
            <span>{r.name} · แตะเพื่อสลับ</span>
          </div>
          <span className="sf-switch">{IC.dots}</span>
        </button>
        <RoleSwitcher role={role} setRole={setRole} open={swOpen} onClose={() => setSwOpen(false)} anchor="desk" />
      </nav>);

  }

  function MoreSheet({ open, onClose, screen, role, setRole }) {
    const r = D.roles[role];
    const extra = [
    { id: "meetings", label: "การประชุม", icon: "meet" },
    { id: "decisions", label: "Decision Log", icon: "dec" },
    { id: "documents", label: "เอกสาร", icon: "doc" },
    { id: "reports", label: "รายงาน", icon: "rep" },
    { id: "settings", label: "ตั้งค่า & สิทธิ์", icon: "settings" }].filter((it) => r.nav.includes(it.id));
    const [swOpen, setSwOpen] = useState(false);
    if (!open) return null;
    return (
      <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 60, background: "rgba(35,33,27,.32)", backdropFilter: "blur(2px)", display: "flex", alignItems: "flex-end" }}>
        <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", background: "var(--surface)", borderRadius: "20px 20px 0 0", padding: "10px 14px 26px", boxShadow: "var(--shadow-lg)" }}>
          <div style={{ width: 40, height: 4, borderRadius: 99, background: "var(--line-strong)", margin: "8px auto 14px" }} />
          <button className="role-opt" onClick={() => setSwOpen(true)} style={{ width: "100%", marginBottom: 6, minHeight: 48 }}>
            <span className={"role-dot " + r.color} />
            <span style={{ flex: 1, textAlign: "left" }}><span className="ro-n">{r.id === "admin" ? "โหมดผู้ดูแลระบบ" : "โหมดผู้บริหาร"}</span><span className="ro-d">แตะเพื่อสลับโหมด</span></span>
            <span style={{ color: "var(--faint)" }}>{IC.chevR}</span>
          </button>
          {extra.map((it) =>
          <a key={it.id} href={"#/" + it.id} onClick={onClose}
          style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 12px", minHeight: 48, borderRadius: 12, fontSize: 15, fontWeight: 600, color: screen === it.id ? "var(--accent)" : "var(--ink)" }}>
              <span style={{ color: screen === it.id ? "var(--accent)" : "var(--muted)" }}>{IC[it.icon]}</span>{it.label}
            </a>
          )}
          <RoleSwitcher role={role} setRole={setRole} open={swOpen} onClose={() => {setSwOpen(false);onClose();}} anchor="mobile" />
        </div>
      </div>);

  }

  window.AppShell = function AppShell() {
    const route = window.useRoute();
    const [moreOpen, setMoreOpen] = useState(false);
    const [theme, toggleTheme] = window.useTheme();
    const [role, setRole] = window.useRole();
    const r = D.roles[role];
    // redirect if current screen not allowed for role
    useEffect(() => {
      if (!r.nav.includes(route.screen) && route.screen !== "project") window.navigate("dashboard");
    }, [role, route.screen]);
    let Screen = window.SCREENS && window.SCREENS[route.screen] || window.SCREENS.dashboard;
    useEffect(() => {setMoreOpen(false);}, [route.screen, route.id]);

    const [protoDismissed, setProtoDismissed] = useState(() => { try {return sessionStorage.getItem("bp-proto-dismiss") === "1";} catch (e) {return false;} });
    const dismissProto = () => { try {sessionStorage.setItem("bp-proto-dismiss", "1");} catch (e) {} setProtoDismissed(true); };

    const openSearch = () => window.dispatchEvent(new CustomEvent("open-search"));

    return (
      <div className="app">
        <Sidebar screen={route.screen} role={role} setRole={setRole} />
        <div className="app-main">
          <header className="appbar">
            <a className="brand" href="#/dashboard">
              <div className="mark" style={{ backgroundColor: "rgb(0,0,0)" }}>BT</div>
              <div className="bn"><b>BANK PROJECT</b><small>Project Intelligence</small></div>
            </a>
            <button className="search" onClick={openSearch}>
              {IC.search}<span className="search-ph">ค้นหาโครงการ, ประชุม, เอกสาร, Decision…</span>
              <span className="kbd">⌘K</span>
            </button>
            <div className="spacer" />
            <button className="icon-btn m-search" onClick={openSearch}>{IC.search}</button>
            <button className="icon-btn" onClick={toggleTheme} title={theme === "dark" ? "โหมดสว่าง" : "โหมดมืด"} aria-label="สลับธีม">{theme === "dark" ? IC.sun : IC.moon}</button>
            <button className="icon-btn">{IC.bell}<span className="dot" /></button>
            <span className={"avatar md role-av " + r.color} style={{ marginLeft: 4, color: "rgb(255, 255, 255)", backgroundColor: "rgb(60, 60, 60)" }}>{r.id === "admin" ? "AD" : "ผบ"}</span>
          </header>

          {role === "admin" && !protoDismissed &&
          <div className="proto-banner">
              <span>⚠️ นี่คือ UI Prototype — ข้อมูลจำลองเท่านั้น</span>
              <button className="proto-x" onClick={dismissProto} aria-label="ปิดแถบ">{IC.x}</button>
            </div>
          }

          <main>
            <window.ScreenHost screenKey={route.screen + ":" + (route.id || "") + ":" + role}>
              <Screen route={route} role={role} />
            </window.ScreenHost>
          </main>
        </div>

        <nav className="bottomnav">
          {MOBILE_NAV.map((it) => {
            if (it.id !== "__more" && !r.nav.includes(it.id)) return null;
            const on = it.id === "__more" ? moreOpen : route.screen === it.id;
            if (it.id === "__more")
            return <a key={it.id} href="#" onClick={(e) => {e.preventDefault();setMoreOpen(true);}} className={on ? "on" : ""}>{IC[it.icon]}<span>{it.label}</span></a>;
            return <a key={it.id} href={"#/" + it.id} className={on ? "on" : ""}>{IC[it.icon]}<span>{it.label}</span></a>;
          })}
        </nav>
        <MoreSheet open={moreOpen} onClose={() => setMoreOpen(false)} screen={route.screen} role={role} setRole={setRole} />
        {window.CommandPalette && <window.CommandPalette />}
        {window.ReportModal && <window.ReportModal />}
        {window.LoginModal && <window.LoginModal />}
        <Toast />
      </div>);

  };
})();