/* CONTROLLING · Vista 1 — RESUMO
   4 KPIs hero + custos fixos + tesouraria preview + onboarding em curso + sidebar Digi */

const CtrlResumoView = ({ ctx, onGoTo }) => {
  const H = window.CtrlHelpers;
  const K = window.CTRL_HEAD;
  const empresa = ctx.empresa === 'todas' ? null : window.CTRL_EMPRESAS.find(e => e.id === ctx.empresa);
  const custos = window.CTRL_CUSTOS_FIXOS;
  const custosMax = Math.max(...custos.map(c => c.v));
  const tes = window.CTRL_TESOURARIA;
  const alerts = window.CTRL_LIVE_ALERTS;
  const onboardingAtivos = window.CTRL_ONBOARDING.filter(o => o.col !== 'concluido');

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 320px', gap: 16, padding: '4px 4px 80px', alignItems: 'flex-start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minWidth: 0 }}>

          {/* Briefing matinal */}
          <div className="ai-surface card" style={{ padding: 16, borderLeft: '3px solid var(--ai-500)' }}>
            <span className="ai-chip"><span className="ai-dot" />Digi · briefing 08:00</span>
            <div style={{ fontSize: 13.5, lineHeight: 1.6, marginTop: 10 }}>
              <strong>Bom dia, Clara.</strong> Hoje no Controlling: <strong>9 faturas FSE em fila</strong> (1 escalada à Etelvina · Vodafone 8.425 €), <strong>2 RFQs em curso</strong> (consumíveis Mimaki · Adobe CC 14 lugares), <strong>contrato MR-2841 multirriscos NetScreen renova em 38 dias</strong>, e a admissão da Maria Silva (BIOND · 5/Maio) tem cartão telemóvel + seguro AT por activar. Por onde começamos?
            </div>
            <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-xs btn-ai" onClick={() => onGoTo('fse')}>Abrir inbox FSE</button>
              <button className="btn btn-xs" onClick={() => onGoTo('compras')}>Ver RFQs</button>
              <button className="btn btn-xs" onClick={() => onGoTo('activos')}>Avisar broker (MDS)</button>
              <button className="btn btn-xs" onClick={() => onGoTo('onboarding')}>Continuar admissão Maria</button>
            </div>
          </div>

          {/* 4 KPIs hero */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
            <KpiHero
              label="FSE pendentes"
              value={`${K.fsePendentes.count} · ${H.fmtEURcompact(K.fsePendentes.valor)}`}
              delta={`${K.fsePendentes.acima2500} acima de 2.500 €`}
              deltaColor="#F59E0B"
              accent="#1E40AF"
              action={<button className="btn btn-xs btn-ai" onClick={() => onGoTo('fse')}>Ir para inbox →</button>}
            />
            <KpiHero
              label="Compras abertas"
              value={`${K.comprasAbertas.count} · ${H.fmtEURcompact(K.comprasAbertas.valor)}`}
              delta={`${K.comprasAbertas.rfqAguardam} RFQ aguardam propostas`}
              deltaColor="var(--text-muted)"
              accent="#0F766E"
              action={<button className="btn btn-xs" onClick={() => onGoTo('compras')}>Ver kanban →</button>}
            />
            <KpiHero
              label="Custos fixos · mês"
              value={H.fmtEUR(K.custosFixosMes)}
              delta={K.custosFixosDelta}
              deltaColor="var(--text-muted)"
              accent="#A855F7"
              sub={empresa ? `só ${empresa.short}` : 'agregado scope · 6 empresas'}
            />
            <KpiHero
              label="Contratos · 30d"
              value={`${K.contratosExpirar30d} a expirar`}
              delta="MR-2841 · GitHub Ent · LeasePlan 88-EF-91"
              deltaColor="#F97316"
              accent="#F97316"
              action={<button className="btn btn-xs" onClick={() => onGoTo('activos')}>Ver lista →</button>}
              urgent
            />
          </div>

          {/* Custos fixos por categoria */}
          <div className="card" style={{ padding: 16 }}>
            <CardHeader title="Decomposição custos fixos · mês corrente" sub="Por categoria · vs mês anterior. Click numa barra para drilldown ao detalhe das faturas FSE." />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
              {custos.map(c => (
                <div key={c.cat} style={{ display: 'grid', gridTemplateColumns: '120px 1fr 120px 64px', alignItems: 'center', gap: 10, fontSize: 12 }}>
                  <span style={{ color: 'var(--text-muted)' }}>{c.cat}</span>
                  <div style={{ height: 14, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${(c.v / custosMax) * 100}%`, background: 'var(--ai-500)', borderRadius: 3, opacity: 0.85 }} />
                  </div>
                  <span className="font-mono" style={{ textAlign: 'right', fontWeight: 600 }}>{H.fmtEUR(c.v)}</span>
                  <span className="font-mono" style={{ fontSize: 11, color: c.deltaColor, textAlign: 'right' }}>{c.delta}</span>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: 'var(--text-muted)' }}>
              <span>Total <strong style={{ color: 'var(--text)' }}>{H.fmtEUR(K.custosFixosMes)}</strong> · sync Primavera 14:32</span>
              <button className="btn btn-xs">Drilldown →</button>
            </div>
          </div>

          {/* Tesouraria preview */}
          <div className="card" style={{ padding: 16 }}>
            <CardHeader title="Mapa tesouraria · próximas 4 semanas" sub={
              <span>Alimentado a 4 mãos: Clara mete compromissos a pagar, Sandra mete entradas previstas. <H.ValidarClara>Confirmar com Clara/Sandra exactamente o que cada uma alimenta · pode haver overlap com Tesouraria (módulo separado).</H.ValidarClara></span>
            } />
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 4 }}>
              <thead>
                <tr>
                  <th></th>
                  {tes.semanas.map(s => (
                    <th key={s} className="font-mono" style={{ padding: '6px 8px', textAlign: 'right', fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.06em', fontWeight: 600 }}>{s}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                <TesRow label="Saldo inicial" vals={tes.saldoInic} muted />
                <TesRow label="Entradas (Sandra)" vals={tes.entradas} color="var(--success)" prefix="+" />
                <TesRow label="Saídas (Clara)" vals={tes.saidas.map(v => -v)} color="var(--danger)" />
                <TesRow label="Saldo final" vals={tes.saldoFinal} bold />
              </tbody>
            </table>
            <div style={{ marginTop: 10, padding: 10, borderRadius: 5, background: 'color-mix(in oklch, var(--danger) 6%, transparent)', border: '1px solid color-mix(in oklch, var(--danger) 22%, transparent)', fontSize: 11.5 }}>
              <strong style={{ color: 'var(--danger)' }}>⚠ Saldo final Sem 21 abaixo de 250.000 €.</strong> Threshold default é 250K (config). Sandra avisada às 09:14.
            </div>
            <div style={{ marginTop: 10 }}>
              <button className="btn btn-xs">Abrir mapa completo · Tesouraria →</button>
            </div>
          </div>

          {/* Onboarding em curso */}
          <div className="card" style={{ padding: 16 }}>
            <CardHeader title="Admissões / demissões em curso" sub="Workflow orquestrado entre Clara, IT (Paulino) e RH/FC. Click para abrir checklist." />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
              {onboardingAtivos.map(o => {
                const allTasks = [...o.checklist.clara, ...o.checklist.it, ...o.checklist.rh];
                const done = allTasks.filter(t => t.done).length;
                const pct = Math.round((done / allTasks.length) * 100);
                return (
                  <button key={o.id} onClick={() => onGoTo('onboarding', { focus: o.id })} style={{
                    padding: 12, borderRadius: 6, textAlign: 'left',
                    background: 'var(--bg-sunken)', border: '1px solid var(--border)', cursor: 'pointer',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                      <span className="font-mono" style={{
                        fontSize: 9, padding: '1px 5px', borderRadius: 3, fontWeight: 700,
                        background: o.tipo === 'admissao' ? 'color-mix(in oklch, var(--success) 14%, transparent)' : 'color-mix(in oklch, #F97316 14%, transparent)',
                        color: o.tipo === 'admissao' ? 'var(--success)' : '#F97316',
                        letterSpacing: '0.06em',
                      }}>{o.tipo === 'admissao' ? 'ADMIT' : 'DEMIS'}</span>
                      {H.empresaChip(o.empresa)}
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{o.nome}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 1 }}>{o.cargo}</div>
                    <div style={{ marginTop: 8, height: 4, background: 'var(--bg-elev)', borderRadius: 2, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: pct + '%', background: pct >= 80 ? 'var(--success)' : pct >= 40 ? '#F59E0B' : '#F97316' }} />
                    </div>
                    <div style={{ marginTop: 4, fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{done}/{allTasks.length} tasks · start {o.start}</div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Cards inline — como aparece no chat */}
          <CardsInline />
        </div>

        {/* Sidebar direita */}
        <SidebarDigi alerts={alerts} />
      </div>
    </div>
  );
};

// ─── helpers internos ──────────────────────────────────────────────

const CardHeader = ({ title, sub }) => (
  <div style={{ marginBottom: 12 }}>
    <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>
    {sub && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>}
  </div>
);

const KpiHero = ({ label, value, delta, deltaColor, accent, sub, action, urgent }) => (
  <div className="card" style={{
    padding: 14, position: 'relative',
    borderTop: `2px solid ${accent}`,
    background: urgent ? 'color-mix(in oklch, var(--ai-500) 4%, var(--bg-elev))' : 'var(--bg-elev)',
  }}>
    <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</div>
    <div className="font-display" style={{ fontSize: 22, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>{value}</div>
    {(delta || sub) && (
      <div style={{ marginTop: 6, fontSize: 11, color: deltaColor || 'var(--text-muted)' }}>
        {delta}
        {sub && <span style={{ color: 'var(--text-dim)', marginLeft: 6 }}>· {sub}</span>}
      </div>
    )}
    {action && <div style={{ marginTop: 10 }}>{action}</div>}
  </div>
);

const TesRow = ({ label, vals, color, muted, bold, prefix }) => {
  const H = window.CtrlHelpers;
  return (
    <tr style={{ borderTop: '1px solid var(--border)' }}>
      <td style={{ padding: '7px 8px', fontSize: 11.5, color: muted ? 'var(--text-dim)' : 'var(--text-muted)' }}>{label}</td>
      {vals.map((v, i) => (
        <td key={i} className="font-mono" style={{
          padding: '7px 8px', textAlign: 'right',
          color: color || (bold ? 'var(--text)' : 'var(--text-muted)'),
          fontWeight: bold ? 700 : 500,
        }}>{prefix && v > 0 ? prefix : ''}{H.fmtEURcompact(Math.abs(v) * Math.sign(v || 1))}</td>
      ))}
    </tr>
  );
};

const SidebarDigi = ({ alerts }) => {
  const colors = {
    critical: { bg: 'color-mix(in oklch, var(--danger) 8%, transparent)', fg: 'var(--danger)', icon: '🚨' },
    warn:     { bg: 'color-mix(in oklch, #F59E0B 8%, transparent)',        fg: '#F59E0B',        icon: '🟡' },
    ok:       { bg: 'color-mix(in oklch, var(--success) 8%, transparent)', fg: 'var(--success)', icon: '🟢' },
  };
  return (
    <div style={{ position: 'sticky', top: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div className="ai-surface card" style={{ padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <span className="ai-chip"><span className="ai-dot" />Digi · live</span>
        </div>
        <div className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>O que está a observar</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, marginBottom: 10 }}>Eventos do Primavera + integração contratos · últimas 5h</div>

        {alerts.map((a, i) => {
          const c = colors[a.tipo];
          return (
            <div key={i} style={{
              padding: '10px 12px', marginBottom: 8, borderRadius: 5,
              background: c.bg, border: '1px solid color-mix(in oklch, ' + c.fg + ' 16%, transparent)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                <span style={{ fontSize: 12 }}>{c.icon}</span>
                <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{a.ts}</span>
              </div>
              <div style={{ fontSize: 12, lineHeight: 1.45 }}>{a.msg}</div>
            </div>
          );
        })}

        <button className="btn btn-xs" style={{ width: '100%', marginTop: 4 }}>Ver todos os eventos →</button>
      </div>
    </div>
  );
};

const CardsInline = () => {
  const H = window.CtrlHelpers;
  return (
    <div className="card" style={{ padding: 16 }}>
      <CardHeader title="Como aparece no chat com a Digi" sub="Cards inline que a Digi mostra no chat (painel lateral ou WhatsApp) quando responde sobre Controlling." />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginTop: 4 }}>
        {/* Card fatura FSE */}
        <ChatCard>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#A855F7' }} />
            <strong style={{ fontSize: 13 }}>Vodafone Empresas</strong>
            <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', marginLeft: 'auto' }}>FT V/2026/8842901</span>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 4 }}>Escalada Etelvina · &gt;2.500 €</div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 8 }}>
            <span style={{ color: 'var(--text-muted)' }}>Total c/ IVA</span>
            <span className="font-mono" style={{ fontWeight: 600 }}>8.425,50 €</span>
          </div>
          <button className="btn btn-xs btn-ai" style={{ width: '100%' }}>Ver workflow →</button>
        </ChatCard>

        {/* Card duplicado */}
        <ChatCard>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#F59E0B' }} />
            <strong style={{ fontSize: 13 }}>EDP · possível duplicado</strong>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 4 }}>FT 2026/A/14209 entrou 2× <strong>(SA + NS)</strong></div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 8 }}>Mesmo nº doc · mesmo total · empresas diferentes</div>
          <button className="btn btn-xs">Comparar →</button>
        </ChatCard>

        {/* Card encomenda recebida */}
        <ChatCard>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <strong style={{ fontSize: 13 }}>Encomenda EC2841</strong>
            <span className="font-mono" style={{ fontSize: 10, padding: '1px 5px', borderRadius: 3, background: 'color-mix(in oklch, var(--success) 14%, transparent)', color: 'var(--success)' }}>recebida</span>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 4 }}>NetScreen · Cabos UTP cat6 200m · 380 €</div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 8 }}>Match com fatura ainda pendente.</div>
          <button className="btn btn-xs btn-ai" style={{ width: '100%' }}>Fazer match →</button>
        </ChatCard>

        {/* Card admissão */}
        <ChatCard>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ fontSize: 18 }}>👤</span>
            <strong style={{ fontSize: 13 }}>Maria Silva · admissão</strong>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 4 }}>BIOND · Designer · start <strong>5/Maio</strong></div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 8 }}>Checklist 4/14 · 2 tasks bloqueadas (cartão telemóvel + seguro AT)</div>
          <button className="btn btn-xs btn-ai" style={{ width: '100%' }}>Abrir workflow →</button>
        </ChatCard>
      </div>
    </div>
  );
};

const ChatCard = ({ children }) => (
  <div style={{
    padding: 12, borderRadius: 6,
    background: 'var(--bg-sunken)', border: '1px solid var(--border)',
  }}>{children}</div>
);

window.CtrlResumoView = CtrlResumoView;
