// page-billing.jsx — Plans + Stripe Embedded

const { useState: usB } = React;

function PageBilling() {
  const [tab, setTab] = usB('plan');
  return (
    <div className="fade-up">
      <div className="page-head">
        <div>
          <h1 className="page-title">Plano & cobrança</h1>
          <p className="page-sub">Gerencie seu plano, pagamentos e créditos consumidos.</p>
        </div>
      </div>

      <div className="tabs">
        {[['plan','Plano atual'],['change','Trocar plano'],['payment','Pagamento'],['invoices','Faturas']].map(([id,l]) => (
          <button key={id} className={'tab ' + (tab===id?'on':'')} onClick={() => setTab(id)}>{l}</button>
        ))}
      </div>

      {tab === 'plan' && <CurrentPlan />}
      {tab === 'change' && <ChangePlan />}
      {tab === 'payment' && <PaymentSection />}
      {tab === 'invoices' && <Invoices />}
    </div>
  );
}

function CurrentPlan() {
  const used = TENANT.credits_used, total = TENANT.credits_total;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 'var(--gap)' }}>
      <div className="card" style={{ position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: 0, right: 0, width: 200, height: 200,
          background: 'radial-gradient(circle at top right, var(--accent-soft), transparent 70%)' }} />
        <div className="row gap-sm" style={{ marginBottom: 8, position: 'relative' }}>
          <span className="tag tag-accent">Plano atual</span>
          <span className="tag tag-ok tag-dot">ativo</span>
        </div>
        <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: '-0.5px' }}>Growth</div>
        <div className="row" style={{ alignItems: 'baseline', gap: 4, marginTop: 2 }}>
          <span style={{ fontSize: 22, fontWeight: 700 }}>R$ 149</span>
          <span className="muted">/mês · próxima cobrança em 11 dias</span>
        </div>

        <div style={{ marginTop: 22, padding: 14, background: 'var(--bg-base)', borderRadius: 'var(--r-md)', border: '1px solid var(--border)' }}>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
            <span style={{ fontSize: 12, fontWeight: 700 }}>Créditos do mês</span>
            <span className="mono"><b>{used.toLocaleString('pt-BR')}</b> / {total.toLocaleString('pt-BR')}</span>
          </div>
          <div className="progress"><div className="progress-bar" style={{ width: (used/total*100)+'%' }} /></div>
          <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>Restam {(total-used).toLocaleString('pt-BR')} execuções até o ciclo renovar.</div>
        </div>

        <div className="row gap-sm" style={{ marginTop: 16 }}>
          <button className="btn btn-primary"><iconify-icon icon="lucide:arrow-up-circle" />Fazer upgrade</button>
          <button className="btn"><iconify-icon icon="lucide:zap" />Comprar créditos extras</button>
          <button className="btn btn-ghost" style={{ marginLeft: 'auto', color: 'var(--err)' }}>Cancelar plano</button>
        </div>
      </div>

      <div className="card">
        <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 14 }}>Consumo dos últimos 30 dias</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 120 }}>
          {Array.from({length: 30}).map((_, i) => (
            <div key={i} style={{
              flex: 1,
              height: (40 + Math.sin(i*0.4)*20 + Math.random()*30) + '%',
              background: i > 22 ? 'var(--accent)' : 'var(--bg-elevated)',
              borderRadius: '2px 2px 0 0',
            }} />
          ))}
        </div>
        <div className="row" style={{ justifyContent: 'space-between', marginTop: 16, fontSize: 11 }}>
          <div><div className="muted">Pico</div><div className="strong mono">312 / dia</div></div>
          <div><div className="muted">Média</div><div className="strong mono">114 / dia</div></div>
          <div><div className="muted">Projeção</div><div className="strong mono">4.8k / mês</div></div>
        </div>
      </div>
    </div>
  );
}

