// Main app — shell, nav, persona switching, page routing

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "persona": "fbp",
  "scopeFilter": "All in scope",
  "density": "comfortable",
  "showAuditTrail": true
}/*EDITMODE-END*/;

// Nav groups
const NAV_GROUPS = [
  {
    label: "Rates",
    items: [
      { id: "rates", label: "Rate Repository", icon: "table" },
      { id: "health", label: "Rate Health", icon: "shield" },
      { id: "roe",   label: "ROE Table", icon: "globe" },
      { id: "calc",  label: "Rate Calculator", icon: "calc" },
      { id: "ai",    label: "AI Assistant", icon: "sparkle" },
      { id: "export",label: "Export", icon: "export" },
    ],
  },
  {
    label: "Contracts & Finance",
    items: [
      { id: "rebate", label: "Rebate Monitor", icon: "key" },
      { id: "volume", label: "Volume Tracker", icon: "table" },
      { id: "tco",    label: "TCO Analysis", icon: "bolt" },
    ],
  },
  {
    label: "Access",
    items: [
      { id: "access", label: "Access Requests", icon: "key" },
    ],
  },
  {
    label: "Administration",
    items: [
      { id: "admin", label: "Admin Console", icon: "settings", adminOnly: true },
    ],
  },
  {
    label: "Resources",
    items: [
      { id: "docs", label: "Documentation", icon: "book" },
    ],
  },
];

