/* Comercial · Dashboard (HOME)
 * ========================================================================
 * Nova home do Comercial — painel resumido de todas as sub-secções.
 * Substitui "Digi" como landing. Digi passa a sub-nav "Chat".
 *
 * Estrutura (scroll vertical, arejado):
 *   1. Hero — saudação Digi + estado BP
 *   2. BP destacado — cartão grande com gap projectado + CTA
 *   3. 3 acções urgentes hoje (Carteira · OPs · Prospecção · Financeiro · SAT)
 *   4. Pulse 4 secções (Clientes · Carteira · Prospecção · OPs) com sparklines/donuts
 *   5. Input "Pergunta à Digi…" com chips
 * ======================================================================== */

// ============================================================================
// MICRO-VIS: sparkline e donut SVG
// ============================================================================
const Sparkline = ({ values, color = 'var(--accent)', w = 120, h = 28, showLast = true }) => {
  const vals = values.filter((v) => v != null);
  if (vals.length < 2) return null;
  const min = Math.min(...vals);
  const max = Math.max(...vals);
  const range = max - min || 1;
  const step = w / (values.length - 1);
  const points = values.map((v, i) => {
    if (v == null) return null;
    const x = i * step;
    const y = h - ((v - min) / range) * (h - 4) - 2;
    return `${x},${y}`;
  }).filter(Boolean).join(' ');
  const lastIdx = values.map((v, i) => v != null ? i : -1).filter((i) => i >= 0).pop();
  const lastX = lastIdx * step;
  const lastY = h - ((values[lastIdx] - min) / range) * (h - 4) - 2;
  return (
    <svg width={w} height={h} style={{ display: 'block' }}>
      <polyline fill="none" stroke={color} strokeWidth="1.5" points={points} />
      {showLast && <circle cx={lastX} cy={lastY} r="2.5" fill={color} />}
    </svg>
  );
};

const Donut = ({ value, max = 100, size = 48, stroke = 5, color = 'var(--accent)', label }) => {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const pct = Math.min(value / max, 1);
  const offset = c - pct * c;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--border)" strokeWidth={stroke} />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
                strokeDasharray={c} strokeDashoffset={offset} strokeLinecap="round"
                transform={`rotate(-90 ${size/2} ${size/2})`} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-mono)' }}>
        {label}
      </div>
    </div>
  );
};

// ============================================================================
// HERO — saudação Digi + barra BP compacta
// ============================================================================
const DashHero = () => {
  const nowStr = (() => {
    const d = new Date();
    const dias = ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'];
    const meses = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
    return `${dias[d.getDay()]}, ${d.getDate()} de ${meses[d.getMonth()]}`;
  })();
  return (
    <div>
      <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', marginBottom: 4 }}>
        COMERCIAL · {nowStr.toUpperCase()}
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 16 }}>
        <h1 className="font-display" style={{ margin: 0, fontSize: 30, fontWeight: 600, letterSpacing: '-0.015em' }}>
          Bom dia, Daniel.
        </h1>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-muted)' }}>
          <span className="ai-chip"><span className="ai-dot" />Digi</span>
          <span>3 acções urgentes hoje · <a style={{ color: 'var(--accent)', textDecoration: 'none', cursor: 'pointer' }}>ver ↓</a></span>
        </div>
      </div>
      <p style={{ margin: '6px 0 0', fontSize: 13.5, color: 'var(--text-muted)', maxWidth: 680 }}>
        Estás a 25% do BP anual e já passou 33% do ano. Identifiquei <strong style={{ color: 'var(--text)' }}>€1,65M recuperáveis</strong> entre carteira, OPs paradas e prospecção. Gap residual: €1,05M.
      </p>
    </div>
  );
};

