/* ============================================================
   app.jsx — root: real auth + role-based render + mount
   No persona switcher: the signed-in user's role decides the app.
   A tokenised email link (?token=) opens the public approval page.
   ============================================================ */

const ROLE_LABEL = {
  brand_ops: "Brand Ops", finance: "Finance team",
  nakad: "Nakad admin", admin: "Lekha admin",
};

function viewForRole(role) {
  if (role === "brand_ops") return BrandOpsApp;
  if (role === "finance") return FinanceApp;
  if (role === "nakad") return NakadApp;
  return AdminApp;
}

/* ---- Account menu — clean top-bar identity chip + dropdown ----------------
   Replaces the raw "Reset demo / Log out" buttons. Navigation items dispatch a
   global `lekha-nav` event that the active persona app listens for (so the chip
   can jump to Team/Settings without owning their tab state). Profile opens a
   modal over the signed-in user's REAL fields — no invented data. */
function AccountMenu({ user, logout, store }) {
  const [open, setOpen] = React.useState(false);
  const [profileOpen, setProfileOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const away = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", away);
    return () => document.removeEventListener("mousedown", away);
  }, [open]);

  const go = (tab) => { setOpen(false); window.dispatchEvent(new CustomEvent("lekha-nav", { detail: tab })); };
  const av = (user.name || "?").slice(0, 2).toUpperCase();
  const hasTabs = user.role === "finance" || user.role === "brand_ops";
  const item = (label, onClick, danger) => (
    <button className="am-item" style={danger ? { color: "#e06a5a" } : null}
      onClick={onClick}>{label}</button>
  );

  return (
    <div className="am-wrap" ref={ref}>
      <button className="am-chip" onClick={() => setOpen((v) => !v)}>
        <span className="am-av">{av}</span>
        <span className="am-name">{user.name}</span>
        <Ic.chevron style={{ transform: open ? "rotate(90deg)" : "none", transition: "transform .15s" }} />
      </button>
      {open && (
        <div className="am-menu">
          <div className="am-head">
            <div className="am-head-name">{user.name}</div>
            <div className="am-head-sub">{user.email || ""}</div>
            <div className="am-head-role">{ROLE_LABEL[user.role] || user.role}</div>
          </div>
          {item("Profile", () => { setOpen(false); setProfileOpen(true); })}
          {hasTabs && item("Team", () => go("team"))}
          {hasTabs && item("Settings", () => go("notif"))}
          <div className="am-div" />
          {item("Log out", () => { setOpen(false); logout(); }, true)}
        </div>
      )}
      {profileOpen && <ProfileModal user={user} onClose={() => setProfileOpen(false)} />}
    </div>
  );
}

