const { useState } = React;

// ─── Health Barometer ────────────────────────────────────────────────────────
function HealthBarometer({ spi, cpi, physReal, physPlan }) {
  const score = ((spi + cpi) / 2 + physReal / physPlan) / 2;
  const status = score >= 0.97 ? 'ok' : score >= 0.92 ? 'at_risk' : 'delayed';
  const color  = statusColor(status);
  const label  = score >= 0.97 ? 'SAUDÁVEL' : score >= 0.92 ? 'EM RISCO' : 'CRÍTICO';

  // Circular gauge via SVG
  const r = 48, cx = 70, cy = 70, circ = 2 * Math.PI * r;
  const filled = Math.min(score, 1) * circ;

  return (
    <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', height:'100%', gap:6 }}>
      <svg width={140} height={140} viewBox="0 0 140 140">
        <circle cx={cx} cy={cy} r={r} fill="none" stroke={C.borderSub} strokeWidth={10} />
        <circle cx={cx} cy={cy} r={r} fill="none" stroke={color} strokeWidth={10}
          strokeDasharray={`${filled} ${circ}`}
          strokeLinecap="round" strokeDashoffset={circ * 0.25}
          transform="rotate(-90 70 70)" />
        <text x={cx} y={cy - 6}  textAnchor="middle" fontSize={22} fontWeight="800" fill={color} fontFamily="IBM Plex Sans, sans-serif">{Math.round(score * 100)}%</text>
        <text x={cx} y={cy + 12} textAnchor="middle" fontSize={9}  fontWeight="700" fill={color} fontFamily="IBM Plex Sans, sans-serif" letterSpacing="1">{label}</text>
        <text x={cx} y={cy + 26} textAnchor="middle" fontSize={8}  fill={C.textSub} fontFamily="IBM Plex Sans, sans-serif">ÍNDICE GERAL</text>
      </svg>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:4, width:130 }}>
        {[{l:'SPI',v:spi},{l:'CPI',v:cpi},{l:'Físico',v:`${physReal}%`},{l:'Plano',v:`${physPlan}%`}].map(({l,v}) => (
          <div key={l} style={{ background:C.borderSub, borderRadius:4, padding:'4px 6px', textAlign:'center' }}>
            <div style={{ fontSize:9, color:C.textSub, fontWeight:600, letterSpacing:0.3 }}>{l}</div>
            <div style={{ fontSize:13, fontWeight:700, color:C.text }}>{typeof v === 'number' ? v.toFixed(2) : v}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Milestone Row ───────────────────────────────────────────────────────────
function MilestoneRow({ m }) {
  const col = statusColor(m.status);
  const bg  = m.status === 'critical' ? '#FFF5F5' : m.status === 'at_risk' ? '#FFFBEB' : '#F0FDF4';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:8, padding:'7px 10px', background:bg, borderRadius:5, marginBottom:5, border:`1px solid ${col}22` }}>
      <div style={{ minWidth:34, height:34, borderRadius:5, background:col, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', color:'#fff' }}>
        <div style={{ fontSize:13, fontWeight:800, lineHeight:1 }}>{m.days}</div>
        <div style={{ fontSize:7.5, fontWeight:600, letterSpacing:0.5 }}>DIAS</div>
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:11.5, fontWeight:600, color:C.text, lineHeight:1.3, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{m.name}</div>
        <div style={{ fontSize:10, color:C.textSub }}>{m.id} · {m.date}</div>
      </div>
      <div style={{ fontSize:9.5, color:col, fontWeight:700, whiteSpace:'nowrap' }}>{statusLabel(m.status).replace('⚠ ','').replace('✓ ','')}</div>
    </div>
  );
}

// ─── Screen 1: Dashboard Principal ──────────────────────────────────────────
function Screen1Dashboard() {
  const D = window.SIGP_DATA;
  const { evm, project, phases, disciplines, milestones, curvaSData } = D;

  return (
    <ScreenShell
      title="Dashboard Principal — Visão Executiva"
      subtitle="SPG · Semana 8 · Comparativo planejado × realizado × forecast"
    >
      {/* ── Row 1: KPI Cards ── */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:10, marginBottom:14 }}>
        <KPICard label="SPI" value={evm.SPI.toFixed(2)} sub="Índice Desempenho Prazo" status="at_risk" delta={`Desvio: ${fmtBRL(evm.SV)}`} />
        <KPICard label="CPI" value={evm.CPI.toFixed(2)} sub="Índice Desempenho Custo" status="at_risk" delta={`CV: ${fmtBRL(evm.CV)}`} />
        <div style={{ background:C.card, borderRadius:8, border:`1px solid ${C.border}`, padding:'12px 14px' }}>
          <div style={{ fontSize:10.5, color:C.textSub, fontWeight:500, letterSpacing:0.3, textTransform:'uppercase', marginBottom:4 }}>Avanço Físico</div>
          <div style={{ display:'flex', alignItems:'baseline', gap:6 }}>
            <span style={{ fontSize:22, fontWeight:800, color:C.danger }}>37,4%</span>
            <span style={{ fontSize:12, color:C.textSub }}>real</span>
          </div>
          <div style={{ marginTop:4 }}>
            <DualBar planned={41.2} real={37.4} status="delayed" showValues={false} />
          </div>
          <div style={{ fontSize:10.5, color:C.textSub, marginTop:2 }}>Planejado: 41,2% · Δ −3,8pp</div>
        </div>
        <div style={{ background:C.card, borderRadius:8, border:`1px solid ${C.border}`, padding:'12px 14px' }}>
          <div style={{ fontSize:10.5, color:C.textSub, fontWeight:500, letterSpacing:0.3, textTransform:'uppercase', marginBottom:2 }}>Conclusão Prevista</div>
          <div style={{ fontSize:19, fontWeight:800, color:C.warning }}>mar/2027</div>
          <div style={{ fontSize:10.5, color:C.textSub }}>Baseline: jan/2027</div>
          <div style={{ marginTop:4, display:'flex', alignItems:'center', gap:5 }}>
            <span style={{ fontSize:10, color:C.danger, fontWeight:700, background:'#FEE2E2', padding:'1px 6px', borderRadius:3 }}>+45 dias de desvio</span>
          </div>
        </div>
        <div style={{ background:C.card, borderRadius:8, border:`1px solid ${C.border}`, padding:'12px 14px' }}>
          <div style={{ fontSize:10.5, color:C.textSub, fontWeight:500, letterSpacing:0.3, textTransform:'uppercase', marginBottom:2 }}>Contingência</div>
          <div style={{ fontSize:19, fontWeight:800, color:C.success }}>{fmtBRL(project.contingencyRemaining)}</div>
          <div style={{ fontSize:10.5, color:C.textSub }}>de {fmtBRL(project.contingencyOriginal)}</div>
          <div style={{ marginTop:5 }}>
            <div style={{ height:5, background:C.borderSub, borderRadius:3, overflow:'hidden' }}>
              <div style={{ height:'100%', width:`${(project.contingencyRemaining/project.contingencyOriginal)*100}%`, background:C.success, borderRadius:3 }} />
            </div>
          </div>
          <div style={{ fontSize:10, color:C.textSub, marginTop:2 }}>{Math.round((project.contingencyRemaining/project.contingencyOriginal)*100)}% disponível</div>
        </div>
      </div>

      {/* ── Row 2: Curva S + Barômetro + Marcos ── */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 160px 240px', gap:10, marginBottom:14 }}>
        <Card title="Curva S — Avanço Acumulado" subtitle="Planejado × Realizado × Forecast IA · Semanas 0–43" noPad>
          <div style={{ padding:'10px 6px 6px' }}>
            <CurvaS data={curvaSData} height={230} />
          </div>
        </Card>

        <Card title="Barômetro" subtitle="Saúde geral" noPad>
          <div style={{ padding:8, height:260, display:'flex', alignItems:'stretch' }}>
            <HealthBarometer spi={evm.SPI} cpi={evm.CPI} physReal={evm.physicalReal} physPlan={evm.physicalPlanned} />
          </div>
        </Card>

        <Card title="Próximos Marcos" subtitle="30 dias · semáforo de urgência" noPad>
          <div style={{ padding:'8px 8px 4px' }}>
            {milestones.map(m => <MilestoneRow key={m.id} m={m} />)}
          </div>
        </Card>
      </div>

      {/* ── Row 3: Fases + Disciplinas ── */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
        <Card title="Progresso por Fase" subtitle="Barras duplas: planejado (claro) × realizado (cor)">
          {phases.map(p => (
            <div key={p.id} style={{ marginBottom:12 }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:5 }}>
                <div>
                  <span style={{ fontSize:12, fontWeight:600, color:C.text }}>{p.name}</span>
                </div>
                <Badge label={statusLabel(p.status)} variant={p.status==='complete'?'success':p.status==='delayed'?'danger':p.status==='upcoming'?'primary':'warning'} small />
              </div>
              <DualBar planned={p.planned} real={p.real} status={p.status} />
            </div>
          ))}
        </Card>

        <Card title="Progresso por Disciplina" subtitle="Barras duplas: planejado (claro) × realizado (cor)">
          {disciplines.map(d => (
            <div key={d.name}>
              <DualBar planned={d.planned} real={d.real} status={d.status} label={d.name} />
            </div>
          ))}
          <div style={{ marginTop:14, padding:'10px', background:'#FFF5F5', borderRadius:6, border:`1px solid #FECACA` }}>
            <div style={{ fontSize:11, color:C.danger, fontWeight:700, marginBottom:4 }}>⚠ Disciplinas em desvio crítico</div>
            <div style={{ fontSize:10.5, color:C.textSub, lineHeight:1.6 }}>
              <strong style={{ color:C.text }}>Civil:</strong> −9pp vs plano · solo expansivo e produtividade abaixo do previsto<br />
              <strong style={{ color:C.text }}>Mecânica:</strong> −13pp vs plano · aguardando PO caldeira e destilador (lead time crítico)
            </div>
          </div>
        </Card>
      </div>
    </ScreenShell>
  );
}

Object.assign(window, { Screen1Dashboard });
