// aerOS Superadmin — app root: auth gate, routing, impersonation banner
const { useState: _aS, useEffect: _aE } = React;

// Real platform notifications derived from org state (suspended / over-limit).
// No mock feed: empty when nothing needs attention.
function SaNotifications({ orgs, lang }) {
  const [open, setOpen] = _aS(false);
  const [reqs, setReqs] = _aS([]);
  const loadReqs = async () => { try { const r = await window.SA_API.listUpgradeRequests(); setReqs((r || []).filter(x => x.status === 'pending')); } catch (e) {} };
  _aE(() => { loadReqs(); const id = setInterval(loadReqs, 30000); return () => clearInterval(id); }, []);
  const resolve = async (id, action) => { try { await window.SA_API.resolveUpgrade(id, action); await loadReqs(); } catch (e) {} };
  const notifs = [];
  (orgs || []).forEach(o => {
    if (o.is_active === false) notifs.push({ id: 'su' + o.id, tone: 'danger', text: `${o.name} askıya alındı` });
    if (o.rooms_max > 0 && o.rooms_used >= o.rooms_max) notifs.push({ id: 'rm' + o.id, tone: 'warn', text: `${o.name}: oda limiti doldu (${o.rooms_used}/${o.rooms_max})` });
    if (o.products_max > 0 && o.products_used >= o.products_max) notifs.push({ id: 'pr' + o.id, tone: 'warn', text: `${o.name}: ürün limiti doldu` });
  });
  const total = notifs.length + reqs.length;
  return (
    <div style={{ position: 'relative' }}>
      <IconButton icon={Icon.bell} title={(lang && lang.notifications) || 'Bildirim'} badge={total || undefined} onClick={() => setOpen(o => !o)} />
      {open && (<>
        <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
        <div style={{ position: 'absolute', right: 0, top: 44, width: 360, background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', boxShadow: '0 12px 32px rgba(0,0,0,0.16)', zIndex: 41, overflow: 'hidden', maxHeight: 460, overflowY: 'auto' }}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', fontSize: 13, fontWeight: 700 }}>{(lang && lang.notifications) || 'Bildirimler'}</div>
          {reqs.map(r => (
            <div key={'rq' + r.id} style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', background: 'var(--brand-soft)' }}>
              <div style={{ fontSize: 12.5, color: 'var(--fg-1)', fontWeight: 600 }}>{Icon.trending ? '' : ''}Plan yükseltme talebi</div>
              <div style={{ fontSize: 12.5, color: 'var(--fg-2)', marginTop: 2 }}><b>{r.org_name}</b> → <b>{r.plan_name}</b>{r.note ? ' · ' + r.note : ''}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                <Button size="sm" variant="primary" brand onClick={() => resolve(r.id, 'approve')}>Onayla</Button>
                <Button size="sm" variant="ghost" onClick={() => resolve(r.id, 'reject')}>Reddet</Button>
              </div>
            </div>
          ))}
          {total === 0
            ? <div style={{ padding: '28px 16px', textAlign: 'center', color: 'var(--fg-3)', fontSize: 13, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>{Icon.bell({ size: 26 })}{(lang && lang.noNotifications) || 'Bildirim yok'}</div>
            : notifs.map(n => (
              <div key={n.id} style={{ display: 'flex', gap: 10, padding: '11px 16px', borderBottom: '1px solid var(--border)', alignItems: 'flex-start' }}>
                <span style={{ width: 7, height: 7, borderRadius: 4, marginTop: 5, flexShrink: 0, background: n.tone === 'danger' ? 'var(--danger)' : 'var(--warn, #d97706)' }} />
                <div style={{ fontSize: 12.5, color: 'var(--fg-1)', lineHeight: 1.4 }}>{n.text}</div>
              </div>
            ))}
        </div>
      </>)}
    </div>
  );
}

function SuperadminApp() {
  const ui = useUI('aeros-sa-ui');
  const lang = ui.lang === 'en' ? window.SA_DATA.EN : window.SA_DATA.TR;
  const [authed, setAuthed] = _aS(!!window.aerosApi.getToken());
  const [route, setRoute] = _aS('overview');
  const [orgs, setOrgs] = _aS([]);
  const [loading, setLoading] = _aS(true);
  const [createOpen, setCreateOpen] = _aS(false);
  const [impersonating, setImpersonating] = _aS(null);

  const loadAll = async () => {
    setLoading(true);
    try {
      const [rows, plans] = await Promise.all([
        window.SA_API.listOrgs(),
        window.SA_API.listPlans(),
      ]);
      if (Array.isArray(plans) && plans.length) window.SA_DATA.PLANS = plans;
      try { const m = await window.SA_API.metrics(); if (m && m.orders_30) window.SA_DATA.ORDERS_30 = m.orders_30; } catch (e) {}
      setOrgs(rows || []);
    } catch (e) {
      setOrgs([]);
      // Expired/invalid session -> show login instead of a blank panel.
      if (e && (e.status === 401 || e.status === 403)) { try { window.aerosApi.setToken(null); } catch (x) {} setAuthed(false); }
    } finally { setLoading(false); }
  };

  _aE(() => { if (authed) loadAll(); }, [authed]);

  if (!authed) return <SALogin t={lang} ui={ui} onAuth={() => setAuthed(true)} />;

  const nav = [
    { section: lang.nav_platform, items: [
      { id: 'overview', label: lang.overview, icon: Icon.grid },
      { id: 'orgs', label: lang.orgs, icon: Icon.building, badge: orgs.length },
    ] },
    { section: lang.nav_management, items: [
      { id: 'billing', label: lang.billing, icon: Icon.creditcard },
      { id: 'settings', label: lang.settings || 'Ayarlar', icon: Icon.settings || Icon.gear || Icon.creditcard },
    ] },
  ];

  const titles = { overview: lang.overview, orgs: lang.orgsTitle, billing: lang.billingTitle, settings: lang.settings || 'Ayarlar' };
  const subs = { overview: `${lang.today} · ${new Date().toLocaleDateString(ui.lang === 'en' ? 'en-GB' : 'tr-TR', { day: 'numeric', month: 'long', year: 'numeric' })}`, orgs: lang.orgsSub, billing: lang.billingSub, settings: 'Yapay zeka ve platform ayarları' };

  const onImpersonate = async (org) => {
    try {
      const res = await window.SA_API.impersonate(org.id);
      // Open the tenant's panel on ITS subdomain (token handoff via #t=), in a
      // new tab so the superadmin session here stays intact. No token overwrite.
      const slug = res.org_slug || org.slug;
      const host = location.hostname, port = location.port ? ':' + location.port : '';
      window.open(location.protocol + '//' + slug + '.' + host + port + '/admin.html#t=' + encodeURIComponent(res.token), '_blank');
    } catch (e) { /* ignore */ }
  };

  const banner = impersonating ? (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 20px', background: 'var(--warn)', color: '#fff' }}>
      {Icon.shield({ size: 17 })}
      <span style={{ fontSize: 13, fontWeight: 500, flex: 1 }}>
        <b>{lang.imperBanner}</b> <b>{impersonating.name}</b> {lang.imperAs}.
      </span>
      <button onClick={() => setImpersonating(null)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 'var(--r-sm)', border: '1px solid rgba(255,255,255,0.5)', background: 'rgba(255,255,255,0.15)', color: '#fff', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
        {Icon.arrowLeft({ size: 14 })}{lang.imperReturn}
      </button>
    </div>
  ) : null;

  const topRight = (
    <>
      <SaNotifications orgs={orgs} lang={lang} />
      <LangThemeControls ui={ui} />
      <div style={{ width: 1, height: 26, background: 'var(--border)', margin: '0 2px' }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
        <Avatar name="Süper Admin" size={32} />
        <div style={{ lineHeight: 1.2 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Süper Admin</div>
          <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{lang.role}</div>
        </div>
      </div>
    </>
  );

  return (
    <AppShell
      brand={{ name: lang.appName, sub: lang.appSub, color: 'var(--accent)', onColor: 'var(--on-accent)', logo: Icon.layers({ size: 20 }) }}
      nav={nav} active={route} onNav={setRoute}
      title={titles[route]} subtitle={subs[route]} topRight={topRight} banner={banner}
      footer={<button onClick={() => { window.SA_API.logout(); setAuthed(false); }} style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: '8px 10px', borderRadius: 'var(--r-sm)', border: 'none', background: 'transparent', color: 'var(--fg-2)', fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit' }}>{Icon.logout({ size: 17 })}{lang.logout}</button>}
    >
      {route === 'overview' && <SAOverview t={lang} orgs={orgs} loading={loading} />}
      {route === 'orgs' && <SAOrgs t={lang} orgs={orgs} setOrgs={setOrgs} onImpersonate={onImpersonate} onCreate={() => setCreateOpen(true)} />}
      {route === 'billing' && <SABilling t={lang} orgs={orgs} />}
      {route === 'settings' && <SaSettings t={lang} />}

      <SACreateOrg t={lang} open={createOpen} onClose={() => setCreateOpen(false)} onCreated={async (f) => {
        await window.SA_API.createOrg(f);   // throws on failure (caught by the wizard)
        await loadAll();
        setRoute('orgs');
      }} />
    </AppShell>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ToastProvider><SuperadminApp /></ToastProvider>);
