/* global React, BezaLogo, Icon, Pill, Card, Delta, Infotip, fmt */
const { useState: useStateIdx, useEffect: useEffectIdx, useMemo: useMemoIdx, useRef: useRefIdx } = React;

/* ============================================================
   BEZA · COMMAND CENTER · dashboard interno da agência
   "Relatórios" é apenas um dos módulos.
   ============================================================ */

// BEZA:CLIENTS-INDEX
const AGENCY_CLIENTS = [
  { slug: 'soldado-de-deus',   brand: 'Soldado de Deus',        responsible: 'Rob Grier',              segment: 'Conteúdo cristão · liderança',              channels: ['instagram', 'youtube'],                        startedAt: 'set/2025', lastUpdated: 'abr/2026', status: 'ativo', lastReach: 6086,   lastReachDelta: null, hasReport: true  },
  { slug: 'divine',            brand: 'Divine Home Improvement', responsible: 'Phillip De Melo',        segment: 'Home improvement · Massachusetts',           channels: ['instagram', 'linkedin'],                       startedAt: 'mai/2026', lastUpdated: '',         status: 'novo',  lastReach: 0,      lastReachDelta: 0,   hasReport: false },
  { slug: 'hope',              brand: 'Hope · Pr. Wanderson',    responsible: 'Pr. Wanderson Braga',    segment: 'Liderança cristã · movimento global',        channels: ['instagram', 'youtube', 'threads', 'tiktok'],   startedAt: 'mai/2026', lastUpdated: '',         status: 'novo',  lastReach: 0,      lastReachDelta: 0,   hasReport: false },
  { slug: 'projeto-eu',        brand: 'Projeto EU',              responsible: 'Pr. Wanderson Braga',    segment: 'Transformação cristã · Brasil + EUA',        channels: ['instagram', 'youtube', 'threads', 'tiktok'],   startedAt: 'mai/2026', lastUpdated: '',         status: 'novo',  lastReach: 0,      lastReachDelta: 0,   hasReport: false },
  { slug: 'filhos-reais',      brand: 'Filhos Reais',            responsible: 'Luana Carvalho Gomes',   segment: 'Maternidade · fé cristã · neurociência',    channels: ['instagram'],                                   startedAt: 'mai/2026', lastUpdated: '',         status: 'novo',  lastReach: 0,      lastReachDelta: 0,   hasReport: false },
  { slug: 'possmozer-usa',     brand: 'Possmozer USA',           responsible: 'Ellem Possmozer',        segment: 'Saúde mental · brasileiros nos EUA',         channels: ['instagram', 'youtube'],                        startedAt: 'mai/2026', lastUpdated: '',         status: 'novo',  lastReach: 0,      lastReachDelta: 0,   hasReport: false },
  { slug: 'samara-soares',     brand: 'Samara Soares',           responsible: 'Samara Soares',          segment: 'Mentoria de vendas High Ticket',             channels: ['instagram'],                                   startedAt: 'fev/2026', lastUpdated: 'abr/2026', status: 'ativo', lastReach: 8242,   lastReachDelta: 15.09, hasReport: true  },
  { slug: 'anderson-guzanshe', brand: 'Pr. Anderson Guzanshe',   responsible: 'Anderson Guzanshe',      segment: 'Formação da alma · maturidade espiritual',   channels: ['instagram'],                                   startedAt: 'mai/2026', lastUpdated: '',         status: 'novo',  lastReach: 0,      lastReachDelta: 0,   hasReport: false },
  { slug: 'ge-builders',       brand: 'GE Builders',             responsible: 'Geliabi Zotti',          segment: 'Construção de alto padrão · Massachusetts',  channels: ['instagram'],                                   startedAt: 'abr/2026', lastUpdated: 'abr/2026', status: 'ativo', lastReach: 1198,   lastReachDelta: 2039.29, hasReport: true  },
  { slug: 'agroexata',         brand: 'Agroexata',               responsible: 'Fernando Martins',       segment: 'Agricultura de precisão · Consultoria Agro',  channels: ['instagram', 'linkedin'],                       startedAt: 'abr/2026', lastUpdated: 'abr/2026', status: 'ativo', lastReach: 4980,   lastReachDelta: 189.87, hasReport: true  },
  { slug: 'brady-bankston',    brand: 'Brady Bankston',          responsible: 'Brady Bankston',         segment: 'GC · construção residencial · Rhode Island', channels: ['instagram'],                                   startedAt: 'mai/2026', lastUpdated: '',         status: 'novo',  lastReach: 0,      lastReachDelta: 0,   hasReport: false },
];
// BEZA:END