function canSee(page, perms) {
  if (perms.accessOnly) return page === "access" || page === "docs";
  switch (page) {
    case "rates":  return perms.viewRates;
    case "health": return perms.rateHealth;
    case "roe":    return perms.roeTable;
    case "calc":   return true;
    case "ai":     return perms.aiAssistant;
    case "export": return perms.export;
    case "rebate": return perms.rebateMonitor;
    case "volume": return perms.volumeTracker;
    case "tco":    return perms.tcoAnalysis;
    case "access": return true;
    case "admin":  return perms.admin;
    case "docs":   return true;
  }
  return true;
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Use real SSO user when available; fall back to persona simulator for local dev
  const [ssoUser, setSsoUser] = useState(window.OCMS_USER || null);
  const [permsMap, setPermsMap] = useState(window.OCMS_PERMS || PERMS);
  const [tweaksPanelOpen, setTweaksPanelOpen] = useState(false);

  useEffect(() => {
    const handler = (e) => {
      setSsoUser(e.detail);
      if (e.detail?.role && PERSONAS[e.detail.role]) {
        setTweak("persona", e.detail.role);
      }
    };
    window.addEventListener('ocms:user-ready', handler);
    return () => window.removeEventListener('ocms:user-ready', handler);
  }, []);

  useEffect(() => {
    const handler = (e) => setPermsMap(e.detail);
    window.addEventListener('ocms:perms-ready', handler);
    return () => window.removeEventListener('ocms:perms-ready', handler);
  }, []);

  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__edit_mode_dismissed') {
        setTweaksPanelOpen(false);
        if (ssoUser?.role && PERSONAS[ssoUser.role]) {
          setTweak("persona", ssoUser.role);
        }
        // Refresh permissions from API in case admin changed them
        if (window.OCMS_PERMS) setPermsMap({ ...window.OCMS_PERMS });
      }
    };
    window.addEventListener('message', onMsg);
    return () => window.removeEventListener('message', onMsg);
  }, [ssoUser]);

  const _devEnv  = ['localhost', '127.0.0.1', 'ocms-cdt.maersk.io'].includes(window.location.hostname);
  const _isAdmin = ssoUser
    ? (ssoUser.role === 'admin' || (window.location.hostname === 'localhost' && ssoUser.roles.length === 0))
    : true;
  const showTweaks = _devEnv && _isAdmin;

  // Persona switcher only overrides when TweaksPanel is actually open
  const user  = (showTweaks && tweaksPanelOpen) ? (PERSONAS[tweaks.persona] || PERSONAS.fbp) : (ssoUser || PERSONAS.fbp);
  const perms = user.role === 'unknown' ? PERMS.unknown : (permsMap[user.role] || permsMap.read || PERMS.read);

  const defaultPage = NAV_GROUPS.flatMap(g => g.items).map(i => i.id).find(p => canSee(p, perms));
  const [page, setPage] = useState(defaultPage || "calc");
  useEffect(() => {
    if (!canSee(page, perms)) setPage(defaultPage || "calc");
  }, [tweaks.persona]);

  const [showWelcome, setShowWelcome] = useState(true);
  const dismissWelcome = () => setShowWelcome(false);

  const [openRate, setOpenRate] = useState(null);
  const [showAdd, setShowAdd] = useState(false);
  const [showAddPrefill, setShowAddPrefill] = useState(null);
  const [showImport, setShowImport] = useState(false);
  const [showAI, setShowAI] = useState(false);
  const [toast, setToast] = useState("");
  const [rateRefreshKey, setRateRefreshKey] = useState(0);
  const [rateNavCount, setRateNavCount] = useState(null);
  const [accessPendingCount, setAccessPendingCount] = useState(0);
  const [accessCountKey, setAccessCountKey] = useState(0);

  useEffect(() => {
    apiFetch("/api/rates/count").then(r => {
      if (r?.total != null) setRateNavCount(r.total);
    }).catch(() => {});
  }, [rateRefreshKey]);

  // Fetch pending access request count — returns 0 for non-approvers without 403
  useEffect(() => {
    if (!ssoUser) return;
    apiFetch("/api/access-requests/pending-count")
      .then(r => setAccessPendingCount(r?.count ?? 0))
      .catch(() => setAccessPendingCount(0));
  }, [ssoUser, accessCountKey]);

  const fmtCount = n => n == null ? "" : n >= 1000 ? (n / 1000).toFixed(1).replace(/\.0$/, "") + "k" : String(n);

  const allNavItems = NAV_GROUPS.flatMap(g => g.items);
  const pageMeta = allNavItems.find(p => p.id === page);
  const groupMeta = NAV_GROUPS.find(g => g.items.some(i => i.id === page));

  return (
    <div className="app" data-screen-label="TCMS">
      {/* SIDEBAR */}
      <aside className="sidebar" data-screen-label="Sidebar">
        <div className="brand">
          <div className="brand-mark">T</div>
          <div className="brand-name">
            <b>TCMS</b>
            <span>Ocean Finance · APA</span>
          </div>
        </div>
        <div className="nav">
          {NAV_GROUPS.map(g => {
            const visibleItems = g.items.filter(it => canSee(it.id, perms) || it.adminOnly);
            if (visibleItems.length === 0) return null;
            // hide admin group for non-admin
            if (g.label === "Administration" && !perms.admin) return null;
            return (
              <React.Fragment key={g.label}>
                <div className="nav-label">{g.label}</div>
                {visibleItems.map(p => {
                  const ok = canSee(p.id, perms);
                  return (
                    <button key={p.id} className={`nav-item ${page === p.id ? "active" : ""} ${!ok ? "disabled" : ""}`}
                      onClick={() => ok && setPage(p.id)}>
                      <Icon name={p.icon} size={15} className="nav-icon" />
                      {p.label}
                      {p.id === "rates" && perms.viewRates && rateNavCount != null && <span className="nav-count">{fmtCount(rateNavCount)}</span>}
                      {p.id === "ai" && perms.aiAssistant && <span className="nav-count" style={{ background: "#14a3bd", color: "#061425" }}>AI</span>}
                      {p.id === "health" && perms.rateHealth && <span className="nav-count" style={{ background: "#b86a1b", color: "#fff" }}>{VALIDATION_RESULTS.filter(r=>r.severity==="Error").length}</span>}
                      {p.id === "rebate" && perms.rebateMonitor && <span className="nav-count">{REBATES.length}</span>}
                      {p.id === "access" && accessPendingCount > 0 && <span className="nav-count" style={{ background: "var(--amber)", color: "#fff" }}>{accessPendingCount}</span>}
                      {p.id === "docs" && <span className="nav-count" style={{ background: "#14a3bd", color: "#061425" }}>v1.1</span>}
                    </button>
                  );
                })}
              </React.Fragment>
            );
          })}
        </div>
        <div className="sidebar-foot" style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <span>v1.1.0-rc.2 · APA<br /><span style={{ color: "#9bb0c8" }}>Last sync 2 min ago</span></span>
          {showTweaks && (
            <button title="Tweaks panel" onClick={() => { setTweaksPanelOpen(true); window.postMessage({ type: '__activate_edit_mode' }, '*'); }}
              style={{ background: "transparent", border: "1px solid #2a4a6c", borderRadius: 5, color: "#6a85a3", padding: "4px 7px", fontSize: 13, cursor: "pointer", lineHeight: 1 }}>
              ⚙
            </button>
          )}
        </div>
      </aside>

      {/* TOP BAR */}
      <header className="topbar">
        <div className="crumb">
          <span className="ghost">APA Ocean Finance</span>
          <span className="sep">/</span>
          {groupMeta && <><span className="ghost">{groupMeta.label}</span><span className="sep">/</span></>}
          <span className="here">{pageMeta?.label || "—"}</span>
        </div>
        <div className="top-right">
          <div className="scope" style={{ position: "relative" }} onMouseEnter={e => { const t = e.currentTarget.querySelector(".scope-tip"); if (t) t.style.display = "block"; }} onMouseLeave={e => { const t = e.currentTarget.querySelector(".scope-tip"); if (t) t.style.display = "none"; }}>
            <Icon name="pin" size={11} />
            Scope:
            <b>{user.regions.length > 1 ? `${user.regions.length} regions` : (user.regions[0] || "—")}</b>
            {(user.regions.length > 0 && user.regions[0] !== "—") || user.areas?.length > 0 ? (
              <div className="scope-tip" style={{ display: "none", position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 500, background: "var(--ink)", color: "#fff", borderRadius: 8, padding: "10px 14px", minWidth: 200, maxWidth: 320, boxShadow: "0 4px 16px rgba(0,0,0,.25)", fontSize: 12, lineHeight: 1.6, whiteSpace: "normal" }}>
                <div style={{ fontWeight: 600, marginBottom: 6, color: "var(--teal-light, #4dd9c0)" }}>Regions</div>
                {user.regions.map(r => <div key={r} style={{ marginBottom: 2 }}>· {r}</div>)}
                {user.areas && user.areas.length > 0 && (
                  <>
                    <div style={{ fontWeight: 600, marginTop: 8, marginBottom: 6, color: "var(--teal-light, #4dd9c0)" }}>Areas</div>
                    {user.areas.map(a => <div key={a} style={{ marginBottom: 2 }}>· {a}</div>)}
                  </>
                )}
              </div>
            ) : null}
          </div>
          {perms.aiAssistant && (
            <button className="icon-btn" onClick={() => setShowAI(true)} title="AI Assistant">
              <Icon name="sparkle" size={14} stroke="var(--teal)" />
            </button>
          )}
          <button className="icon-btn" title="Notifications">
            <Icon name="bell" size={14} />
            <span style={{ position: "absolute", top: 6, right: 6, width: 6, height: 6, background: "var(--amber)", borderRadius: "50%", boxShadow: "0 0 0 2px #fff" }} />
          </button>
          <div className="user-chip">
            <Avatar user={ssoUser || user} size={26} />
            <div>
              <div className="name">{ssoUser ? ssoUser.name : user.name}</div>
              <div className="role">{user.role}</div>
            </div>
          </div>
        </div>
      </header>

      {/* MAIN */}
      <main className="main">
        {page === "rates" && perms.viewRates && (
          <RateList user={user} perms={perms}
            onOpenRate={setOpenRate}
            onAdd={() => setShowAdd(true)}
            onAddPrefill={(prefill) => { setShowAddPrefill(prefill); setShowAdd(true); }}
            onImport={() => setShowImport(true)}
            onOpenAI={() => setShowAI(true)}
            onToast={setToast}
            refreshKey={rateRefreshKey} />
        )}
        {page === "rates" && !perms.viewRates && <NoAccess role={user.role} feature="Rate Repository" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "health" && perms.rateHealth && (
          <RateHealth user={user} perms={perms} onAddRate={(prefill) => { setShowAddPrefill(prefill); setShowAdd(true); }} />
        )}
        {page === "health" && !perms.rateHealth && <NoAccess role={user.role} feature="Rate Health" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "roe" && perms.roeTable && <ROETable />}
        {page === "roe" && !perms.roeTable && <NoAccess role={user.role} feature="ROE Table" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "calc" && <Calculator user={user} perms={perms} />}

        {page === "ai" && perms.aiAssistant && <AIAssistant user={user} perms={perms} />}
        {page === "ai" && !perms.aiAssistant && <NoAccess role={user.role} feature="AI Assistant" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "export" && perms.export && <ExportPage user={user} />}
        {page === "export" && !perms.export && <NoAccess role={user.role} feature="Export" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "rebate" && canSee("rebate", perms) && <RebateMonitor user={user} perms={perms} />}
        {page === "rebate" && !canSee("rebate", perms) && <NoAccess role={user.role} feature="Rebate Monitor" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "volume" && canSee("volume", perms) && <VolumeTracker user={user} perms={perms} />}
        {page === "volume" && !canSee("volume", perms) && <NoAccess role={user.role} feature="Volume Tracker" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "tco" && canSee("tco", perms) && <TCOAnalysis user={user} perms={perms} />}
        {page === "tco" && !canSee("tco", perms) && <NoAccess role={user.role} feature="TCO Analysis" canDo="Rate Calculator" onGoCalc={() => setPage("calc")} />}

        {page === "access" && <AccessRequests user={user} perms={perms} onApprovalAction={() => setAccessCountKey(k => k + 1)} />}
        {page === "admin" && perms.admin && <Admin user={user} />}
        {page === "docs" && <Documentation user={user} perms={perms} />}
      </main>

      {openRate && <RateDetail rate={openRate} onClose={() => setOpenRate(null)} perms={perms}
        onEdit={rate => { setOpenRate(null); setShowAddPrefill(rate); setShowAdd(true); }}
        onDuplicate={rate => { setOpenRate(null); setShowAddPrefill({ ...rate, id: undefined, status: "Draft", created_at: undefined, modified_at: undefined }); setShowAdd(true); }} />}
      {showAdd && <AddRateForm prefill={showAddPrefill} onClose={() => { setShowAdd(false); setShowAddPrefill(null); }} onSave={msg => { setShowAdd(false); setShowAddPrefill(null); setToast(msg); setRateRefreshKey(k => k + 1); }} />}
      {showImport && <ImportWizard onClose={() => setShowImport(false)} onDone={msg => { setShowImport(false); setToast(msg); setRateRefreshKey(k => k + 1); }} />}
      {showAI && <AIAssistant user={user} perms={perms} drawerMode onClose={() => setShowAI(false)} />}
      <Toast msg={toast} onClose={() => setToast("")} />

      {showWelcome && <WelcomeOverlay onDismiss={dismissWelcome} />}

      {/* TWEAKS PANEL — local/dev env + admin role only */}
      {showTweaks && <TweaksPanel title="Tweaks · Persona Simulator">
        <TweakSection title="Identity">
          <TweakRadio
            label="Active role"
            value={tweaks.persona}
            onChange={v => setTweak("persona", v)}
            options={[
              { value: "rate_calculator", label: "Calc only" },
              { value: "read", label: "Read" },
              { value: "edit", label: "Rate Focal (edit)" },
              { value: "fbp", label: "FBP" },
              { value: "procurement", label: "Procurement" },
              { value: "admin", label: "Admin" },
            ]}
          />
          <div className="tiny muted" style={{ marginTop: 6, lineHeight: 1.45 }}>
            <b>rate_calculator</b> · Calculator only · rates hidden<br/>
            <b>read</b> · browse rates + Health Dashboard<br/>
            <b>edit</b> · Rate Focal — create / import rates + Volume upload<br/>
            <b>fbp</b> · adds AI, Export, Rebate, TCO<br/>
            <b>procurement</b> · adds contract upload + Rebate settlement<br/>
            <b>admin</b> · full system + Admin console
          </div>
        </TweakSection>
        <TweakSection title="Preview">
          <TweakToggle label="Show audit trail badges" value={tweaks.showAuditTrail} onChange={v => setTweak("showAuditTrail", v)} />
        </TweakSection>
      </TweaksPanel>}
    </div>
  );
}


function NoAccess({ role, feature, canDo, onGoCalc }) {
  return (
    <div style={{ display: "grid", placeItems: "center", padding: "80px 20px" }}>
      <div className="card" style={{ padding: 32, maxWidth: 480, textAlign: "center" }}>
        <div style={{ width: 48, height: 48, borderRadius: 8, background: "var(--paper-2)", color: "var(--ink-mute)", display: "grid", placeItems: "center", margin: "0 auto 14px" }}>
          <Icon name="eyeOff" size={22} />
        </div>
        <div className="serif" style={{ fontSize: 20, fontWeight: 500, marginBottom: 8 }}>{feature} is not available for your role</div>
        <div className="muted" style={{ marginBottom: 20 }}>
          Your role <span className="mono bold" style={{ color: "var(--ink)" }}>{role}</span> does not include access to <b>{feature}</b>.
          You can use the <b>{canDo}</b> for cost estimation, or submit a new access request.
        </div>
        <div className="row gap-8" style={{ justifyContent: "center" }}>
          <button className="btn" onClick={onGoCalc}><Icon name="calc" size={14} /> Open Calculator</button>
          <button className="btn primary"><Icon name="key" size={14} /> Request Access</button>
        </div>
      </div>
    </div>
  );
}

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