/* Billing & usage — wired to live /api/billing.
   Returns { plan, plan_name, status, max_sites, max_screens,
   current_period_end, cancel_at_period_end, ... }. Stripe-backed when
   STRIPE_SECRET_KEY is set; otherwise returns the org's static plan. */

function BL_planLabel(plan) {
  if (!plan) return 'No plan';
  return plan.charAt(0).toUpperCase() + plan.slice(1);
}

function BillingScreen() {
  const [billing, setBilling] = useState(null);
  const [meters, setMeters] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let cancelled = false;
    Promise.all([
      apiFetch('/api/billing').catch(() => null),
      Promise.all([
        apiFetch('/api/zones').catch(() => null),
        apiFetch('/api/screens').catch(() => null),
        apiFetch('/api/species?limit=1').catch(() => null),
        apiFetch('/api/auth/users').catch(() => null),
      ]),
    ]).then(([billingRes, [zonesRes, screensRes, speciesRes, usersRes]]) => {
      if (cancelled) return;
      setBilling(billingRes);
      setMeters({
        zones: zonesRes ? (zonesRes.zones || []).length : null,
        screens: screensRes ? (screensRes.screens || []).length : null,
        species: speciesRes ? speciesRes.total : null,
        users: usersRes ? (usersRes.users || []).length : null,
      });
      setLoading(false);
    }).catch((err) => {
      if (cancelled) return;
      setError(err.message);
      setLoading(false);
    });
    return () => { cancelled = true; };
  }, []);

  return (
    <div className="aq-content">
      <div className="aq-content-inner" style={{ maxWidth: 1000 }}>
        <header style={{ marginBottom: 24 }}>
          <div className="aq-eyebrow">
            <span>Slate</span>
            <span className="aq-sep">·</span>
            <span>Billing & usage</span>
          </div>
          <h1 style={{
            fontFamily: 'var(--aq-ff-display)', fontSize: 26, fontWeight: 500,
            letterSpacing: '-0.012em', color: 'var(--aq-text)', margin: '4px 0 4px',
          }}>Billing & usage</h1>
          <p style={{ fontSize: 13, color: 'var(--aq-text-faint)', margin: 0 }}>
            Plan, meters, and invoices.
          </p>
        </header>

        {loading && (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--aq-text-faint)' }}>
            Loading plan…
          </div>
        )}
        {error && (
          <div style={{
            padding: '10px 14px',
            background: 'color-mix(in srgb, var(--aq-danger) 12%, transparent)',
            border: '1px solid color-mix(in srgb, var(--aq-danger) 30%, transparent)',
            borderRadius: 6, color: 'var(--aq-danger)', fontSize: 12,
          }}>{error}</div>
        )}

        {!loading && !error && billing && (
          <>
            <section className="x-card" style={{ padding: 22, marginBottom: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
                <div>
                  <div className="x-eyebrow">Current plan</div>
                  <div style={{
                    fontFamily: 'var(--aq-ff-display)', fontSize: 22, fontWeight: 500,
                    color: 'var(--aq-text)', letterSpacing: '-0.018em', marginTop: 4,
                  }}>{billing.plan_name || BL_planLabel(billing.plan)}</div>
                  <div style={{ fontSize: 12, color: 'var(--aq-text-faint)', marginTop: 4 }}>
                    {billing.max_sites != null ? `${billing.max_sites} sites` : ''}
                    {billing.max_sites != null && billing.max_screens != null ? ' · ' : ''}
                    {billing.max_screens != null ? `up to ${billing.max_screens} screens` : ''}
                    {billing.current_period_end && (
                      <> · renews {new Date(billing.current_period_end).toLocaleDateString()}</>
                    )}
                    {billing.cancel_at_period_end && (
                      <span style={{ color: 'var(--aq-warn)' }}> · cancelling at period end</span>
                    )}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="x-btn ghost">View invoices</button>
                  <button className="x-btn">{billing.status === 'active' ? 'Manage plan' : 'Upgrade plan'}</button>
                </div>
              </div>
              {billing.status && billing.status !== 'active' && (
                <div style={{
                  marginTop: 14, padding: '8px 12px',
                  background: 'color-mix(in srgb, var(--aq-warn) 12%, transparent)',
                  border: '1px solid color-mix(in srgb, var(--aq-warn) 30%, transparent)',
                  borderRadius: 6, color: 'var(--aq-warn)', fontSize: 12,
                }}>Status: {billing.status}</div>
              )}
            </section>

            {meters && (
              <div className="x-meters" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16 }}>
                <div className="x-meter">
                  <div className="x-meter-label">Sites</div>
                  <div className="x-meter-value">
                    1{billing.max_sites && <small>/{billing.max_sites}</small>}
                  </div>
                  <div className="x-meter-bar">
                    <div className="x-meter-fill" style={{ width: billing.max_sites ? `${Math.round(100 / billing.max_sites)}%` : '20%' }} />
                  </div>
                </div>
                <div className="x-meter">
                  <div className="x-meter-label">Screens</div>
                  <div className="x-meter-value">
                    {meters.screens ?? '—'}{billing.max_screens && <small>/{billing.max_screens}</small>}
                  </div>
                  <div className="x-meter-bar">
                    <div className="x-meter-fill" style={{
                      width: billing.max_screens && meters.screens != null
                        ? `${Math.round((meters.screens / billing.max_screens) * 100)}%`
                        : '0%',
                    }} />
                  </div>
                </div>
                <div className="x-meter">
                  <div className="x-meter-label">Species</div>
                  <div className="x-meter-value">{meters.species ?? '—'}</div>
                  <div className="x-meter-bar"><div className="x-meter-fill" style={{ width: '8%' }} /></div>
                </div>
                <div className="x-meter">
                  <div className="x-meter-label">Users</div>
                  <div className="x-meter-value">{meters.users ?? '—'}</div>
                  <div className="x-meter-bar"><div className="x-meter-fill" style={{ width: '15%' }} /></div>
                </div>
              </div>
            )}

            <section className="x-card">
              <div className="x-card-head">
                <div>
                  <h2>Recent invoices</h2>
                  <p>{billing.status === 'active' ? 'Latest billing periods' : 'No active subscription'}</p>
                </div>
                <button className="x-btn ghost sm">Download all</button>
              </div>
              <div className="x-invoice-table">
                <div className="x-invoice-row is-head">
                  <div>Number</div>
                  <div>Period</div>
                  <div>Plan</div>
                  <div>Status</div>
                  <div>Amount</div>
                </div>
                <div className="x-invoice-row">
                  <div className="x-invoice-num">—</div>
                  <div>Stripe invoice list isn't wired client-side yet</div>
                  <div>{BL_planLabel(billing.plan)}</div>
                  <div><span className="aq-pill is-soft is-neutral">—</span></div>
                  <div className="x-invoice-amount">—</div>
                </div>
              </div>
            </section>
          </>
        )}
      </div>
    </div>
  );
}

window.BillingScreen = BillingScreen;
