const { useState: usePA, useEffect: useEffectPA } = React;

function NavItem({ item, active, onClick }) {
  return (
    <div
      className={"nav-item" + (active === item.id ? " active" : "")}
      onClick={() => onClick(item.id)}
    >
      <Icon name={item.icon} size={15} color={active === item.id ? "var(--ink)" : "var(--ink-3)"} />
      <span>{item.label}</span>
    </div>
  );
}

function PortalApp() {
  const [active, setActive] = usePA("dashboard");
  const [, setTick] = usePA(0);
  const forceRender = () => setTick((t) => t + 1);

  useEffectPA(() => {
    window.applyLang();
    window.onLangChange = () => forceRender();
    window.onAuthChange = () => forceRender();
    return () => {
      window.onLangChange = null;
      window.onAuthChange = null;
    };
  }, []);

  if (!window.API.hasToken()) {
    return <PortalLogin onAuthed={() => forceRender()} />;
  }

  const NAV = [
    { section: window.T("sectionMain"), items: [
      { id: "dashboard", label: window.T("navDashboard"), icon: "home" },
      { id: "offers", label: window.T("navOffers"), icon: "pipeline" },
      { id: "links", label: window.T("navLinks"), icon: "link" }
    ]},
    { section: window.T("sectionMoney"), items: [
      { id: "payouts", label: window.T("navPayouts"), icon: "leaf" },
      { id: "profile", label: window.T("navProfile"), icon: "settings" }
    ]}
  ];

  const labels = {};
  NAV.forEach((s) => s.items.forEach((i) => { labels[i.id] = i.label; }));

  const views = {
    dashboard: window.PortalDashboard,
    offers: window.PortalOffers,
    links: window.PortalLinks,
    payouts: window.PortalPayouts,
    profile: window.PortalProfile
  };
  const ActiveView = views[active] || views.dashboard;

  const user = window.API.user() || {};
  const initials = (user.fullName || "?").split(" ").map((w) => w[0]).join("").slice(0, 2).toUpperCase();

  const logout = async () => {
    try { await window.API.logout(); } catch (e) {}
    forceRender();
  };

  return (
    <div className="app">
      <aside className="sidebar">
        <div className="brand">
          <div className="brand-mark" />
          <div className="col" style={{ gap: 2 }}>
            <span className="brand-name">{window.T("brand")}</span>
            <span className="brand-tag">{window.T("portalTag")}</span>
          </div>
        </div>

        {NAV.map((sec) => (
          <div className="nav-section" key={sec.section}>
            <div className="nav-label">{sec.section}</div>
            {sec.items.map((item) => (
              <NavItem key={item.id} item={item} active={active} onClick={setActive} />
            ))}
          </div>
        ))}

        <div className="sidebar-foot">
          <div className="flex between items-center">
            <div className="user-chip grow">
              <div className="user-avatar">{initials}</div>
              <div className="col grow" style={{ gap: 1, minWidth: 0 }}>
                <span className="user-name" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{user.fullName || "—"}</span>
                <span className="user-role">{window.T("navProfile")}</span>
              </div>
            </div>
            <button className="icon-btn" title={window.T("signOut")} onClick={logout}>
              <Icon name="x" size={16} color="var(--ink-3)" />
            </button>
          </div>
        </div>
      </aside>

      <header className="topbar">
        <div className="crumbs">
          <span>{window.T("brand")}</span>
          <span className="sep">/</span>
          <span className="here">{labels[active] || window.T("navDashboard")}</span>
        </div>
        <div className="grow" />
        <button
          className="btn btn-ghost btn-sm"
          onClick={() => window.setLang(window.getLang() === "ar" ? "en" : "ar")}
        >
          {window.T("langToggle")}
        </button>
        <button className="icon-btn">
          <Icon name="bell" size={16} color="var(--ink-2)" />
        </button>
      </header>

      <main className="main">
        <ActiveView />
      </main>
    </div>
  );
}
window.PortalApp = PortalApp;
