// aerOS Superadmin — Login gate + Overview screen
const { useState: _saS, useMemo: _saM } = React;

function fmtTRY(n) { return '€' + Number(n || 0).toLocaleString('de-DE'); }  // planning figures in EUR
function fmtK(n) { return n >= 1000 ? (n / 1000).toFixed(n % 1000 === 0 ? 0 : 1) + 'B' : String(n); }

/* ----------------------------- Login ----------------------------- */
function SALogin({ t, ui, onAuth }) {
  const [email, setEmail] = _saS('');
  const [pass, setPass] = _saS('');
  const [loading, setLoading] = _saS(false);
  const [err, setErr] = _saS('');
  const [tfa, setTfa] = _saS(null); const [code, setCode] = _saS('');   // 2FA (TOTP)
  const submit = async (e) => {
    e && e.preventDefault();
    if (!email || !pass) return;
    setLoading(true); setErr('');
    try {
      const d = await window.SA_API.login(email, pass);
      if (d && d.two_factor) { setTfa(d); setLoading(false); return; }
      onAuth();
    } catch (ex) {
      setErr(ex.message === 'not_superadmin' ? (t.notSuperadmin || 'Bu hesap platform yöneticisi değil.')
        : (t.loginFailed || 'Giriş başarısız. Bilgileri kontrol edin.'));
      setLoading(false);
    }
  };
  const submitCode = async (e) => {
    e && e.preventDefault();
    if ((code || '').trim().length < 6) return;
    setLoading(true); setErr('');
    try { await window.SA_API.twoFactorVerify(tfa.challenge, code.trim()); onAuth(); }
    catch (ex) {
      setErr(ex.message === 'not_superadmin' ? (t.notSuperadmin || 'Bu hesap platform yöneticisi değil.') : 'Kod hatalı veya süresi doldu.');
      setLoading(false);
    }
  };
  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-2)', padding: 20, position: 'relative' }}>
      <div style={{ position: 'absolute', top: 18, right: 18 }}><LangThemeControls ui={ui} /></div>
      <div style={{ width: '100%', maxWidth: 380 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 26 }}>
          <div style={{ width: 52, height: 52, borderRadius: 14, background: 'var(--accent)', color: 'var(--on-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14, boxShadow: 'var(--shadow-md)' }}>{Icon.layers({ size: 26 })}</div>
          <h1 style={{ fontSize: 21, fontWeight: 700 }}>{t.appName} · {t.loginTitle}</h1>
          <p style={{ fontSize: 13.5, color: 'var(--fg-3)', marginTop: 4 }}>{t.loginSub}</p>
        </div>
        <Card pad={24}>
          {tfa ? (
            <form onSubmit={submitCode} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div style={{ fontSize: 13.5, color: 'var(--fg-2)', lineHeight: 1.45 }}>{tfa.two_factor === 'setup' ? 'Google Authenticator ile QR kodu tarayın, sonra 6 haneli kodu girin.' : 'Google Authenticator uygulamasındaki 6 haneli kodu girin.'}</div>
              {tfa.two_factor === 'setup' && tfa.qr_png && <div style={{ textAlign: 'center' }}><img src={tfa.qr_png} alt="QR" style={{ width: 168, height: 168, borderRadius: 12, border: '1px solid var(--border)' }} /></div>}
              <Field label="6 haneli kod"><Input value={code} onChange={setCode} icon={Icon.shield} /></Field>
              <Button variant="primary" size="lg" full type="submit" onClick={submitCode} disabled={loading}>
                {loading ? <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}><Spinner size={15} color="var(--on-accent)" />…</span> : 'Doğrula'}
              </Button>
              {err && <div style={{ fontSize: 12.5, color: 'var(--danger)', textAlign: 'center', fontWeight: 500 }}>{err}</div>}
            </form>
          ) : (
          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Field label={t.email}><Input value={email} onChange={setEmail} type="email" icon={Icon.user} /></Field>
            <Field label={t.password}><Input value={pass} onChange={setPass} type="password" icon={Icon.shield} /></Field>
            <Button variant="primary" size="lg" full type="submit" onClick={submit} icon={loading ? null : Icon.login} disabled={loading}>
              {loading ? <span style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}><Spinner size={15} color="var(--on-accent)" />{t.signingIn}</span> : t.signIn}
            </Button>
            {err && <div style={{ fontSize: 12.5, color: 'var(--danger)', textAlign: 'center', fontWeight: 500 }}>{err}</div>}
            <div style={{ fontSize: 11.5, color: 'var(--fg-3)', textAlign: 'center' }}>{t.loginHint}</div>
          </form>
          )}
        </Card>
      </div>
    </div>
  );
}

