/* Kay Construction — app shell: login gate, sidebar nav, hash router, topbar. */

function useHash() {
  const [hash, setHash] = useState(window.location.hash || "#/dashboard");
  useEffect(() => {
    const h = () => { setHash(window.location.hash || "#/dashboard"); window.scrollTo(0, 0); };
    window.addEventListener("hashchange", h);
    return () => window.removeEventListener("hashchange", h);
  }, []);
  return hash;
}
function parseRoute(hash) {
  const clean = hash.replace(/^#\/?/, "").split("?")[0];
  const parts = clean.split("/").filter(Boolean);
  return parts.length ? parts : ["dashboard"];
}
function routeQuery(hash) {
  const qi = hash.indexOf("?");
  const out = {};
  if (qi >= 0) hash.slice(qi + 1).split("&").forEach((kv) => { const [k, v] = kv.split("="); if (k) out[decodeURIComponent(k)] = decodeURIComponent(v || ""); });
  return out;
}

const NAV = [
  { group: "nav.financeOps", items: [
    { key: "dashboard", icon: "dashboard", path: "#/dashboard", label: "nav.dashboard" },
    { key: "proyek", icon: "projects", path: "#/proyek", label: "nav.projects" },
    { key: "klien", icon: "clients", path: "#/klien", label: "nav.clients" },
    { key: "pengeluaran", icon: "expenses", path: "#/pengeluaran", label: "nav.expenses" }
  ] },
  { group: "nav.docGen", items: [
    { key: "rab", icon: "rab", path: "#/dokumen/rab", label: "nav.rab" },
    { key: "penawaran", icon: "quotation", path: "#/dokumen/penawaran", label: "nav.quotation" },
    { key: "tambah-kurang", icon: "swap", path: "#/dokumen/tambah-kurang", label: "nav.addendum" },
    { key: "spk", icon: "spk", path: "#/dokumen/spk", label: "nav.spk" },
    { key: "invoice", icon: "invoice", path: "#/dokumen/invoice", label: "nav.invoice", badge: true },
    { key: "kwitansi", icon: "kwitansi", path: "#/dokumen/kwitansi", label: "nav.kwitansi" }
  ] },
  { group: "nav.opsExtra", items: [
    { key: "harga", icon: "tag", path: "#/harga", label: "nav.pricebook" },
    { key: "laporan", icon: "report", path: "#/laporan", label: "nav.reports" }
  ] }
];

function Sidebar({ activeKey, open, onClose }) {
  useStore();
  const overdueCount = S.outstandingInvoices().filter((r) => r.overdueDays > 0).length;
  return (
    <aside className={"sidebar" + (open ? " open" : "")}>
      <div className="brand">
        <div className="word">KAY</div>
        <div className="sub">Construction</div>
      </div>
      <nav className="nav">
        {NAV.map((grp) => (
          <div key={grp.group}>
            <div className="nav-group-label">{t(grp.group)}</div>
            {grp.items.map((it) => (
              <div key={it.key} className={"nav-item" + (activeKey === it.key ? " active" : "")}
                onClick={() => { go(it.path); onClose && onClose(); }}>
                <Icon name={it.icon} size={17} className="nav-ico" />
                <span>{t(it.label)}</span>
                {it.badge && overdueCount > 0 && <span className="nav-badge">{overdueCount}</span>}
              </div>
            ))}
          </div>
        ))}
      </nav>
      <div style={{ padding: "0 12px 8px" }}>
        <div className={"nav-item" + (activeKey === "pengaturan" ? " active" : "")} onClick={() => { go("#/pengaturan"); onClose && onClose(); }}>
          <Icon name="settings" size={17} className="nav-ico" />
          <span>{t("nav.settings")}</span>
        </div>
      </div>
      <div className="sidebar-foot">
        {(S.getDB().company || {}).legalName || "Ketut Adi Yoga"}<br />
        <span style={{ opacity: .7 }}>app.kayconstruction.id</span>
      </div>
    </aside>
  );
}

function Topbar({ onMenu }) {
  const [lang, setLang] = useLang();
  const crumbLabel = () => {
    const r = parseRoute(window.location.hash);
    return r;
  };
  return (
    <header className="topbar no-print">
      <div className="row" style={{ gap: 14 }}>
        <button className="btn icon ghost menu-btn" id="menuBtn" onClick={onMenu}><Icon name="menu" size={18} /></button>
        <Breadcrumb />
      </div>
      <div className="row" style={{ gap: 14 }}>
        <div className="row" style={{ gap: 8 }}>
          <span className="tiny muted" style={{ fontWeight: 600 }}>{t("common.language")}</span>
          <Segmented value={lang} onChange={setLang} options={[{ value: "id", label: "ID" }, { value: "en", label: "EN" }]} />
        </div>
        <div className="row" style={{ gap: 9, paddingLeft: 14, borderLeft: "1px solid var(--line)" }}>
          <div className="avatar sm">{(((S.getDB().company || {}).ownerName) || "K").charAt(0)}</div>
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontWeight: 600, fontSize: 13 }}>{((S.getDB().company || {}).ownerName) || "Ketut Adi Yoga"}</div>
            <div className="tiny muted" style={{ cursor: "pointer" }} onClick={() => { localStorage.removeItem("kay_auth"); window.dispatchEvent(new Event("kay-auth")); }}>{t("login.signout")}</div>
          </div>
        </div>
      </div>
    </header>
  );
}