function ProfileModal({ user, onClose }) {
  const row = (k, v) => v ? (
    <div className="row" style={{ justifyContent: "space-between", padding: "8px 0", borderBottom: "1px solid var(--border)" }}>
      <span className="tiny" style={{ color: "var(--text-3)" }}>{k}</span>
      <span style={{ fontWeight: 600 }}>{v}</span>
    </div>
  ) : null;
  return (
    <div className="am-overlay" onMouseDown={onClose}>
      <div className="card card-pad" style={{ width: "min(420px, 92vw)" }} onMouseDown={(e) => e.stopPropagation()}>
        <div className="row" style={{ justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
          <div className="section-title">Profile</div>
          <button className="icon-btn" onClick={onClose}><Ic.x /></button>
        </div>
        {row("Name", user.name)}
        {row("Email", user.email)}
        {row("Role", ROLE_LABEL[user.role] || user.role)}
        {row("Company", user.company_name || user.business_name)}
      </div>
    </div>
  );
}

function AuthedApp({ user, logout }) {
  const store = useStore();
  store.user = user;      // expose signed-in identity (role + brand) to personas
  store.logout = logout;  // so the AppHeader account menu can sign out
  const View = viewForRole(user.role);
  return (
    <div className="stage">
      <View store={store} />
      <Toasts toasts={store.toasts} />
    </div>
  );
}

/* ---- Onboarding (spec Screen 2 — Tally detection: 2A confirm / 2B mismatch / 2C none) ----
   Runs once right after signup. In the desktop app it probes the open Tally company
   (tally_list_companies) and asks the backend /detect to compare it with the account
   company; auto-polls every 5s so a company switch resolves without clicking. In the web
   app (no Tally probe) it goes straight to the confirm-details step. */
function Onboarding({ onDone, logout }) {
  const [state, setState] = React.useState("checking");  // checking|not_detected|mismatch|matched
  const [info, setInfo] = React.useState({});
  const [gstin, setGstin] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const invoke = () => (window.__TAURI__ && window.__TAURI__.core && window.__TAURI__.core.invoke) || null;

  const probe = React.useCallback(async () => {
    const inv = invoke();
    let open_name = null, tally_online = false;
    if (inv) {
      try {
        const xml = await inv("tally_list_companies");
        const m = xml && xml.match(/<COMPANY NAME="([^"]+)"/i);
        open_name = m ? m[1] : null; tally_online = !!open_name;
      } catch (_) { tally_online = false; }
    }
    let r;
    try { r = await api.post("/api/desktop/detect", { open_name, tally_online }); }
    catch (_) { return; }
    if (!r || !r.bound) { onDone(); return; }              // no bound company → skip onboarding
    setInfo(r);
    if (!inv) { setState("matched"); return; }             // web app (no Tally probe) → confirm directly
    setState(r.state || "not_detected");
    if (r.state === "matched") setGstin((g) => g || r.expected_gstin || "");
  }, [onDone]);

  React.useEffect(() => {
    if (state === "matched") return;                       // confirming → stop detecting
    probe();
    const t = setInterval(probe, 5000);
    return () => clearInterval(t);
  }, [probe, state]);

  const save = async () => {
    setErr(""); setBusy(true);
    try { await api.post("/api/desktop/company-details", { gstin: gstin.trim() }); onDone(); }
    catch (e) { setErr((e && e.message) || "Couldn't save — check the GSTIN."); setBusy(false); }
  };

  const shell = (children) => (
    <div style={{ minHeight: "100vh", background: "var(--bg)", display: "grid", placeItems: "center", padding: "32px 18px" }}>
      <div style={{ width: "min(460px, 100%)" }}>
        <div style={{ textAlign: "center", marginBottom: 16 }}>
          <div style={{ fontFamily: "var(--serif)", fontWeight: 800, fontSize: 30, color: "var(--lime-ink)" }}>Lekha AI</div>
        </div>
        <div className="card card-pad">{children}</div>
        <div className="tiny" style={{ textAlign: "center", marginTop: 14 }}>
          <a href="#" onClick={(e) => { e.preventDefault(); logout(); }} style={{ color: "var(--text-3)" }}>Log out</a>
        </div>
      </div>
    </div>
  );

  if (state === "checking")
    return shell(<div className="tiny">Detecting TallyPrime on this PC…</div>);

  if (state === "not_detected")
    return shell(
      <div>
        <div className="section-title">Open Tally to continue</div>
        <div className="tiny" style={{ marginTop: 6 }}>
          Lekha can't detect TallyPrime on this computer. Open TallyPrime with <b>{info.company_name}</b> loaded — this screen continues automatically.
        </div>
      </div>
    );

  if (state === "mismatch")
    return shell(
      <div>
        <div className="section-title" style={{ color: "#c0392b" }}>Wrong company open in Tally</div>
        <div className="tiny" style={{ marginTop: 8 }}>
          <div style={{ marginBottom: 6 }}>Expected: <b>{info.company_name}</b> (your account)</div>
          <div style={{ marginBottom: 10 }}>Found: <b>{info.open_name || "another company"}</b> (open in Tally)</div>
          <div>In Tally press <b>F3</b> → select <b>{info.company_name}</b>. This screen continues automatically when it matches.</div>
        </div>
      </div>
    );

  // matched → Screen 2A confirm details
  return shell(
    <div>
      <div className="section-title">Confirm company details</div>
      <div className="tiny" style={{ margin: "6px 0 12px" }}>We detected your company. Review and complete before your first posting.</div>
      <div style={{ marginBottom: 12 }}>
        <div className="tiny" style={{ marginBottom: 4, color: "var(--text-3)" }}>COMPANY NAME</div>
        <div style={{ padding: "10px 12px", background: "#1c1c1d", border: "1px solid var(--border)", borderRadius: 8, fontWeight: 600 }}>
          {info.company_name || ""} <span className="tiny" style={{ color: "var(--text-3)" }}>· locked</span>
        </div>
      </div>
      <Field label="GSTIN" value={gstin} onChange={(e) => setGstin(e.target.value.toUpperCase())}
        placeholder="27AAAAA0000A1Z5" hint="State is derived from the GSTIN automatically." />
      {err && <div className="tiny" style={{ color: "#c0392b", marginTop: 4 }}>{err}</div>}
      <div className="row gap10" style={{ marginTop: 16 }}>
        <button className="btn btn-primary btn-lg" disabled={busy} onClick={save} style={{ flex: 1, justifyContent: "center" }}>
          {busy ? "Saving…" : "Save & continue"}
        </button>
        <button className="btn btn-ghost btn-lg" disabled={busy} onClick={onDone} style={{ justifyContent: "center" }}>
          Skip for now
        </button>
      </div>
    </div>
  );
}

function Root() {
  const { user, ready, login, googleLogin, signup, logout } = useAuth();
  const [onboarding, setOnboarding] = React.useState(false);
  const doSignup = async (payload) => { const r = await signup(payload); setOnboarding(true); return r; };
  if (!ready) return <div style={{ minHeight: "100vh", background: "var(--bg)", display: "grid", placeItems: "center", color: "var(--text-3)" }}>Loading…</div>;
  if (!user) return <LoginScreen onLogin={login} onGoogleLogin={googleLogin} onSignup={doSignup} />;
  if (onboarding && user.role === "finance") return <Onboarding onDone={() => setOnboarding(false)} logout={logout} />;
  return <AuthedApp user={user} logout={logout} />;
}

// a tokenised email-link (?token=) opens the standalone approval landing
// (public — no login); otherwise the authenticated app mounts.
const _token = new URLSearchParams(window.location.search).get("token");
ReactDOM.createRoot(document.getElementById("root"))
  .render(_token ? <ApprovalLanding token={_token} /> : <Root />);