const MODULES = [
  {
    id: 'reports',
    label: 'Relatórios',
    kicker: 'mensal · automatizado',
    desc: 'Dashboard mensal por cliente · alimenta-se sozinho via mLabs e canais. Links únicos por cliente.',
    icon: Icon.Analytics,
    status: 'ativo',
    accent: '#9A9BE5',
  },
  {
    id: 'pauta',
    label: 'Pauta',
    kicker: 'demanda do mês · time',
    desc: 'Visualização estratégica sobre o ClickUp. Carga de cada colaborador, % até fechar o mês, mural da reunião de segunda.',
    icon: Icon.Calendar,
    status: 'ativo',
    accent: '#9A9BE5',
  },
  {
    id: 'proposals',
    label: 'Propostas',
    kicker: 'pipeline comercial',
    desc: 'Geração e tracking de propostas. Link único por lead, expira em 14 dias, sinaliza quando abrem.',
    icon: Icon.External,
    status: 'em-breve',
  },
  {
    id: 'crm',
    label: 'CRM de clientes',
    kicker: 'relacionamento + histórico',
    desc: 'Ficha de cada cliente · contratos, briefings, deliveries, datas-chave, anotações de reunião.',
    icon: Icon.Users,
    status: 'em-breve',
  },
  {
    id: 'finance',
    label: 'Financeiro',
    kicker: 'contratos + recorrência',
    desc: 'MRR, recebíveis, status de pagamento por cliente. Conexão com Asaas / banco.',
    icon: Icon.Up,
    status: 'planejado',
  },
  {
    id: 'team',
    label: 'Gestão da Beza',
    kicker: 'minha visão · gestor',
    desc: 'Sua perspectiva como gestor: subir demandas novas, definir datas-chave, acompanhar desempenho do time, ver alocação e gargalos. Camada que fica por cima da Pauta.',
    icon: Icon.Sparkle,
    status: 'em-breve',
  },
];

/* ============================================================
   APP
   ============================================================ */
function IndexApp() {
  const [activeModule, setActiveModule] = useStateIdx('reports');

  return (
    <>
      <TopBar />
      <HeroCommand />
      <ModulesNav active={activeModule} onSelect={setActiveModule} />
      <main style={{
        maxWidth: 1320, margin: '0 auto',
        padding: '0 var(--space-5) var(--space-8)',
      }}>
        {activeModule === 'reports' ? (
          <ReportsModule />
        ) : activeModule === 'pauta' ? (
          <PautaApp />
        ) : (
          <ComingSoonModule module={MODULES.find(m => m.id === activeModule)} />
        )}
        <IndexFooter />
      </main>
    </>
  );
}

/* ============================================================
   TOPBAR · sticky, branding + área interna marker
   ============================================================ */
function TopBar() {
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 30,
      borderBottom: '1px solid var(--border)',
      background: 'var(--surface-strong)',
      backdropFilter: 'blur(20px) saturate(140%)',
      WebkitBackdropFilter: 'blur(20px) saturate(140%)',
    }}>
      <div style={{
        maxWidth: 1320, margin: '0 auto',
        padding: '16px var(--space-5)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 16, flexWrap: 'wrap',
      }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 14 }}>
          <BezaLogo size={26} />
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '4px 10px',
            background: 'var(--accent-soft)',
            border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-pill)',
            fontSize: 11, fontWeight: 500,
            letterSpacing: '0.08em', textTransform: 'uppercase',
            color: 'var(--accent)',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'currentColor' }} />
            Acesso interno
          </span>
        </div>

        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 16 }}>
          <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>
            Equipe Beza · 4 membros
          </span>
          <div style={{
            width: 32, height: 32, borderRadius: '50%',
            background: 'linear-gradient(135deg, var(--accent), var(--beza-deep))',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontWeight: 500, fontSize: 13,
          }}>
            L
          </div>
        </div>
      </div>
    </header>
  );
}

/* ============================================================
   HERO · "painel de comando"
   ============================================================ */