function Breadcrumb() {
  useHash();
  useStore();
  const r = parseRoute(window.location.hash);
  const map = {
    dashboard: t("nav.dashboard"), proyek: t("nav.projects"), klien: t("nav.clients"),
    pengeluaran: t("nav.expenses"), pengaturan: t("nav.settings"), dokumen: t("nav.documents"),
    rab: t("nav.rab"), penawaran: t("nav.quotation"), spk: t("nav.spk"), invoice: t("nav.invoice"),
    kwitansi: t("nav.kwitansi"), baru: t("common.new"),
    harga: t("nav.pricebook"), laporan: t("nav.reports"), "tambah-kurang": t("nav.addendum")
  };
  const crumbs = [];
  if (r[0] === "dokumen") { crumbs.push(map.dokumen); if (r[1]) crumbs.push(map[r[1]] || r[1]); if (r[2] === "baru") crumbs.push(t("common.new")); }
  else { crumbs.push(map[r[0]] || r[0]); if (r[1] === "baru") crumbs.push(t("common.new")); }
  return (
    <div className="row" style={{ gap: 8, fontSize: 13 }}>
      {crumbs.map((c, i) => (
        <span key={i} className="row" style={{ gap: 8, color: i === crumbs.length - 1 ? "var(--ink)" : "var(--muted)", fontWeight: i === crumbs.length - 1 ? 600 : 500 }}>
          {i > 0 && <span className="muted">/</span>}{c}
        </span>
      ))}
    </div>
  );
}

/* ---------------- login ---------------- */
function Login({ onLogin }) {
  const [lang, setLang] = useLang();
  useStore();
  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--paper)", padding: 24 }}>
      <div style={{ position: "absolute", top: 24, right: 24 }}>
        <Segmented value={lang} onChange={setLang} options={[{ value: "id", label: "ID" }, { value: "en", label: "EN" }]} />
      </div>
      <div style={{ width: 380, maxWidth: "100%" }}>
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <img src="assets/kay-logo.png" alt="Kay Construction" style={{ width: 150, height: 150, objectFit: "contain", margin: "0 auto" }} />
          <div className="serif" style={{ fontSize: 13, letterSpacing: "0.28em", textTransform: "uppercase", color: "var(--muted)", marginTop: 4 }}>{t("login.welcome")}</div>
        </div>
        <div className="card pad">
          <form onSubmit={(e) => { e.preventDefault(); onLogin(); }}>
            <Field label={t("login.email")}>
              <Input type="email" defaultValue="admin@kayconstruction.id" />
            </Field>
            <Field label={t("login.password")}>
              <Input type="password" defaultValue="demo1234" />
            </Field>
            <Button variant="primary" type="submit" style={{ width: "100%", marginTop: 6 }}>{t("login.signin")}</Button>
          </form>
          <div className="tiny muted" style={{ textAlign: "center", marginTop: 14 }}>{t("login.hint")}</div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- router (pure: no hooks) ---------------- */