// ============================================================================
// CARTÃO BP DESTACADO
// ============================================================================
const DashBPCard = ({ onNav }) => {
  // mini-matriz de desvio 12m (sparkline)
  const desvios = [-55130, -106390, 5201, -226706, -556706, -881706, -1206706, -1426706, -1751706, -2081706, -2411706, -2736706];
  return (
    <div onClick={() => onNav && onNav('bp')}
         style={{
           background: 'var(--bg-elev)',
           border: '1px solid var(--border)', borderLeft: '3px solid var(--danger)',
           borderRadius: 10, padding: 18, cursor: 'pointer',
           display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr auto', alignItems: 'center', gap: 20,
         }}
         onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-elev-2)'}
         onMouseLeave={(e) => e.currentTarget.style.background = 'var(--bg-elev)'}
    >
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)', marginBottom: 4 }}>BUSINESS PLAN 2026</div>
        <div className="font-display" style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em', marginBottom: 4 }}>Desvio crítico</div>
        <div style={{ fontSize: 12.5, color: 'var(--text-muted)', lineHeight: 1.5 }}>
          Vendas <strong style={{ color: 'var(--text)' }}>€923k</strong> vs BP <strong style={{ color: 'var(--text)' }}>€1,15M</strong> YTD
        </div>
      </div>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)', marginBottom: 4 }}>GAP PROJECTADO</div>
        <div className="font-display" style={{ fontSize: 26, fontWeight: 600, color: 'var(--danger)', letterSpacing: '-0.01em' }}>−€2,7M</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>+€342k/mês p/ recuperar</div>
      </div>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>DESVIO ACUMULADO</div>
        <Sparkline values={desvios} color="var(--danger)" w={140} h={32} />
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 2 }}>JAN → DEZ</div>
      </div>
      <button className="btn btn-primary" style={{ fontSize: 12, padding: '8px 14px', whiteSpace: 'nowrap' }}>Ver plano →</button>
    </div>
  );
};

// ============================================================================
// 3 ACÇÕES URGENTES HOJE
// ============================================================================
const DASH_ACCOES = [
  {
    kind: 'carteira', kindLabel: 'CARTEIRA', kindColor: 'var(--accent)',
    titulo: 'João Afonso · Olimpo Lda',
    body: 'Respondeu no WhatsApp ontem às 22:47. Disse que reuniu com a Roland hoje. Urgente reagir antes de fecharem.',
    metric: '€95k', metricLabel: 'potencial',
    cta: 'Abrir conversa', navTo: 'clientes',
  },
  {
    kind: 'ops', kindLabel: 'OP · PRIMAVERA', kindColor: 'var(--warning)',
    titulo: 'Vinyl Lab · Proposta Mimaki UJV200',
    body: 'Proposta enviada há 33 dias sem resposta. Valor €110k · fase "proposta enviada". Follow-up automático sugerido.',
    metric: '33d', metricLabel: 'parado',
    cta: 'Fazer follow-up', navTo: 'carteira',
  },
  {
    kind: 'prospec', kindLabel: 'PROSPECÇÃO ES', kindColor: 'var(--success)',
    titulo: 'Impresión Madrid Digital · Score 9/10',
    body: 'Lead detectado hoje. CNAE 1812, 28 colaboradores, comprou HP Latex há 4 anos. Match directo Mimaki UJV200.',
    metric: '€120k', metricLabel: 'potencial',
    cta: 'Ver lead', navTo: 'prospeccao',
  },
  {
    kind: 'finance', kindLabel: 'FINANCEIRO', kindColor: 'var(--danger)',
    titulo: 'Gráfica Central, Lda · €12.400 em dívida',
    body: 'Factura vencida há 67 dias. Patrícia Mota já enviou 2 lembretes. Antes de abordares recompra, tens de resolver.',
    metric: '67d', metricLabel: 'em atraso',
    cta: 'Ver aging',
  },
  {
    kind: 'sat', kindLabel: 'SAT', kindColor: '#c084fc',
    titulo: 'Rótulos Norte · Mimaki UJV200 em down',
    body: 'Máquina parada há 2 dias. Técnico agendado para amanhã. Falar com o cliente antes que abra novo fornecedor.',
    metric: '2d', metricLabel: 'down',
    cta: 'Ver ticket',
  },
];