function HeroCommand() {
  const ativos = AGENCY_CLIENTS.filter(c => c.status === 'ativo').length;
  const novos = AGENCY_CLIENTS.filter(c => c.status === 'novo').length;
  const totalReach = AGENCY_CLIENTS.reduce((a, c) => a + (c.status !== 'pausado' ? c.lastReach : 0), 0);

  return (
    <section style={{
      position: 'relative', overflow: 'hidden',
      borderBottom: '1px solid var(--border)',
    }}>
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(circle at 85% 30%, rgba(154,155,229,0.18), transparent 55%)',
        pointerEvents: 'none',
      }} />
      <div aria-hidden="true" style={{
        position: 'absolute', top: '-40%', left: '-10%',
        width: 600, height: 600, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(154,155,229,0.10), transparent 60%)',
        filter: 'blur(40px)',
        pointerEvents: 'none',
      }} />

      <div style={{
        maxWidth: 1320, margin: '0 auto',
        padding: 'var(--space-7) var(--space-5) var(--space-6)',
        position: 'relative',
      }}>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 14 }}>
          Beza Media · painel de comando
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 'var(--space-6)', alignItems: 'flex-end', flexWrap: 'wrap' }}>
          <h1 className="t-display" style={{
            margin: 0,
            maxWidth: 820,
            color: 'var(--text)',
            textWrap: 'pretty',
          }}>
            <span className="t-light">Tudo que a Beza opera, num </span>
            <span className="punch">lugar só</span>
            <span className="t-light">.</span>
          </h1>

          <p className="t-body" style={{
            margin: 0,
            maxWidth: 440,
            color: 'var(--text-muted)',
            fontSize: 16,
          }}>
            Relatórios é o primeiro módulo. Cada cliente acessa só o próprio link. Em breve, propostas, CRM e financeiro entram no mesmo painel.
          </p>
        </div>

        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',
          gap: 'var(--space-5)',
          marginTop: 'var(--space-6)',
          paddingTop: 'var(--space-5)',
          borderTop: '1px solid var(--border)',
        }}>
          <HeroStat label="Clientes ativos" value={ativos} accent />
          <HeroStat label="Em onboarding" value={novos} />
          <HeroStat label="Alcance total · abr" value={fmt.k(totalReach)} />
          <HeroStat label="Módulos · ativos / total" value={`2 / ${MODULES.length}`} />
        </div>
      </div>
    </section>
  );
}

function HeroStat({ label, value, accent }) {
  return (
    <div>
      <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 6 }}>
        {label}
      </div>
      <div className="num" style={{
        fontSize: 'clamp(28px, 3.4vw, 40px)',
        fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1,
        color: accent ? 'var(--accent)' : 'var(--text)',
      }}>
        {value}
      </div>
    </div>
  );
}

/* ============================================================
   MODULES NAV · sticky chips abaixo do hero
   ============================================================ */