function ChangePlan() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'var(--gap)' }}>
      {PLANS.map(p => (
        <div key={p.id} className="card" style={{
          display: 'flex', flexDirection: 'column',
          border: p.popular ? '1px solid var(--accent)' : null,
          position: 'relative',
        }}>
          {p.popular && (
            <span className="tag tag-accent" style={{ position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)' }}>
              Mais escolhido
            </span>
          )}
          <div style={{ fontSize: 15, fontWeight: 700 }}>{p.name}</div>
          <div className="row" style={{ alignItems: 'baseline', gap: 4, marginTop: 8, marginBottom: 16 }}>
            <span style={{ fontSize: 28, fontWeight: 800 }}>R$ {p.price}</span>
            <span className="muted">/mês</span>
          </div>
          <div style={{ display: 'grid', gap: 8, marginBottom: 18, flex: 1 }}>
            {p.features.map((f, i) => (
              <div key={i} className="row gap-sm" style={{ fontSize: 13 }}>
                <iconify-icon icon="lucide:check" style={{ color: 'var(--accent)', fontSize: 14 }} />
                <span>{f}</span>
              </div>
            ))}
          </div>
          {p.current ? (
            <button className="btn" disabled style={{ justifyContent: 'center', opacity: 0.5 }}>Plano atual</button>
          ) : (
            <button className={'btn ' + (p.popular ? 'btn-primary' : '')} style={{ justifyContent: 'center' }}>
              {p.price > 149 ? 'Fazer upgrade' : 'Mudar para ' + p.name}
            </button>
          )}
        </div>
      ))}
    </div>
  );
}

function PaymentSection() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 'var(--gap)' }}>
      <div className="card">
        <div className="row gap-sm" style={{ marginBottom: 14 }}>
          <iconify-icon icon="lucide:credit-card" style={{ color: 'var(--accent)' }} />
          <span style={{ fontSize: 14, fontWeight: 700 }}>Pagamento</span>
          <span className="tag" style={{ marginLeft: 'auto' }}>powered by Stripe</span>
        </div>

        {/* Mock Stripe Embedded Element */}
        <div style={{
          background: 'var(--bg-base)', border: '1px solid var(--border)',
          borderRadius: 'var(--r-md)', padding: 14, marginBottom: 12,
        }}>
          <div className="muted" style={{ fontSize: 11, marginBottom: 6 }}>Número do cartão</div>
          <div className="row gap-sm" style={{ marginBottom: 14 }}>
            <span className="mono" style={{ fontSize: 15, letterSpacing: 2 }}>4242 4242 4242 4242</span>
            <iconify-icon icon="logos:visa" style={{ marginLeft: 'auto', fontSize: 28 }} />
          </div>
          <div className="row gap-md">
            <div style={{ flex: 1 }}>
              <div className="muted" style={{ fontSize: 11, marginBottom: 6 }}>Validade</div>
              <span className="mono">12/29</span>
            </div>
            <div style={{ flex: 1 }}>
              <div className="muted" style={{ fontSize: 11, marginBottom: 6 }}>CVC</div>
              <span className="mono">•••</span>
            </div>
            <div style={{ flex: 1 }}>
              <div className="muted" style={{ fontSize: 11, marginBottom: 6 }}>CEP</div>
              <span className="mono">04567-000</span>
            </div>
          </div>
        </div>
        <button className="btn"><iconify-icon icon="lucide:edit-3" />Atualizar método</button>
      </div>

      <div className="card">
        <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 12 }}>Endereço de cobrança</div>
        <div style={{ fontSize: 13, lineHeight: 1.7 }}>
          <div className="strong">Casa Bonita Decor LTDA</div>
          <div className="muted">CNPJ 12.345.678/0001-90</div>
          <div className="muted">Av. Paulista, 1.000 — Sala 1204</div>
          <div className="muted">São Paulo, SP — 01310-100</div>
        </div>
        <button className="btn" style={{ marginTop: 14 }}>Editar</button>
      </div>
    </div>
  );
}

function Invoices() {
  const inv = [
    { d: '01 abr 2026', amount: 149, status: 'paid' },
    { d: '01 mar 2026', amount: 149, status: 'paid' },
    { d: '01 fev 2026', amount: 149, status: 'paid' },
    { d: '01 jan 2026', amount: 49, status: 'paid' },
    { d: '01 dez 2025', amount: 49, status: 'paid' },
  ];
  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <table className="tbl">
        <thead><tr>
          <th>Data</th><th>Plano</th><th>Valor</th><th>Status</th><th></th>
        </tr></thead>
        <tbody>
          {inv.map((i, idx) => (
            <tr key={idx}>
              <td className="strong">{i.d}</td>
              <td>{i.amount === 49 ? 'Starter' : 'Growth'} (mensal)</td>
              <td className="strong mono">R$ {i.amount},00</td>
              <td><span className="tag tag-ok tag-dot">paga</span></td>
              <td style={{ textAlign: 'right' }}>
                <button className="btn btn-sm btn-ghost"><iconify-icon icon="lucide:download" />PDF</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { PageBilling });
