// aerOS Superadmin — Plans & Billing
const { useState: _bS } = React;

function SABilling({ t, orgs }) {
  const toast = useToast();
  const D = window.SA_DATA;
  const [plans, setPlans] = _bS(D.PLANS);
  const [edit, setEdit] = _bS(null);

  const totalSubs = orgs.filter(o => o.is_active).length;
  const mrr = orgs.filter(o => o.is_active).reduce((s, o) => { const p = plans.find(p => p.tier === o.plan_tier); return s + (p ? p.price : 0); }, 0);

  const savePlan = async () => {
    try {
      await window.SA_API.updatePlan(edit);
      const fresh = await window.SA_API.listPlans();  // re-pull persisted plans
      if (Array.isArray(fresh) && fresh.length) { setPlans(fresh); window.SA_DATA.PLANS = fresh; }
      else setPlans(ps => ps.map(p => p.tier === edit.tier ? edit : p));
      toast.ok(`${edit.name}`, t.planChanged);
      setEdit(null);
    } catch (e) { toast.error(e.message || 'Hata'); }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <Grid cols={3} gap={16} min={220}>
        <StatCard label={t.activeSubs} value={totalSubs} icon={Icon.checkCircle} tone="ok" sub={`/ ${orgs.length} ${t.orgs.toLowerCase()}`} />
        <StatCard label={t.mrr} value={fmtTRY(mrr)} icon={Icon.creditcard} tone="brand" delta={8} />
        <StatCard label={t.planDefs} value={plans.length} icon={Icon.layers} sub={t.tier.toLowerCase()} />
      </Grid>

      <div>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--fg-2)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 12 }}>{t.planDefs}</div>
        <Grid cols={4} gap={16} min={230}>
          {plans.map(p => {
            const subCount = orgs.filter(o => o.plan_tier === p.tier).length;
            return (
              <div key={p.tier} style={{ position: 'relative', background: 'var(--bg-0)', border: p.popular ? '1.5px solid var(--brand)' : '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 20, boxShadow: 'var(--shadow-sm)', display: 'flex', flexDirection: 'column', gap: 14 }}>
                {p.popular && <div style={{ position: 'absolute', top: -10, left: 20, background: 'var(--brand)', color: 'var(--on-brand)', fontSize: 10.5, fontWeight: 700, padding: '3px 10px', borderRadius: 999, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{t.mostPopular}</div>}
                <div>
                  <div style={{ fontSize: 16, fontWeight: 700 }}>{p.name}</div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 6 }}>
                    {p.price ? <><span className="tnum" style={{ fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em' }}>{fmtTRY(p.price)}</span><span style={{ fontSize: 12.5, color: 'var(--fg-3)' }}>{t.perMonth}</span></>
                      : <span style={{ fontSize: 20, fontWeight: 700 }}>Özel fiyat</span>}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <LimitChip label={t.maxRooms} value={p.maxRooms >= 9999 ? '∞' : p.maxRooms} icon={Icon.bed} />
                  <LimitChip label={t.maxProducts} value={p.maxProducts >= 9999 ? '∞' : p.maxProducts} icon={Icon.utensils} />
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 7, flex: 1 }}>
                  {p.features.map((ft, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--fg-2)' }}>
                      <span style={{ color: 'var(--ok)', display: 'flex' }}>{Icon.check({ size: 14 })}</span>{ft}
                    </div>
                  ))}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 12, borderTop: '1px solid var(--border)' }}>
                  <Badge tone="neutral" size="sm" icon={Icon.building}>{subCount} {t.subscribers.toLowerCase()}</Badge>
                  <Button size="sm" variant="ghost" icon={Icon.edit} onClick={() => setEdit({ ...p })}>{t.save && t.editPlan}</Button>
                </div>
              </div>
            );
          })}
        </Grid>
      </div>

      <Card title={t.subscription} subtitle={`${totalSubs} ${t.activeSubs.toLowerCase()}`} icon={Icon.creditcard} noBody>
        <DataTable
          columns={[
            { key: 'name', label: t.name, sortable: true, render: o => <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Avatar name={o.name} size={28} square /><span style={{ fontWeight: 600 }}>{o.name}</span></div> },
            { key: 'plan_tier', label: t.plan, sortable: true, render: o => planBadge(o.plan_tier) },
            { key: 'price', label: t.price, align: 'right', sortable: true, sortValue: o => { const p = plans.find(p => p.tier === o.plan_tier); return p ? p.price : 0; }, render: o => { const p = plans.find(p => p.tier === o.plan_tier); return <span className="tnum">{p && p.price ? fmtTRY(p.price) + '/ay' : 'Özel'}</span>; } },
            { key: 'is_active', label: t.status, sortable: true, sortValue: o => o.is_active ? 1 : 0, render: o => <Badge tone={o.is_active ? 'ok' : 'warn'} dot size="sm">{o.is_active ? t.active : t.suspended}</Badge> },
            { key: 'created_at', label: t.created, align: 'right', sortable: true, render: o => <span className="tnum" style={{ color: 'var(--fg-2)' }}>{o.created_at}</span> },
          ]}
          rows={orgs} searchKeys={['name', 'slug']} searchPlaceholder={t.searchOrg} pageSize={6}
          filters={[{ key: 'plan_tier', label: t.plan, options: [{ value: '', label: t.all + ' · ' + t.plan }, ...plans.map(p => ({ value: p.tier, label: p.name }))] }]}
        />
      </Card>

      <Modal open={!!edit} onClose={() => setEdit(null)} title={t.editPlan} subtitle={edit?.name} icon={Icon.layers} width={460}
        footer={<><Button variant="ghost" onClick={() => setEdit(null)}>{t.cancel}</Button><Button variant="primary" icon={Icon.save} onClick={savePlan}>{t.save}</Button></>}>
        {edit && (
          <Grid cols={2} gap={16}>
            <Field label={t.planName} span={2}><Input value={edit.name} onChange={v => setEdit(e => ({ ...e, name: v }))} /></Field>
            <Field label={t.maxRooms}><Input type="number" align="right" value={edit.maxRooms} onChange={v => setEdit(e => ({ ...e, maxRooms: +v }))} suffix={t.rooms.toLowerCase()} /></Field>
            <Field label={t.maxProducts}><Input type="number" align="right" value={edit.maxProducts} onChange={v => setEdit(e => ({ ...e, maxProducts: +v }))} suffix={t.products.toLowerCase()} /></Field>
            <Field label={`${t.price} (EUR)`} span={2}><Input type="number" align="right" value={edit.price} onChange={v => setEdit(e => ({ ...e, price: +v }))} prefix="€" suffix={t.perMonth} /></Field>
          </Grid>
        )}
      </Modal>
    </div>
  );
}

function LimitChip({ label, value, icon }) {
  return (
    <div style={{ flex: 1, background: 'var(--bg-2)', borderRadius: 'var(--r-sm)', padding: '8px 10px', display: 'flex', flexDirection: 'column', gap: 2 }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: 'var(--fg-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.03em' }}>{icon({ size: 12 })}{label}</span>
      <span className="tnum" style={{ fontSize: 16, fontWeight: 700 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { SABilling });
