/* global React, BezaLogo, Icon, Pill, fmt,
   GESTAO_PERIOD, REVENUE_HISTORY, CONTRACTS, COST_STRUCTURE,
   TEAM_ALLOCATION, CLIENT_HEALTH, PROPOSALS, ALERTS, GOALS,
   STAGE_META, PAYMENT_STATUS_META, BURNOUT_META, TREND_META, RISK_META,
   LineChart, TEAM */
const { useState: useStateGS, useMemo: useMemoGS } = React;

/* ============================================================
   HEADER · marca + logout
   ============================================================ */
function GestaoHeader({ onLogout }) {
  return (
    <div style={{
      padding: 'var(--space-6)',
      background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
      border: '1px solid var(--border-strong)',
      borderRadius: 'var(--r-card-lg)',
      position: 'relative', overflow: 'hidden',
      marginBottom: 'var(--space-5)',
    }}>
      <div aria-hidden="true" style={{
        position: 'absolute', top: '-30%', right: '-10%',
        width: 500, height: 500, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(154,155,229,0.18), transparent 60%)',
        filter: 'blur(40px)', pointerEvents: 'none',
      }} />

      <div style={{ position: 'relative', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap' }}>
        <div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <span>🔒</span> Acesso restrito · gestão · {GESTAO_PERIOD.current}
          </div>
          <h2 className="t-h1" style={{ margin: '0 0 8px', color: 'var(--text)' }}>
            <span className="t-light">A Beza vista de </span>
            <span className="punch">cima</span>
            <span className="t-light">.</span>
          </h2>
          <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)', maxWidth: 560, lineHeight: 1.6 }}>
            Tudo que o time não precisa ver: receita, custos, margens, saúde de cliente, propostas e calendário gerencial.
          </p>
        </div>
        <button onClick={onLogout} style={{
          appearance: 'none', border: '1px solid var(--border-strong)',
          background: 'var(--surface)', color: 'var(--text-muted)',
          padding: '8px 14px', fontSize: 12, fontFamily: 'inherit',
          borderRadius: 'var(--r-btn)', cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}>
          ⎋ Sair
        </button>
      </div>
    </div>
  );
}

/* ============================================================
   NAV · chips de seção
   ============================================================ */
function GestaoNav({ section, setSection }) {
  const items = [
    { id: 'overview',   label: 'Visão geral' },
    { id: 'pulse',      label: '☀ Pulso do time' },
    { id: 'alertas',    label: '✨ Alertas' },
    { id: 'inbox',      label: 'Inbox' },
    { id: 'allhands',   label: 'All Hands' },
    { id: 'transcript', label: '✨ Transcrições' },
    { id: 'financeiro', label: 'Financeiro' },
    { id: 'custos',     label: 'Custos & retorno' },
    { id: 'time',       label: 'Time consolidado' },
    { id: 'clientes',   label: 'Saúde dos clientes' },
    { id: 'comparativos',label: 'Comparativos' },
    { id: 'propostas',  label: 'Propostas' },
    { id: 'onboarding', label: 'Onboarding · novo cliente' },
    { id: 'calendario', label: 'Calendário do time' },
  ];
  return (
    <div style={{
      display: 'flex', gap: 6, padding: 6,
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-pill)',
      width: 'fit-content', maxWidth: '100%',
      overflowX: 'auto', flexWrap: 'wrap',
    }}>
      {items.map(it => {
        const active = section === it.id;
        return (
          <button key={it.id} onClick={() => setSection(it.id)} style={{
            appearance: 'none', border: 'none',
            background: active ? 'var(--accent)' : 'transparent',
            color: active ? '#fff' : 'var(--text-muted)',
            padding: '8px 16px', fontSize: 13,
            fontWeight: active ? 500 : 400,
            borderRadius: 'var(--r-pill)', cursor: 'pointer',
            fontFamily: 'inherit', whiteSpace: 'nowrap',
          }}>{it.label}</button>
        );
      })}
    </div>
  );
}

/* ============================================================
   SHARED · BlockCard
   ============================================================ */
function BlockCard({ kicker, title, children, action, padding = 'var(--space-5)' }) {
  return (
    <section style={{
      padding,
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card-lg)',
      marginBottom: 'var(--space-5)',
    }}>
      {(kicker || title) && (
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 18, flexWrap: 'wrap' }}>
          <div>
            {kicker && <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 4 }}>{kicker}</div>}
            {title && <h3 className="t-h3" style={{ margin: 0, color: 'var(--text)' }}><Punch text={title} /></h3>}
          </div>
          {action}
        </div>
      )}
      {children}
    </section>
  );
}

function Punch({ text }) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return (
    <>
      {parts.map((p, i) =>
        p.startsWith('**') && p.endsWith('**')
          ? <span key={i} className="punch">{p.slice(2, -2)}</span>
          : <span key={i} className="t-light">{p}</span>
      )}
    </>
  );
}

function BigStat({ label, value, sub, accent, tone }) {
  const c = tone === 'error' ? 'var(--error)' : tone === 'warning' ? 'var(--warning)' : tone === 'success' ? 'var(--success)' : (accent ? 'var(--accent)' : 'var(--text)');
  return (
    <div style={{
      padding: 'var(--space-4)',
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
    }}>
      <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 6 }}>{label}</div>
      <div className="num" style={{ fontSize: 28, fontWeight: 400, color: c, lineHeight: 1, letterSpacing: '-0.01em' }}>
        {value}
      </div>
      {sub && <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 6 }}>{sub}</div>}
    </div>
  );
}

const brl = (n) => 'R$ ' + new Intl.NumberFormat('pt-BR', { maximumFractionDigits: 0 }).format(n);
const brlK = (n) => n >= 1000 ? 'R$ ' + (n/1000).toLocaleString('pt-BR', { maximumFractionDigits: 1 }) + 'k' : brl(n);

Object.assign(window, { GestaoHeader, GestaoNav, BlockCard, Punch, BigStat, brl, brlK });
