const { useState } = React;

// ─── EVM metric card ─────────────────────────────────────────────────────────
function EVMCard({ code, label, value, fmt, status, tooltip }) {
  const col = statusColor(status);
  return (
    <div style={{ background:C.card, border:`1px solid ${status ? col+'55' : C.border}`, borderTop:`3px solid ${col || C.border}`, borderRadius:7, padding:'10px 12px', display:'flex', flexDirection:'column', gap:2 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <span style={{ fontSize:10, fontWeight:700, color:C.textSub, letterSpacing:0.8, textTransform:'uppercase' }}>{code}</span>
        {status && <span style={{ width:7, height:7, borderRadius:'50%', background:col, display:'inline-block' }} />}
      </div>
      <div style={{ fontSize:18, fontWeight:800, color:col || C.text, fontFamily:'IBM Plex Mono, monospace', letterSpacing:-0.5 }}>{fmt ? fmt(value) : value}</div>
      <div style={{ fontSize:10.5, color:C.textSub, lineHeight:1.3 }}>{label}</div>
    </div>
  );
}

// ─── Trend mini chart ─────────────────────────────────────────────────────────
function TrendChart({ data, h = 120 }) {
  const W = 480;
  const pad = { t:10, r:10, b:28, l:40 };
  const cW = W - pad.l - pad.r, cH = h - pad.t - pad.b;

  const allVals = data.flatMap(d => [d.cpi, d.spi]);
  const minV = Math.min(...allVals) - 0.02, maxV = Math.max(...allVals) + 0.02;
  const xf = i => (i / (data.length - 1)) * cW;
  const yf = v => cH - ((v - minV) / (maxV - minV)) * cH;

  const makeLine = key => data.map((d,i) => `${i===0?'M':'L'}${xf(i).toFixed(1)},${yf(d[key]).toFixed(1)}`).join(' ');

  // 1.0 reference line
  const y1 = yf(1.0);

  return (
    <svg viewBox={`0 0 ${W} ${h}`} width="100%" height={h}>
      <g transform={`translate(${pad.l},${pad.t})`}>
        {/* Reference line at 1.0 */}
        <line x1={0} y1={y1} x2={cW} y2={y1} stroke="#E2E8F0" strokeWidth={1} strokeDasharray="4,3" />
        <text x={-6} y={y1+4} textAnchor="end" fontSize={9} fill="#94A3B8" fontFamily="IBM Plex Mono, monospace">1,00</text>
        {/* 0.9 reference */}
        <line x1={0} y1={yf(0.9)} x2={cW} y2={yf(0.9)} stroke="#FECACA" strokeWidth={1} strokeDasharray="3,3" />
        <text x={-6} y={yf(0.9)+4} textAnchor="end" fontSize={9} fill="#94A3B8" fontFamily="IBM Plex Mono, monospace">0,90</text>
        {/* Grid */}
        {data.map((d,i) => (
          <g key={i}>
            <line x1={xf(i)} y1={0} x2={xf(i)} y2={cH} stroke="#F1F5F9" strokeWidth={1} />
            <text x={xf(i)} y={cH+16} textAnchor="middle" fontSize={9} fill="#94A3B8" fontFamily="IBM Plex Mono, monospace">{d.label}</text>
          </g>
        ))}
        {/* Lines */}
        <path d={makeLine('cpi')} fill="none" stroke={C.success}  strokeWidth={2.5} strokeLinejoin="round" />
        <path d={makeLine('spi')} fill="none" stroke={C.warning}  strokeWidth={2.5} strokeLinejoin="round" />
        {data.map((d,i) => (
          <g key={i}>
            <circle cx={xf(i)} cy={yf(d.cpi)} r={3} fill={C.success} stroke="white" strokeWidth={1} />
            <circle cx={xf(i)} cy={yf(d.spi)} r={3} fill={C.warning} stroke="white" strokeWidth={1} />
          </g>
        ))}
      </g>
      {/* Legend */}
      <g transform={`translate(${pad.l + 10},${h-2})`}>
        <line x1={0} y1={0} x2={16} y2={0} stroke={C.success} strokeWidth={2.5} />
        <text x={20} y={3.5} fontSize={9.5} fill={C.textSub} fontFamily="IBM Plex Sans, sans-serif">CPI</text>
        <line x1={50} y1={0} x2={66} y2={0} stroke={C.warning} strokeWidth={2.5} />
        <text x={70} y={3.5} fontSize={9.5} fill={C.textSub} fontFamily="IBM Plex Sans, sans-serif">SPI</text>
      </g>
    </svg>
  );
}

// ─── Budget commitment bars ──────────────────────────────────────────────────
function CommitmentBar({ label, budgeted, contracted, realized, total }) {
  const pBudg = (budgeted    / total) * 100;
  const pCont = (contracted  / total) * 100;
  const pReal = (realized    / total) * 100;
  return (
    <div style={{ marginBottom:12 }}>
      <div style={{ display:'flex', justifyContent:'space-between', marginBottom:4 }}>
        <span style={{ fontSize:11.5, color:C.text, fontWeight:500 }}>{label}</span>
        <span style={{ fontSize:10.5, color:C.textSub, fontFamily:'IBM Plex Mono, monospace' }}>{fmtBRL(realized)} / {fmtBRL(budgeted)}</span>
      </div>
      <div style={{ position:'relative', height:20, background:'#F1F5F9', borderRadius:5 }}>
        <div style={{ position:'absolute', top:0, left:0, width:`${pBudg}%`, height:'100%', background:'#CBD5E1', borderRadius:5 }} />
        <div style={{ position:'absolute', top:3, left:0, width:`${pCont}%`, height:14, background:`${C.primary}88`, borderRadius:4 }} />
        <div style={{ position:'absolute', top:5, left:0, width:`${pReal}%`, height:10, background:C.primary, borderRadius:3 }} />
      </div>
      <div style={{ display:'flex', gap:12, marginTop:3, fontSize:10 }}>
        <span style={{ color:'#94A3B8' }}>□ Orçado: {fmtBRL(budgeted)}</span>
        <span style={{ color:`${C.primary}99` }}>□ Contratado: {fmtBRL(contracted)}</span>
        <span style={{ color:C.primary }}>■ Realizado: {fmtBRL(realized)}</span>
      </div>
    </div>
  );
}

// ─── Screen 4: Dashboard de Custos (EVM) ────────────────────────────────────
function Screen4Custos() {
  const { evm, wbsDeviations, cpiSpiTrend, currencyExposure } = window.SIGP_DATA;
  const [showAlert, setShowAlert] = useState(true);

  const evmCards = [
    { code:'PV',   label:'Valor Planejado',         value: evm.PV,   fmt: v => fmtBRL(v),          status: null },
    { code:'EV',   label:'Valor Agregado',           value: evm.EV,   fmt: v => fmtBRL(v),          status: null },
    { code:'AC',   label:'Custo Real',               value: evm.AC,   fmt: v => fmtBRL(v),          status: null },
    { code:'SV',   label:'Variação de Prazo',        value: evm.SV,   fmt: v => fmtBRL(v),          status: evm.SV < 0 ? 'delayed' : 'ok' },
    { code:'CV',   label:'Variação de Custo',        value: evm.CV,   fmt: v => fmtBRL(v),          status: evm.CV < 0 ? 'at_risk' : 'ok' },
    { code:'SPI',  label:'Índice Desempenho Prazo',  value: evm.SPI,  fmt: v => v.toFixed(3),       status: evm.SPI < 0.9 ? 'delayed' : evm.SPI < 1 ? 'at_risk' : 'ok' },
    { code:'CPI',  label:'Índice Desempenho Custo',  value: evm.CPI,  fmt: v => v.toFixed(3),       status: evm.CPI < 0.9 ? 'delayed' : evm.CPI < 1 ? 'at_risk' : 'ok' },
    { code:'EAC',  label:'Estimativa no Término',    value: evm.EAC,  fmt: v => fmtBRL(v),          status: evm.EAC > evm.BAC ? 'at_risk' : 'ok' },
    { code:'ETC',  label:'Estimativa para Concluir', value: evm.ETC,  fmt: v => fmtBRL(v),          status: null },
    { code:'TCPI', label:'Índice Desempenho Necessário', value:evm.TCPI, fmt: v => v.toFixed(3),   status: evm.TCPI > 1.1 ? 'delayed' : evm.TCPI > 1 ? 'at_risk' : 'ok' },
  ];

  return (
    <ScreenShell
      title="Dashboard de Alertas de Desvios de Custos"
      subtitle="EVM · Earned Value Management completo — Semana 8 · BAC: R$ 234M"
    >
      {/* ── Alert FN-06 ── */}
      {showAlert && (
        <div style={{ padding:'9px 14px', background:'#FFF5F5', border:`1px solid ${C.danger}66`, borderRadius:7, marginBottom:14, display:'flex', gap:10, alignItems:'center' }}>
          <span style={{ fontSize:16 }}>📋</span>
          <div style={{ flex:1 }}>
            <strong style={{ color:C.danger, fontSize:12 }}>Ação Requerida — Formulário FN-06</strong>
            <span style={{ color:C.text, fontSize:11.5, marginLeft:8 }}>3 pacotes de trabalho com desvio &gt;5% ou &gt;R$100k aguardando Análise de Causa Raiz: WBS 1.1 (terraplenagem), WBS 1.2 (fundações), WBS 2.1 (equipamentos)</span>
          </div>
          <Btn variant="danger" small onClick={() => setShowAlert(false)}>Preencher FN-06</Btn>
        </div>
      )}

      {/* ── EVM Cards ── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:8, marginBottom:14 }}>
        {evmCards.map(c => <EVMCard key={c.code} {...c} />)}
      </div>

      {/* ── Gauges + Trend chart ── */}
      <div style={{ display:'grid', gridTemplateColumns:'160px 160px 1fr', gap:10, marginBottom:14 }}>
        <Card title="CPI" subtitle="Cost Performance Index" noPad>
          <div style={{ padding:'10px 0 4px', display:'flex', justifyContent:'center' }}>
            <Gauge value={evm.CPI} max={1.5} warnAt={1.0} dangerAt={0.9} label="CPI · meta ≥ 1,00" size={140} />
          </div>
        </Card>
        <Card title="SPI" subtitle="Schedule Performance Index" noPad>
          <div style={{ padding:'10px 0 4px', display:'flex', justifyContent:'center' }}>
            <Gauge value={evm.SPI} max={1.5} warnAt={1.0} dangerAt={0.9} label="SPI · meta ≥ 1,00" size={140} />
          </div>
        </Card>
        <Card title="Tendência CPI / SPI" subtitle="Últimas 6 semanas de medição">
          <TrendChart data={cpiSpiTrend} h={120} />
        </Card>
      </div>

      {/* ── WBS Deviations ── */}
      <Card title="Desvios por Pacote de Trabalho (WBS)" subtitle="Orçado × Realizado — desvios >5% ou >R$100k exigem análise de causa raiz (FN-06)" noPad style={{ marginBottom:14 }}>
        <Table>
          <thead>
            <tr>
              <Th>WBS</Th>
              <Th>Pacote de Trabalho</Th>
              <Th style={{ textAlign:'right' }}>Orçado</Th>
              <Th style={{ textAlign:'right' }}>Realizado</Th>
              <Th style={{ textAlign:'right' }}>Desvio R$</Th>
              <Th style={{ textAlign:'right' }}>Desvio %</Th>
              <Th>Status</Th>
              <Th>Análise de Causa</Th>
            </tr>
          </thead>
          <tbody>
            {wbsDeviations.map((row, i) => {
              const needsAction = Math.abs(row.pct) >= 5 && row.deviation !== 0;
              const isTotal = row.wbs === 'TOTAL';
              return (
                <tr key={row.wbs} style={{ background: isTotal ? '#F0F6FF' : needsAction ? `${statusColor(row.status)}0A` : i%2===0?'#FAFBFC':C.card, fontWeight: isTotal ? 700 : 400 }}>
                  <Td><span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11 }}>{row.wbs}</span></Td>
                  <Td><span style={{ fontWeight: isTotal ? 700 : 500, color:C.text }}>{row.name}</span></Td>
                  <Td style={{ textAlign:'right', fontFamily:'IBM Plex Mono, monospace', fontSize:11 }}>{fmtBRL(row.budgeted)}</Td>
                  <Td style={{ textAlign:'right', fontFamily:'IBM Plex Mono, monospace', fontSize:11 }}>{row.actual > 0 ? fmtBRL(row.actual) : '—'}</Td>
                  <Td style={{ textAlign:'right' }}>
                    {row.deviation !== 0 && (
                      <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, fontWeight:700, color: statusColor(row.status) }}>
                        {row.deviation > 0 ? '+' : ''}{fmtBRL(Math.abs(row.deviation))}
                      </span>
                    )}
                  </Td>
                  <Td style={{ textAlign:'right' }}>
                    {row.pct !== 0 && (
                      <span style={{ fontWeight:700, fontSize:11.5, color: statusColor(row.status) }}>
                        {row.pct > 0 ? '+' : ''}{row.pct.toFixed(1)}%
                      </span>
                    )}
                  </Td>
                  <Td>
                    {row.status !== 'pending' && <Badge label={statusLabel(row.status)} variant={row.status==='over'?'danger':row.status==='under'?'success':'default'} small />}
                    {row.status === 'pending' && <span style={{ fontSize:10.5, color:C.textSub }}>Não iniciado</span>}
                  </Td>
                  <Td style={{ fontSize:11, color: needsAction ? C.danger : C.textSub }}>
                    {row.cause ? <><span style={{ color:C.danger, fontWeight:700 }}>⚠ FN-06 pendente · </span>{row.cause}</> : row.status === 'pending' ? '—' : 'Dentro do esperado'}
                  </Td>
                </tr>
              );
            })}
          </tbody>
        </Table>
      </Card>

      {/* ── Row: Commitment + Currency ── */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
        <Card title="Comprometimento Orçamentário por Categoria">
          <CommitmentBar label="Civil e Fundações"      budgeted={54600000} contracted={48200000} realized={40740000} total={234000000} />
          <CommitmentBar label="Equipamentos e Processo" budgeted={64000000} contracted={46200000} realized={44200000} total={234000000} />
          <CommitmentBar label="Elétrica e I&C"         budgeted={15200000} contracted={9200000}  realized={9200000}  total={234000000} />
          <CommitmentBar label="Gestão e PMO"           budgeted={5200000}  contracted={5480000}  realized={5480000}  total={234000000} />
          <div style={{ borderTop:`1px solid ${C.borderSub}`, paddingTop:10, marginTop:4, fontSize:11, color:C.textSub }}>
            <span style={{ color:C.text, fontWeight:600 }}>Total contratado: {fmtBRL(109080000)}</span> · Realizado: {fmtBRL(evm.AC)} · Saldo BAC: {fmtBRL(evm.BAC - evm.AC)}
          </div>
        </Card>

        <Card title="Exposição Cambial" subtitle="Contratos indexados em moeda estrangeira">
          <table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>
            <thead>
              <tr style={{ background:'#F8FAFC' }}>
                <Th>Moeda</Th>
                <Th style={{ textAlign:'right' }}>Valor Contratado</Th>
                <Th>Taxa Base</Th>
                <Th>Taxa Atual</Th>
                <Th>Variação</Th>
                <Th>Hedge</Th>
              </tr>
            </thead>
            <tbody>
              {currencyExposure.map((cx, i) => (
                <tr key={cx.currency} style={{ background: i%2===0 ? '#FAFBFC' : C.card }}>
                  <Td><strong style={{ fontFamily:'IBM Plex Mono, monospace', color:C.primary }}>{cx.currency}</strong></Td>
                  <Td style={{ textAlign:'right', fontFamily:'IBM Plex Mono, monospace', fontSize:11 }}>{fmtBRL(cx.contracted)}</Td>
                  <Td style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11 }}>{cx.baseRate.toFixed(2)}</Td>
                  <Td style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, color:C.warning, fontWeight:700 }}>{cx.currentRate.toFixed(2)}</Td>
                  <Td><span style={{ color:C.danger, fontWeight:700 }}>+{cx.variation.toFixed(1)}%</span></Td>
                  <Td>
                    <Badge label={cx.hedgeStatus} variant={cx.hedgeStatus === 'Sem hedge' ? 'danger' : 'warning'} small />
                  </Td>
                </tr>
              ))}
            </tbody>
          </table>
          <div style={{ marginTop:12, padding:'8px 10px', background:'#FFF5F5', borderRadius:5, border:`1px solid #FECACA`, fontSize:11, color:C.danger }}>
            <strong>⚠ Exposição líquida sem cobertura: R$ 2,8M (EUR)</strong> — Risco de impacto de R$+420k no EAC caso EUR/BRL atinja 6,60.
          </div>
          <div style={{ marginTop:8, padding:'8px 10px', background:'#FFF5F5', borderRadius:5, border:`1px solid #FECACA`, fontSize:11, color:C.danger }}>
            <strong>⚠ Hedge parcial USD (60%):</strong> R$+1,2M de exposição adicional — encaminhar para aprovação CFO.
          </div>
        </Card>
      </div>
    </ScreenShell>
  );
}

Object.assign(window, { Screen4Custos });