/* ----------------------------- Overview ----------------------------- */
function SAOverview({ t, orgs, loading }) {
  const [range, setRange] = _saS('12m');
  const D = window.SA_DATA;
  const stats = _saM(() => {
    const total = orgs.length;
    const active = orgs.filter(o => o.is_active).length;
    const orders = orgs.reduce((s, o) => s + o.monthly_orders, 0);
    const rev = orgs.reduce((s, o) => s + o.monthly_revenue, 0);
    const mrr = orgs.filter(o => o.is_active).reduce((s, o) => { const p = D.PLANS.find(p => p.tier === o.plan_tier); return s + (p ? p.price : 0); }, 0);
    return { total, active, suspended: total - active, orders, rev, mrr };
  }, [orgs]);

  const planDist = _saM(() => D.PLANS.map((p, i) => ({ label: p.name, value: orgs.filter(o => o.plan_tier === p.tier).length, color: ['#94a3b8', 'var(--brand)', '#0d9488', '#7c3aed'][i] })).filter(d => d.value > 0), [orgs]);
  const vertDist = _saM(() => [
    { label: t.hotel, value: orgs.filter(o => o.vertical === 'hotel').length, color: '#2563eb' },
    { label: t.restaurant, value: orgs.filter(o => o.vertical === 'restaurant').length, color: '#d97706' },
    { label: t.hospital, value: orgs.filter(o => o.vertical === 'hospital').length, color: '#0d9488' },
  ].filter(d => d.value > 0), [orgs]);

  if (loading) return <OverviewSkeleton />;

  // No mock history: series reflect real current values (flat) until the
  // platform tracks time-series metrics.
  const sRev = Array(12).fill((stats.mrr || 0) / 1000);
  const sOrgs = Array(12).fill(stats.total || 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <Grid cols={3} gap={16} min={220}>
        <StatCard label={t.totalOrgs} value={stats.total} icon={Icon.building} sub={`${stats.active} ${t.active.toLowerCase()}`} spark={sOrgs} />
        <StatCard label={t.mrr} value={fmtTRY(stats.mrr)} icon={Icon.creditcard} tone="brand" spark={sRev} />
        <StatCard label={t.totalRevenue} value={fmtTRY(stats.rev)} unit="/ay" icon={Icon.dollar} tone="ok" spark={sRev} />
      </Grid>

      <Grid cols={3} gap={16}>
        <div style={{ gridColumn: 'span 2', minWidth: 0 }}>
          <Card title={t.growthTitle} subtitle={t.growthSub} icon={Icon.trending}
            actions={<Segmented size="sm" value={range} onChange={setRange} options={[{ value: '12m', label: t.last12 }, { value: '30d', label: t.last30 }]} />}>
            {range === '12m'
              ? <LineChart data={sRev} labels={D.MONTHS} height={240} valueFmt={v => fmtTRY(v * 1000)} />
              : <BarChart data={Array(30).fill(stats.orders / 30 || 0)} labels={Array.from({ length: 30 }, (_, i) => i % 5 === 0 ? (i + 1) : '')} height={240} valueFmt={v => fmtK(v)} />}
            <div style={{ display: 'flex', gap: 24, marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
              <Legend color="var(--brand)" label={range === '12m' ? t.totalRevenue : t.totalOrders} value={range === '12m' ? fmtTRY(stats.rev) : fmtK(stats.orders)} />
              <Legend color="var(--ok)" label={t.totalOrgs} value={stats.total} />
              <Legend color="var(--info)" label={t.active} value={stats.active} />
            </div>
          </Card>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minWidth: 0 }}>
          <Card title={t.planDist} icon={Icon.layers}>
            <DonutChart data={planDist} size={150} thickness={22} centerLabel={t.totalOrgs} centerValue={stats.total} />
          </Card>
          <Card title={t.verticalDist} icon={Icon.grid}>
            <div style={{ paddingTop: 4 }}>
              <BarChart horizontal data={vertDist.map(v => ({ label: v.label, value: v.value, color: v.color }))} />
            </div>
          </Card>
        </div>
      </Grid>

      <Card title={t.recentOrgs} icon={Icon.building} noBody>
        <div>
          {[...orgs].sort((a, b) => (b.created_at || '').localeCompare(a.created_at || '')).slice(0, 8).map((o, i, arr) => (
            <div key={o.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 18px', borderBottom: i < arr.length - 1 ? '1px solid var(--border)' : 'none' }}>
              <Avatar name={o.name} size={34} square />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{o.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{o.slug}{o.city ? ' · ' + o.city : ''}</div>
              </div>
              <Badge tone="neutral" size="sm">{t[o.vertical]}</Badge>
              <Badge tone={o.is_active ? 'ok' : 'warn'} size="sm" dot>{o.is_active ? t.active : t.suspended}</Badge>
              <span style={{ fontSize: 12, color: 'var(--fg-3)', minWidth: 78, textAlign: 'right' }} className="tnum">{o.created_at}</span>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function Legend({ color, label, value }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--fg-3)' }}><span style={{ width: 9, height: 9, borderRadius: 3, background: color }} />{label}</span>
      <span className="tnum" style={{ fontSize: 17, fontWeight: 700, color: 'var(--fg-1)' }}>{value}</span>
    </div>
  );
}

function OverviewSkeleton() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <Grid cols={3} gap={16}>{[0, 1, 2].map(i => <div key={i} style={{ background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 18 }}><Skeleton w={90} h={11} /><Skeleton w={130} h={28} style={{ marginTop: 16 }} /><Skeleton w={70} h={12} style={{ marginTop: 12 }} /></div>)}</Grid>
      <Grid cols={3} gap={16}>
        <div style={{ gridColumn: 'span 2', background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 18, height: 320 }}><Skeleton w={160} h={16} /><Skeleton h={240} style={{ marginTop: 20 }} /></div>
        <div style={{ background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 18, height: 320 }}><Skeleton w={120} h={16} /><Skeleton w={150} h={150} r={75} style={{ marginTop: 30, marginLeft: 'auto', marginRight: 'auto' }} /></div>
      </Grid>
    </div>
  );
}

Object.assign(window, { SALogin, SAOverview, fmtTRY, fmtK });