const DashAccoes = ({ onNav }) => {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
        <h3 className="font-display" style={{ margin: 0, fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>Acções urgentes hoje</h3>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>5 alertas que não podem passar para amanhã</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 10 }}>
        {DASH_ACCOES.map((a, i) => (
          <div key={i}
               onClick={() => a.navTo && onNav && onNav(a.navTo)}
               style={{
                 background: 'var(--bg-elev)', border: '1px solid var(--border)',
                 borderTop: `2px solid ${a.kindColor}`,
                 borderRadius: 10, padding: 14, cursor: a.navTo ? 'pointer' : 'default',
                 transition: 'background 0.15s',
                 display: 'flex', flexDirection: 'column', gap: 8,
               }}
               onMouseEnter={(e) => a.navTo && (e.currentTarget.style.background = 'var(--bg-elev-2)')}
               onMouseLeave={(e) => a.navTo && (e.currentTarget.style.background = 'var(--bg-elev)')}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontSize: 9.5, color: a.kindColor, letterSpacing: '0.08em', fontFamily: 'var(--font-mono)', fontWeight: 700 }}>
                {a.kindLabel}
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="font-display" style={{ fontSize: 16, fontWeight: 600, color: a.kindColor, lineHeight: 1 }}>{a.metric}</div>
                <div style={{ fontSize: 9, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>{a.metricLabel.toUpperCase()}</div>
              </div>
            </div>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text)' }}>{a.titulo}</div>
            <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5, flex: 1 }}>{a.body}</div>
            <button className="btn" style={{ fontSize: 11, padding: '6px 10px', alignSelf: 'flex-start' }}>{a.cta} →</button>
          </div>
        ))}
      </div>
    </div>
  );
};

// ============================================================================
// PULSE — 4 cartões (Clientes, Carteira, Prospecção, OPs Primavera)
// ============================================================================
const DashPulseClientes = ({ onNav }) => (
  <div onClick={() => onNav && onNav('clientes')}
       className="dash-pulse-card">
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)' }}>CLIENTES</div>
        <div className="font-display" style={{ fontSize: 26, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>3</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>conversas activas</div>
      </div>
      <Donut value={1} max={3} color="var(--danger)" label="1" />
    </div>
    <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5, borderTop: '1px solid var(--border-subtle)', paddingTop: 8 }}>
      <strong style={{ color: 'var(--danger)' }}>1 urgente</strong> · Olimpo aguarda há 14h
    </div>
  </div>
);

const DashPulseCarteira = ({ onNav }) => (
  <div onClick={() => onNav && onNav('carteira')}
       className="dash-pulse-card">
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)' }}>CARTEIRA</div>
        <div className="font-display" style={{ fontSize: 26, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>47</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>clientes activos</div>
      </div>
      <div style={{ display: 'flex', gap: 4, alignItems: 'flex-end', height: 40 }}>
        {[8, 12, 15, 10, 12, 14].map((v, i) => (
          <div key={i} style={{ width: 6, height: `${(v/15)*100}%`, background: i === 2 ? 'var(--accent)' : 'var(--border)', borderRadius: 1 }} />
        ))}
      </div>
    </div>
    <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5, borderTop: '1px solid var(--border-subtle)', paddingTop: 8, display: 'flex', gap: 14 }}>
      <span><strong style={{ color: 'var(--danger)' }}>8</strong> em risco</span>
      <span><strong style={{ color: 'var(--success)' }}>12</strong> recompra</span>
    </div>
  </div>
);

const DashPulseProspec = ({ onNav }) => (
  <div onClick={() => onNav && onNav('prospeccao')}
       className="dash-pulse-card">
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)' }}>PROSPECÇÃO ES</div>
        <div className="font-display" style={{ fontSize: 26, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>571</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>leads · 72 empresas</div>
      </div>
      <Donut value={124} max={571} color="var(--success)" stroke={4} label="124" />
    </div>
    <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5, borderTop: '1px solid var(--border-subtle)', paddingTop: 8, display: 'flex', gap: 14 }}>
      <span><strong style={{ color: 'var(--success)' }}>124</strong> quentes</span>
      <span><strong style={{ color: 'var(--text)' }}>8</strong> match Mimaki</span>
    </div>
  </div>
);