function ModulesNav({ active, onSelect }) {
  return (
    <div style={{
      position: 'sticky', top: 65, zIndex: 20,
      borderBottom: '1px solid var(--border)',
      background: 'var(--surface-soft)',
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
    }}>
      <div style={{
        maxWidth: 1320, margin: '0 auto',
        padding: '12px var(--space-5)',
        display: 'flex', gap: 6,
        overflowX: 'auto',
        scrollbarWidth: 'none',
      }}>
        {MODULES.map(m => {
          const isActive = m.id === active;
          const isAvail  = m.status === 'ativo';
          const I = m.icon;
          return (
            <button
              key={m.id}
              onClick={() => onSelect(m.id)}
              style={{
                appearance: 'none',
                border: '1px solid',
                borderColor: isActive ? 'var(--accent)' : 'var(--border)',
                background: isActive ? 'var(--accent-soft)' : 'transparent',
                color: isActive ? 'var(--accent)' : 'var(--text-muted)',
                padding: '8px 14px',
                borderRadius: 'var(--r-pill)',
                fontSize: 13,
                fontWeight: isActive ? 500 : 400,
                fontFamily: 'inherit',
                cursor: 'pointer',
                whiteSpace: 'nowrap',
                display: 'inline-flex',
                alignItems: 'center',
                gap: 8,
                transition: 'all var(--t-fast) var(--ease-out)',
                opacity: isAvail ? 1 : 0.85,
              }}
            >
              <I width={14} height={14} />
              {m.label}
              {!isAvail && (
                <span style={{
                  fontSize: 10, padding: '2px 6px',
                  borderRadius: 999,
                  background: 'var(--surface)',
                  border: '1px solid var(--border)',
                  color: 'var(--text-faint)',
                  letterSpacing: '0.06em',
                  textTransform: 'uppercase',
                }}>
                  {m.status === 'em-breve' ? 'em breve' : 'planejado'}
                </span>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ============================================================
   REPORTS MODULE · módulo atual
   ============================================================ */
function ReportsModule() {
  const [filter, setFilter] = useStateIdx('todos');
  const [query, setQuery] = useStateIdx('');

  const filtered = useMemoIdx(() => {
    return AGENCY_CLIENTS.filter(c => {
      if (filter !== 'todos' && c.status !== filter) return false;
      if (query && !(`${c.brand} ${c.responsible} ${c.segment}`).toLowerCase().includes(query.toLowerCase())) return false;
      return true;
    });
  }, [filter, query]);

  const totals = useMemoIdx(() => ({
    total: AGENCY_CLIENTS.length,
    ativos: AGENCY_CLIENTS.filter(c => c.status === 'ativo').length,
    novos: AGENCY_CLIENTS.filter(c => c.status === 'novo').length,
    pausados: AGENCY_CLIENTS.filter(c => c.status === 'pausado').length,
  }), []);

  return (
    <div style={{ padding: 'var(--space-6) 0 0' }}>
      <div style={{
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
        gap: 24, marginBottom: 'var(--space-5)', flexWrap: 'wrap',
      }}>
        <div>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>
            Módulo · Relatórios
          </div>
          <h2 className="t-h1" style={{ margin: 0, color: 'var(--text)' }}>
            <span className="t-light">Cada cliente, um </span>
            <span className="punch">link único</span>
            <span className="t-light">. Cada mês, atualizado sozinho.</span>
          </h2>
        </div>
        <div style={{
          padding: 'var(--space-3) var(--space-4)',
          background: 'var(--surface)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-card)',
          maxWidth: 360,
        }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <Icon.Info width={14} height={14} style={{ color: 'var(--accent)' }} />
            <span className="t-overline" style={{ color: 'var(--accent)' }}>Como funciona o acesso</span>
          </div>
          <p style={{ margin: 0, fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
            O link de cada cliente é único e privado. Você envia <span style={{ fontFamily: 'monospace', color: 'var(--text)' }}>beza.media/[slug]</span> apenas para aquele cliente. Ninguém vê o relatório de ninguém.
          </p>
        </div>
      </div>

      <Toolbar filter={filter} setFilter={setFilter} query={query} setQuery={setQuery} count={filtered.length} totals={totals} />

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))',
        gap: 16,
      }}>
        {filtered.map(c => <ClientCard key={c.slug} client={c} />)}
      </div>

      {filtered.length === 0 && (
        <div style={{
          padding: 'var(--space-7)', textAlign: 'center', color: 'var(--text-muted)',
          border: '1px dashed var(--border-strong)', borderRadius: 'var(--r-card-lg)',
        }}>
          Nenhum cliente com esse filtro.
        </div>
      )}
    </div>
  );
}

function Toolbar({ filter, setFilter, query, setQuery, count, totals }) {
  const tabs = [
    { id: 'todos',    label: 'Todos',       n: totals.total },
    { id: 'ativo',    label: 'Ativos',      n: totals.ativos },
    { id: 'novo',     label: 'Onboarding',  n: totals.novos },
    { id: 'pausado',  label: 'Pausados',    n: totals.pausados },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      gap: 16, flexWrap: 'wrap',
      marginBottom: 'var(--space-5)',
      padding: 'var(--space-3) var(--space-3)',
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
    }}>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
        {tabs.map(tab => {
          const active = filter === tab.id;
          return (
            <button key={tab.id} onClick={() => setFilter(tab.id)} style={{
              appearance: 'none',
              border: '1px solid',
              borderColor: active ? 'var(--accent)' : 'transparent',
              background: active ? 'var(--accent-soft)' : 'transparent',
              color: active ? 'var(--accent)' : 'var(--text-muted)',
              padding: '6px 12px', fontSize: 13,
              fontWeight: active ? 500 : 400,
              borderRadius: 'var(--r-pill)', cursor: 'pointer',
              fontFamily: 'inherit',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {tab.label}
              <span style={{ fontSize: 11, color: 'var(--text-faint)', fontVariantNumeric: 'tabular-nums' }}>{tab.n}</span>
            </button>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <input
          type="text"
          placeholder="Buscar cliente, segmento..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          style={{
            appearance: 'none',
            border: '1px solid var(--border-strong)',
            background: 'var(--bg-flat)',
            color: 'var(--text)',
            padding: '8px 14px', fontSize: 13,
            borderRadius: 'var(--r-btn)',
            fontFamily: 'inherit', minWidth: 240,
            outline: 'none',
          }}
        />
        <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>{count} resultado{count === 1 ? '' : 's'}</span>
      </div>
    </div>
  );
}

/* ============================================================
   CLIENT CARD · com link único + spotlight
   ============================================================ */
function ClientCard({ client }) {
  const ref = useRefIdx(null);
  const onMove = (e) => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    ref.current.style.setProperty('--mx', (e.clientX - r.left) + 'px');
    ref.current.style.setProperty('--my', (e.clientY - r.top) + 'px');
  };

  const statusMeta = {
    ativo:   { label: 'Ativo',      tone: 'success' },
    novo:    { label: 'Onboarding', tone: 'purple' },
    pausado: { label: 'Pausado',    tone: 'warning' },
  }[client.status];

  const Tag = client.hasReport ? 'a' : 'div';
  const linkProps = client.hasReport ? { href: `clientes/${client.slug}.html` } : {};

  return (
    <Tag
      ref={ref}
      onMouseMove={onMove}
      {...linkProps}
      style={{
        display: 'flex', flexDirection: 'column',
        textDecoration: 'none', color: 'var(--text)',
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-card-lg)',
        padding: 'var(--space-4)',
        gap: 'var(--space-3)',
        transition: 'all var(--t-base) var(--ease-out)',
        position: 'relative',
        overflow: 'hidden',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        isolation: 'isolate',
        opacity: client.hasReport ? 1 : 0.82,
        cursor: client.hasReport ? 'pointer' : 'default',
      }}
      onMouseEnter={(e) => {
        if (!client.hasReport) return;
        e.currentTarget.style.borderColor = 'var(--accent)';
        e.currentTarget.style.transform = 'translateY(-3px)';
        e.currentTarget.style.boxShadow = '0 12px 32px rgba(154,155,229,0.18)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.borderColor = 'var(--border)';
        e.currentTarget.style.transform = '';
        e.currentTarget.style.boxShadow = '';
      }}
    >
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(circle 240px at var(--mx, 50%) var(--my, 50%), rgba(154,155,229,0.18), transparent 60%)',
        opacity: 0, transition: 'opacity var(--t-base)',
        pointerEvents: 'none', zIndex: 0,
      }} className="card-spotlight" />

      {/* faixa lateral lilás */}
      <div style={{
        position: 'absolute', top: 0, left: 0, bottom: 0,
        width: 3, background: 'var(--accent)', opacity: 0.7, zIndex: 1,
      }} />

      <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 4 }}>
              {client.segment}
            </div>
            <h3 style={{
              margin: 0, fontSize: 22, fontWeight: 400, letterSpacing: '-0.01em',
              lineHeight: 1.2, color: 'var(--text)',
            }}>
              {client.brand}
            </h3>
            <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>
              {client.responsible}
            </div>
          </div>
          <Pill tone={statusMeta.tone}>{statusMeta.label}</Pill>
        </div>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: 'var(--space-3) 0',
          borderTop: '1px solid var(--border)',
          borderBottom: '1px solid var(--border)',
        }}>
          {client.channels.map(ch => {
            const M = window.CHANNEL_META?.[ch];
            if (!M) return null;
            return (
              <span key={ch} title={M.label} style={{ color: 'var(--text-muted)' }}>
                <M.Icon width={18} height={18} />
              </span>
            );
          })}
          <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-faint)' }}>
            Início {client.startedAt}
          </span>
        </div>

        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
          <div>
            {client.hasReport ? (
              <>
                <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 2 }}>
                  Alcance · {client.lastUpdated}
                </div>
                <div className="num" style={{ fontSize: 24, fontWeight: 400, lineHeight: 1, color: 'var(--text)' }}>
                  {fmt.k(client.lastReach)}
                </div>
                <Delta value={client.lastReachDelta} />
              </>
            ) : (
              <div style={{ fontSize: 13, color: 'var(--text-faint)', fontStyle: 'italic' }}>
                Relatório em preparação
              </div>
            )}
          </div>
          {client.hasReport ? (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--accent)', fontSize: 13, fontWeight: 500 }}>
              Abrir relatório
              <Icon.Arrow width={16} height={16} />
            </div>
          ) : (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--text-faint)', fontSize: 12 }}>
              <Icon.Calendar width={14} height={14} />
              Dia 05 · próximo mês
            </div>
          )}
        </div>

        <div style={{
          marginTop: 6,
          padding: '8px 12px',
          background: 'var(--surface-soft)',
          border: '1px dashed var(--border-strong)',
          borderRadius: 'var(--r-btn)',
          fontFamily: 'monospace',
          fontSize: 11,
          color: 'var(--text-faint)',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <Icon.External width={11} height={11} />
          dash.beza.media/{client.slug}
        </div>
      </div>
    </Tag>
  );
}