function renderRoute(hash) {
  const r = parseRoute(hash);
  const P = window; // page components live on window

  // print view: #/cetak/:type/:id
  if (r[0] === "cetak") return { node: P.PrintDoc ? <P.PrintDoc type={r[1]} id={r[2]} /> : null, activeKey: "cetak" };

  let node = null, activeKey = r[0];
  const Missing = ({ name }) => <Empty icon="wand" title={name} sub="Halaman ini sedang dibangun." />;

  if (r[0] === "dashboard") node = P.Dashboard ? <P.Dashboard /> : <Missing name="Dashboard" />;
  else if (r[0] === "proyek") {
    if (r[1] && r[1] !== "baru") node = P.ProjectDetail ? <P.ProjectDetail id={r[1]} /> : <Missing name="Proyek" />;
    else node = P.ProjectsList ? <P.ProjectsList createNew={r[1] === "baru"} /> : <Missing name="Proyek" />;
  }
  else if (r[0] === "klien") {
    if (r[1] && r[1] !== "baru") node = P.ClientDetail ? <P.ClientDetail id={r[1]} /> : <Missing name="Klien" />;
    else node = P.ClientsList ? <P.ClientsList createNew={r[1] === "baru"} /> : <Missing name="Klien" />;
  }
  else if (r[0] === "dokumen") {
    const type = r[1];
    const editors = { rab: "RabEditor", penawaran: "QuotationEditor", "tambah-kurang": "AddendumEditor", spk: "SpkEditor", invoice: "InvoiceEditor", kwitansi: "KwitansiEditor" };
    const lists = { rab: "RabList", penawaran: "QuotationList", "tambah-kurang": "AddendumList", spk: "SpkList", invoice: "InvoiceList", kwitansi: "KwitansiList" };
    activeKey = type;
    if (r[2] && r[2] !== "baru") { const C = P[editors[type]]; node = C ? <C id={r[2]} /> : <Missing name={type} />; }
    else if (r[2] === "baru") { const C = P[editors[type]]; node = C ? <C createNew /> : <Missing name={type} />; }
    else { const C = P[lists[type]]; node = C ? <C /> : <Missing name={type} />; }
  }
  else if (r[0] === "pengeluaran") node = P.ExpensesPage ? <P.ExpensesPage /> : <Missing name="Pengeluaran" />;
  else if (r[0] === "harga") node = P.PriceBookPage ? <P.PriceBookPage /> : <Missing name="Harga" />;
  else if (r[0] === "laporan") node = P.ReportsPage ? <P.ReportsPage /> : <Missing name="Laporan" />;
  else if (r[0] === "pengaturan") node = P.SettingsPage ? <P.SettingsPage /> : <Missing name="Pengaturan" />;
  else node = P.Dashboard ? <P.Dashboard /> : <Missing name="Dashboard" />;

  return { node, activeKey };
}

function App() {
  const [authed, setAuthed] = useState(!!localStorage.getItem("kay_auth"));
  const [menuOpen, setMenuOpen] = useState(false);
  const hash = useHash();
  useStore();

  useEffect(() => {
    S.seedIfEmpty();
    const onAuth = () => setAuthed(!!localStorage.getItem("kay_auth"));
    window.addEventListener("kay-auth", onAuth);
    return () => window.removeEventListener("kay-auth", onAuth);
  }, []);
  useEffect(() => { setMenuOpen(false); }, [hash]);

  if (!authed) return <Login onLogin={() => { localStorage.setItem("kay_auth", "1"); setAuthed(true); }} />;

  const r = parseRoute(hash);
  // print view = no chrome
  if (r[0] === "cetak") { const { node } = renderRoute(hash); return node; }

  const { node, activeKey } = renderRoute(hash);
  return (
    <div className="app">
      <Sidebar activeKey={activeKey} open={menuOpen} onClose={() => setMenuOpen(false)} />
      {menuOpen && <div className="scrim no-print" onClick={() => setMenuOpen(false)}></div>}
      <div className="main">
        <Topbar onMenu={() => setMenuOpen((o) => !o)} />
        <div className="content">{node}</div>
      </div>
    </div>
  );
}

Object.assign(window, { go, routeQuery, useHash });
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