const DashPulseOPs = ({ onNav }) => (
  <div onClick={() => onNav && onNav('bp')}
       className="dash-pulse-card">
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
      <div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)' }}>OPs · PRIMAVERA</div>
        <div className="font-display" style={{ fontSize: 26, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>€1,73M</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>47 abertas</div>
      </div>
      <Sparkline values={[2138, 1518, 4031, 1732]} w={60} h={40} color="var(--warning)" />
    </div>
    <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5, borderTop: '1px solid var(--border-subtle)', paddingTop: 8, display: 'flex', gap: 14 }}>
      <span><strong style={{ color: 'var(--warning)' }}>12</strong> paradas &gt;30d</span>
      <span>conversão <strong style={{ color: 'var(--text)' }}>9,8%</strong></span>
    </div>
  </div>
);

const DashPulse = ({ onNav }) => (
  <div>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 10 }}>
      <h3 className="font-display" style={{ margin: 0, fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>Pulse</h3>
      <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>estado de cada secção · click para abrir</div>
    </div>
    <style>{`
      .dash-pulse-card {
        background: var(--bg-elev); border: 1px solid var(--border);
        border-radius: 10px; padding: 14px; cursor: pointer;
        transition: background 0.15s, border-color 0.15s;
      }
      .dash-pulse-card:hover { background: var(--bg-elev-2); border-color: var(--accent); }
    `}</style>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10 }}>
      <DashPulseClientes onNav={onNav} />
      <DashPulseCarteira onNav={onNav} />
      <DashPulseProspec onNav={onNav} />
      <DashPulseOPs onNav={onNav} />
    </div>
  </div>
);

// ============================================================================
// INPUT DIGI — pergunta proactiva
// ============================================================================
const DashDigiInput = ({ onOpenChat }) => {
  const chips = [
    'Quem devo ligar hoje?',
    'Mostra OPs paradas',
    'Simula UJF-7151 p/ Olimpo',
    'Leads quentes em Barcelona',
  ];
  return (
    <div style={{
      background: 'var(--bg-elev)', border: '1px solid var(--border)',
      borderRadius: 12, padding: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <span className="ai-chip"><span className="ai-dot" />Digi</span>
        <div style={{ fontSize: 12.5, color: 'var(--text-muted)' }}>
          Pergunta-me o que quiseres sobre carteira, leads, OPs, simulações…
        </div>
      </div>
      <div onClick={() => onOpenChat && onOpenChat()}
           style={{
             background: 'var(--bg)', border: '1px solid var(--border)', borderRadius: 8,
             padding: '10px 14px', cursor: 'text',
             display: 'flex', alignItems: 'center', gap: 10,
             fontSize: 13, color: 'var(--text-dim)',
           }}>
        <span style={{ color: 'var(--text-muted)' }}>Pergunta à Digi…</span>
        <span style={{ marginLeft: 'auto', fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)', background: 'var(--bg-elev)', padding: '2px 6px', borderRadius: 4, border: '1px solid var(--border)' }}>⌘ K</span>
      </div>
      <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
        {chips.map((c, i) => (
          <button key={i} onClick={() => onOpenChat && onOpenChat(c)}
                  style={{
                    background: 'var(--bg)', border: '1px solid var(--border)',
                    borderRadius: 999, padding: '5px 11px',
                    fontSize: 11, color: 'var(--text-muted)', cursor: 'pointer',
                    transition: 'all 0.15s',
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.color = 'var(--text)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.color = 'var(--text-muted)'; }}
          >
            {c}
          </button>
        ))}
      </div>
    </div>
  );
};

// ============================================================================
// SCREEN
// ============================================================================
const ScreenComercialDashboard = ({ onOpenChat, onNav }) => {
  return (
    <div className="scrollbar" style={{ height: '100%', overflow: 'auto', background: 'var(--bg)' }}>
      <div style={{ padding: '24px 28px 60px', maxWidth: 1360, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 24 }}>
        <DashHero />
        <DashBPCard onNav={onNav} />
        <DashAccoes onNav={onNav} />
        <DashPulse onNav={onNav} />
        <DashDigiInput onOpenChat={onOpenChat} />
      </div>
    </div>
  );
};

window.ScreenComercialDashboard = ScreenComercialDashboard;