/* ============================================================
   ComingSoonModule · placeholder dos módulos planejados
   ============================================================ */
function ComingSoonModule({ module }) {
  if (!module) return null;
  const I = module.icon;
  return (
    <div style={{ padding: 'var(--space-6) 0 0' }}>
      <div style={{
        padding: 'var(--space-7)',
        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',
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', top: '-30%', right: '-10%',
          width: 480, height: 480, 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', flexDirection: 'column', gap: 20, maxWidth: 720 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 12,
            width: 'fit-content',
          }}>
            <div style={{
              width: 48, height: 48,
              borderRadius: 'var(--r-card)',
              background: 'var(--accent-soft)',
              border: '1px solid var(--border-strong)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--accent)',
            }}>
              <I width={22} height={22} />
            </div>
            <Pill tone="purple">{module.status === 'em-breve' ? 'Em desenvolvimento' : 'Planejado'}</Pill>
          </div>

          <h2 className="t-h1" style={{ margin: 0, color: 'var(--text)' }}>
            <span className="t-light">{module.label}</span>
          </h2>

          <div className="t-overline" style={{ color: 'var(--accent)' }}>
            {module.kicker}
          </div>

          <p className="t-body" style={{ margin: 0, color: 'var(--text-muted)', maxWidth: 560 }}>
            {module.desc}
          </p>

          <div style={{ display: 'inline-flex', gap: 12, alignItems: 'center', marginTop: 8 }}>
            <button style={{
              appearance: 'none', border: '1px solid var(--border-strong)',
              background: 'var(--surface-strong)',
              color: 'var(--text-muted)',
              padding: '10px 18px', borderRadius: 'var(--r-btn)',
              fontSize: 13, fontFamily: 'inherit',
              cursor: 'not-allowed',
            }} disabled>
              Aguardando · sem acesso ainda
            </button>
            <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>
              A Beza está construindo este módulo aos poucos.
            </span>
          </div>
        </div>
      </div>

      <div style={{ marginTop: 'var(--space-6)' }}>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 16 }}>
          Roadmap dos módulos
        </div>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 12,
        }}>
          {MODULES.map(m => {
            const I2 = m.icon;
            const active = m.status === 'ativo';
            return (
              <div key={m.id} style={{
                padding: 'var(--space-3) var(--space-4)',
                background: active ? 'var(--accent-soft)' : 'var(--surface)',
                border: '1px solid',
                borderColor: active ? 'var(--border-strong)' : 'var(--border)',
                borderRadius: 'var(--r-card)',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <I2 width={16} height={16} style={{ color: active ? 'var(--accent)' : 'var(--text-faint)' }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{m.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>
                    {m.status === 'ativo' ? 'em produção' : (m.status === 'em-breve' ? 'em breve' : 'planejado')}
                  </div>
                </div>
                {active && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--success)' }} />}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */
function IndexFooter() {
  return (
    <footer style={{
      marginTop: 'var(--space-8)',
      paddingTop: 'var(--space-6)',
      borderTop: '1px solid var(--border)',
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
      gap: 'var(--space-5)',
    }}>
      <div>
        <BezaLogo size={22} />
        <p className="t-caption" style={{ color: 'var(--text-faint)', marginTop: 12, maxWidth: 280 }}>
          Painel interno · uso exclusivo da equipe. Os links dos relatórios são públicos só pra quem recebe pelo cliente.
        </p>
      </div>
      <div>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 12 }}>Privacidade</div>
        <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13, color: 'var(--text-muted)' }}>
          <li>· 1 link por cliente · não compartilhado</li>
          <li>· Sem login pro cliente (acesso pela URL)</li>
          <li>· Equipe Beza acessa este painel</li>
        </ul>
      </div>
      <div>
        <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 12 }}>Automação</div>
        <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13, color: 'var(--text-muted)' }}>
          <li>· Dia 01 · Claude Code puxa mLabs</li>
          <li>· Dia 02 · Beza revisa carta editorial</li>
          <li>· Dia 03 · Publicação automática</li>
        </ul>
      </div>
    </footer>
  );
}

Object.assign(window, {
  AGENCY_CLIENTS, MODULES, IndexApp, TopBar, HeroCommand, HeroStat,
  ModulesNav, ReportsModule, Toolbar, ClientCard, ComingSoonModule, IndexFooter,
});
