const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─── Color system ────────────────────────────────────────────────────────────
const C = {
  primary:   '#185FA5',
  success:   '#1D9E75',
  warning:   '#EF9F27',
  danger:    '#E24B4A',
  bg:        '#F0F2F5',
  sidebar:   '#0D1F35',
  sideText:  '#A8BDD4',
  card:      '#FFFFFF',
  text:      '#1A2332',
  textSub:   '#64748B',
  border:    '#E2E8F0',
  borderSub: '#F1F5F9',
};

// ─── Utilities ───────────────────────────────────────────────────────────────
function fmtBRL(val, compact = true) {
  if (val === null || val === undefined) return '—';
  const abs = Math.abs(val);
  const sign = val < 0 ? '-' : '';
  if (compact) {
    if (abs >= 1e9) return `${sign}R$ ${(abs/1e9).toFixed(1).replace('.',',')}B`;
    if (abs >= 1e6) return `${sign}R$ ${(abs/1e6).toFixed(1).replace('.',',')}M`;
    if (abs >= 1e3) return `${sign}R$ ${(abs/1e3).toFixed(0)}k`;
    return `${sign}R$ ${abs.toFixed(0)}`;
  }
  return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(val);
}

function fmtPct(val, decimals = 1) {
  if (val === null || val === undefined) return '—';
  const s = val >= 0 ? '+' : '';
  return `${s}${val.toFixed(decimals)}%`;
}

function statusColor(status) {
  return ({
    complete: C.success, on_track: C.success, ok: C.success,
    at_risk:  C.warning, warning:  C.warning,
    delayed:  C.danger,  critical: C.danger,
    upcoming: C.primary,
    pending:  C.textSub,
    over:     C.danger,  under: C.success,
  })[status] || C.textSub;
}

function statusLabel(status) {
  return ({
    complete: '✓ Concluído', on_track: '✓ Alinhado', ok: '✓ OK',
    at_risk:  '⚠ Em risco', warning: '⚠ Atenção',
    delayed:  '⏴ Atrasado', critical: '⚠ Crítico',
    upcoming: '○ Previsto',
    pending:  '○ Pendente',
    over:     '▲ Acima',    under: '▼ Abaixo',
  })[status] || status;
}

// ─── Sidebar ─────────────────────────────────────────────────────────────────
function Sidebar({ active, onNav }) {
  const items = [
    { id: 1, code: 'SPG', icon: '▦', label: 'Dashboard Executivo'    },
    { id: 2, code: 'IAP', icon: '◈', label: 'Dashboard IA Preditivo' },
    { id: 3, code: 'AUT', icon: '◉', label: 'Autorizações de Pedidos'},
    { id: 4, code: 'EVM', icon: '◑', label: 'Desvios de Custos'      },
    { id: 5, code: 'AMB', icon: '◎', label: 'Painel Ambiental LI'    },
    { id: 6, code: 'SUP', icon: '◐', label: 'Suprimentos / Lead Time'},
    { id: 7, code: 'RIS', icon: '◌', label: 'Gestão de Riscos'       },
    { id: 8, code: 'SED', icon: '◷', label: 'SED — Campo (Mobile)'   },
  ];

  return (
    <div style={{ width:240, minWidth:240, background:C.sidebar, display:'flex', flexDirection:'column', height:'100vh', position:'fixed', left:0, top:0, zIndex:100, fontFamily:'inherit' }}>
      {/* Header */}
      <div style={{ padding:'18px 16px 14px', borderBottom:`1px solid rgba(255,255,255,0.07)` }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:10 }}>
          <div style={{ width:34, height:34, background:C.primary, borderRadius:7, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, color:'#fff', fontSize:13, letterSpacing:-0.5 }}>DP</div>
          <div>
            <div style={{ color:'#fff', fontWeight:700, fontSize:13, lineHeight:1.2, letterSpacing:-0.2 }}>SIGP</div>
            <div style={{ color:C.sideText, fontSize:10.5 }}>Destilaria Pioneira</div>
          </div>
        </div>
        <div style={{ padding:'6px 10px', background:'rgba(239,159,39,0.12)', borderRadius:5, border:'1px solid rgba(239,159,39,0.25)' }}>
          <div style={{ color:C.warning, fontSize:10, fontWeight:700, letterSpacing:0.3 }}>⚠ CONDICIONANTE CRÍTICA</div>
          <div style={{ color:'rgba(168,189,212,0.85)', fontSize:10, marginTop:1 }}>PGR → IMASUL amanhã 24/05</div>
        </div>
      </div>

      {/* Nav */}
      <nav style={{ flex:1, padding:'6px 0', overflowY:'auto' }}>
        {items.map(it => {
          const isActive = active === it.id;
          return (
            <button key={it.id} onClick={() => onNav(it.id)} style={{
              width:'100%', display:'flex', alignItems:'center', gap:10,
              padding:'9px 16px 9px 12px',
              background: isActive ? 'rgba(24,95,165,0.22)' : 'transparent',
              borderLeft: isActive ? `3px solid ${C.primary}` : '3px solid transparent',
              border:'none', borderRadius:0, cursor:'pointer', textAlign:'left',
              transition:'background 0.12s',
            }}
            onMouseEnter={e => { if (!isActive) e.currentTarget.style.background='rgba(255,255,255,0.04)'; }}
            onMouseLeave={e => { if (!isActive) e.currentTarget.style.background='transparent'; }}
            >
              <span style={{ color: isActive ? C.primary : 'rgba(168,189,212,0.55)', fontSize:13 }}>{it.icon}</span>
              <div>
                <div style={{ color: isActive ? '#fff' : C.sideText, fontSize:12, fontWeight: isActive ? 600 : 400, lineHeight:1.3 }}>{it.label}</div>
                <div style={{ color:'rgba(168,189,212,0.35)', fontSize:9.5, fontWeight:500, letterSpacing:0.5 }}>{it.code}</div>
              </div>
            </button>
          );
        })}
      </nav>

      {/* Footer */}
      <div style={{ padding:'10px 16px', borderTop:'1px solid rgba(255,255,255,0.07)' }}>
        <div style={{ fontSize:10, color:'rgba(168,189,212,0.4)', lineHeight:1.7 }}>
          <div>v1.0.0 · Semana 8 · 23/05/2026</div>
          <div>LI Nº 000977/2022 · IMASUL/MS</div>
        </div>
      </div>
    </div>
  );
}

// ─── TopBar ──────────────────────────────────────────────────────────────────
function TopBar({ evm, project }) {
  const spiColor = evm.SPI >= 1 ? C.success : evm.SPI >= 0.9 ? C.warning : C.danger;
  const cpiColor = evm.CPI >= 1 ? C.success : evm.CPI >= 0.9 ? C.warning : C.danger;
  const devDays  = 45; // dias de desvio no forecast

  const metric = (label, value, color, sub) => (
    <div style={{ display:'flex', flexDirection:'column', alignItems:'center', padding:'0 16px', borderRight:'1px solid rgba(255,255,255,0.12)' }}>
      <span style={{ fontSize:9.5, color:'rgba(255,255,255,0.55)', letterSpacing:0.5, textTransform:'uppercase', marginBottom:1 }}>{label}</span>
      <span style={{ fontSize:16, fontWeight:700, color: color || '#fff', lineHeight:1.1 }}>{value}</span>
      {sub && <span style={{ fontSize:9, color:'rgba(255,255,255,0.4)', marginTop:1 }}>{sub}</span>}
    </div>
  );

  return (
    <div style={{ background:C.primary, display:'flex', alignItems:'center', height:52, paddingLeft:16, paddingRight:16, boxShadow:'0 2px 8px rgba(0,0,0,0.18)', flexShrink:0, gap:0 }}>
      <div style={{ marginRight:16, paddingRight:16, borderRight:'1px solid rgba(255,255,255,0.12)' }}>
        <div style={{ color:'rgba(255,255,255,0.6)', fontSize:10, letterSpacing:0.5 }}>DESTILARIA PIONEIRA</div>
        <div style={{ color:'#fff', fontSize:12, fontWeight:700 }}>SIGP · Implantação</div>
      </div>
      {metric('SPI', evm.SPI.toFixed(2), spiColor)}
      {metric('CPI', evm.CPI.toFixed(2), cpiColor)}
      {metric('Avanço Físico', `${evm.physicalReal}%`, C.warning, `Plano: ${evm.physicalPlanned}%`)}
      {metric('Forecast Conclusão', project.forecastEnd, C.warning, `Baseline: ${project.baselineEnd}`)}
      {metric('Saldo Contingência', fmtBRL(project.contingencyRemaining), '#fff', `de ${fmtBRL(project.contingencyOriginal)}`)}
      <div style={{ flex:1 }} />
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'0 12px', background:'rgba(226,75,74,0.2)', borderRadius:6, border:'1px solid rgba(226,75,74,0.4)' }}>
        <span style={{ color:C.danger, fontSize:13 }}>⚠</span>
        <span style={{ color:'#fff', fontSize:11, fontWeight:600 }}>Saúde: EM RISCO</span>
      </div>
      <div style={{ marginLeft:16, fontSize:11, color:'rgba(255,255,255,0.55)' }}>23/05/2026 · S08</div>
    </div>
  );
}

// ─── Card ────────────────────────────────────────────────────────────────────
function Card({ children, title, subtitle, headerRight, style, noPad }) {
  return (
    <div style={{ background:C.card, borderRadius:8, border:`1px solid ${C.border}`, overflow:'hidden', ...style }}>
      {title && (
        <div style={{ padding:'10px 14px', borderBottom:`1px solid ${C.borderSub}`, display:'flex', alignItems:'center', justifyContent:'space-between', gap:8 }}>
          <div>
            <div style={{ fontWeight:700, fontSize:12.5, color:C.text, letterSpacing:-0.1 }}>{title}</div>
            {subtitle && <div style={{ fontSize:10.5, color:C.textSub, marginTop:1 }}>{subtitle}</div>}
          </div>
          {headerRight}
        </div>
      )}
      <div style={noPad ? {} : { padding:14 }}>{children}</div>
    </div>
  );
}

// ─── Badge ───────────────────────────────────────────────────────────────────
function Badge({ label, variant = 'default', small }) {
  const map = {
    danger:   { bg:'#FEE2E2', color:C.danger,   border:'#FECACA' },
    success:  { bg:'#D1FAE5', color:'#065F46',   border:'#A7F3D0' },
    warning:  { bg:'#FEF3C7', color:'#92400E',   border:'#FDE68A' },
    primary:  { bg:'#DBEAFE', color:'#1E40AF',   border:'#BFDBFE' },
    default:  { bg:C.borderSub, color:C.textSub, border:C.border  },
  };
  const s = map[variant] || map.default;
  return (
    <span style={{ display:'inline-flex', alignItems:'center', padding: small ? '1px 6px' : '2px 8px', borderRadius:4, fontSize: small ? 10 : 11, fontWeight:600, background:s.bg, color:s.color, border:`1px solid ${s.border}`, whiteSpace:'nowrap' }}>
      {label}
    </span>
  );
}

// ─── KPI Card ────────────────────────────────────────────────────────────────
function KPICard({ label, value, sub, status, delta, style }) {
  const col = status ? statusColor(status) : C.text;
  return (
    <div style={{ background:C.card, borderRadius:8, border:`1px solid ${C.border}`, padding:'12px 14px', display:'flex', flexDirection:'column', gap:2, ...style }}>
      <div style={{ fontSize:10.5, color:C.textSub, fontWeight:500, letterSpacing:0.3, textTransform:'uppercase' }}>{label}</div>
      <div style={{ fontSize:22, fontWeight:800, color:col, lineHeight:1.1, letterSpacing:-0.5 }}>{value}</div>
      {sub   && <div style={{ fontSize:10.5, color:C.textSub }}>{sub}</div>}
      {delta && <div style={{ fontSize:10.5, color: delta.startsWith('+') ? C.danger : C.success, fontWeight:600 }}>{delta}</div>}
    </div>
  );
}

// ─── Dual Progress Bar ───────────────────────────────────────────────────────
function DualBar({ planned, real, status, label, showValues = true }) {
  const col = statusColor(status);
  return (
    <div style={{ marginBottom:10 }}>
      {label && (
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:4 }}>
          <span style={{ fontSize:11.5, color:C.text, fontWeight:500 }}>{label}</span>
          {showValues && (
            <span style={{ fontSize:11, color:C.textSub }}>
              <span style={{ color:col, fontWeight:700 }}>{real}%</span>
              <span style={{ color:C.border }}> / </span>
              <span>{planned}% plan</span>
            </span>
          )}
        </div>
      )}
      <div style={{ position:'relative', height:14, background:'#F1F5F9', borderRadius:4, overflow:'hidden' }}>
        {/* Planned */}
        <div style={{ position:'absolute', top:0, left:0, width:`${Math.min(100,planned)}%`, height:'100%', background:'#CBD5E1', borderRadius:4 }} />
        {/* Real */}
        <div style={{ position:'absolute', top:2, left:0, width:`${Math.min(100,real)}%`, height:10, background:col, borderRadius:3 }} />
      </div>
    </div>
  );
}

// ─── Gauge (Semicircle) ──────────────────────────────────────────────────────
function Gauge({ value, max = 1.5, warnAt = 1.0, dangerAt = 0.9, label, size = 150 }) {
  const W = size, H = size * 0.6;
  const cx = W / 2, cy = H;
  const r = H * 0.92;
  const trackW = size * 0.09;

  const pctOf = v => Math.min(0.999, Math.max(0.001, v / max));

  function ptOnArc(pct) {
    const angle = Math.PI - pct * Math.PI;
    return [cx + r * Math.cos(angle), cy - r * Math.sin(angle)];
  }

  function arcD(p1, p2) {
    const [x1, y1] = ptOnArc(Math.max(0.001, p1));
    const [x2, y2] = ptOnArc(Math.min(0.999, p2));
    const la = (p2 - p1) > 0.5 ? 1 : 0;
    return `M ${x1.toFixed(2)} ${y1.toFixed(2)} A ${r} ${r} 0 ${la} 0 ${x2.toFixed(2)} ${y2.toFixed(2)}`;
  }

  const pct = pctOf(value);
  const wPct = pctOf(dangerAt);
  const yPct = pctOf(warnAt);
  const color = value >= warnAt ? C.success : value >= dangerAt ? C.warning : C.danger;
  const [nx, ny] = ptOnArc(pct);

  return (
    <svg width={W} height={H + 4} viewBox={`0 0 ${W} ${H + 4}`} style={{ overflow:'visible' }}>
      {/* Zone track */}
      <path d={arcD(0, wPct)}  fill="none" stroke="#FECACA" strokeWidth={trackW} strokeLinecap="butt" />
      <path d={arcD(wPct, yPct)} fill="none" stroke="#FDE68A" strokeWidth={trackW} strokeLinecap="butt" />
      <path d={arcD(yPct, 1)}  fill="none" stroke="#A7F3D0" strokeWidth={trackW} strokeLinecap="butt" />
      {/* Value arc */}
      <path d={arcD(0, pct)}   fill="none" stroke={color}   strokeWidth={trackW * 0.45} strokeLinecap="round" />
      {/* Needle */}
      <line x1={cx} y1={cy} x2={nx.toFixed(2)} y2={ny.toFixed(2)} stroke={C.text} strokeWidth={1.8} strokeLinecap="round" />
      <circle cx={cx} cy={cy} r={4} fill={C.text} />
      {/* Ticks: 0.9, 1.0 */}
      {[dangerAt, warnAt].map(v => {
        const [tx, ty] = ptOnArc(pctOf(v));
        const [tx2, ty2] = ptOnArc(pctOf(v));
        return <circle key={v} cx={tx.toFixed(2)} cy={ty.toFixed(2)} r={2} fill="rgba(0,0,0,0.3)" />;
      })}
      {/* Value */}
      <text x={cx} y={cy - r * 0.38} textAnchor="middle" fontSize={size * 0.17} fontWeight="800" fill={color} fontFamily="IBM Plex Sans, sans-serif">{value.toFixed(2)}</text>
      {label && <text x={cx} y={H - 1} textAnchor="middle" fontSize={size * 0.08} fill={C.textSub} fontFamily="IBM Plex Sans, sans-serif">{label}</text>}
    </svg>
  );
}

// ─── Sparkline ───────────────────────────────────────────────────────────────
function Sparkline({ data, color = C.primary, w = 80, h = 28 }) {
  if (!data || data.length < 2) return <span style={{ width:w, display:'inline-block' }}>—</span>;
  const mn = Math.min(...data), mx = Math.max(...data);
  const range = mx - mn || 1;
  const xs = data.map((_, i) => (i / (data.length - 1)) * w);
  const ys = data.map(v => h - ((v - mn) / range) * (h - 4) - 2);
  const d = xs.map((x, i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${ys[i].toFixed(1)}`).join(' ');
  const trend = data[data.length-1] >= data[0];
  const col = color === 'auto' ? (trend ? C.success : C.danger) : color;

  return (
    <svg width={w} height={h} style={{ display:'block' }}>
      <path d={d} fill="none" stroke={col} strokeWidth={1.5} strokeLinejoin="round" />
      <circle cx={xs[xs.length-1]} cy={ys[ys.length-1]} r={2.5} fill={col} />
    </svg>
  );
}

// ─── Curva S Chart ───────────────────────────────────────────────────────────
function CurvaS({ data, height = 250 }) {
  const W = 580, H = height;
  const pad = { t:18, r:14, b:32, l:44 };
  const cW = W - pad.l - pad.r, cH = H - pad.t - pad.b;
  const MAX_WEEK = 43;

  const xf = w => (w / MAX_WEEK) * cW;
  const yf = p => cH - (p / 100) * cH;

  function makePath(pts, key) {
    const valid = pts.filter(d => d[key] != null);
    if (!valid.length) return '';
    return valid.map((d, i) => `${i===0?'M':'L'}${xf(d.week).toFixed(1)},${yf(d[key]).toFixed(1)}`).join(' ');
  }

  const plannedD  = makePath(data.filter(d => d.planned  != null), 'planned');
  const actualD   = makePath(data.filter(d => d.actual   != null), 'actual');
  const forecastD = makePath(data.filter(d => d.forecast != null), 'forecast');
  const todayX    = xf(8);

  // Fill under actual
  const actualFill = `${actualD} L${xf(8).toFixed(1)},${cH} L${xf(0)},${cH} Z`;

  const yTicks = [0, 25, 50, 75, 100];
  const xTicks = [0, 8, 16, 24, 32, 40];

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ display:'block' }}>
      <defs>
        <linearGradient id="actualFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%"   stopColor={C.success} stopOpacity="0.15" />
          <stop offset="100%" stopColor={C.success} stopOpacity="0.01" />
        </linearGradient>
      </defs>
      <g transform={`translate(${pad.l},${pad.t})`}>
        {/* Grid */}
        {yTicks.map(v => (
          <g key={v}>
            <line x1={0} y1={yf(v)} x2={cW} y2={yf(v)} stroke="#E2E8F0" strokeWidth={v===0?1.5:1} />
            <text x={-6} y={yf(v)+4} textAnchor="end" fontSize={9.5} fill="#94A3B8" fontFamily="IBM Plex Mono, monospace">{v}%</text>
          </g>
        ))}
        {xTicks.map(w => (
          <g key={w}>
            <line x1={xf(w)} y1={0} x2={xf(w)} y2={cH} stroke="#F1F5F9" strokeWidth={1} />
            <text x={xf(w)} y={cH+18} textAnchor="middle" fontSize={9.5} fill="#94A3B8" fontFamily="IBM Plex Mono, monospace">S{String(w).padStart(2,'0')}</text>
          </g>
        ))}
        {/* Fill */}
        <path d={actualFill} fill="url(#actualFill)" />
        {/* TODAY */}
        <line x1={todayX} y1={-4} x2={todayX} y2={cH} stroke="#475569" strokeWidth={1.5} strokeDasharray="4,3" />
        <rect x={todayX-17} y={-15} width={34} height={13} rx={2} fill="#475569" />
        <text x={todayX} y={-5} textAnchor="middle" fontSize={8.5} fill="white" fontWeight="700" fontFamily="IBM Plex Sans, sans-serif">HOJE</text>
        {/* Lines */}
        <path d={plannedD}  fill="none" stroke={C.primary}  strokeWidth={2}   strokeDasharray="8,4" />
        <path d={actualD}   fill="none" stroke={C.success}  strokeWidth={2.5} />
        <path d={forecastD} fill="none" stroke={C.warning}  strokeWidth={2}   strokeDasharray="5,3" />
        {/* Actual dots */}
        {data.filter(d => d.actual != null).map(d => (
          <circle key={d.week} cx={xf(d.week)} cy={yf(d.actual)} r={2.5} fill={C.success} stroke="white" strokeWidth={1} />
        ))}
        {/* TODAY intersection */}
        <circle cx={todayX} cy={yf(37.4)} r={4.5} fill={C.success} stroke="white" strokeWidth={1.5} />
        <circle cx={todayX} cy={yf(41.2)} r={4}   fill={C.primary} stroke="white" strokeWidth={1.5} fillOpacity="0.8" />
        {/* Labels beside today */}
        <text x={todayX+7} y={yf(37.4)+4} fontSize={9} fill={C.success} fontWeight="700" fontFamily="IBM Plex Sans, sans-serif">37,4%</text>
        <text x={todayX+7} y={yf(41.2)+4} fontSize={9} fill={C.primary} fontWeight="700" fontFamily="IBM Plex Sans, sans-serif">41,2%</text>
      </g>
      {/* Legend */}
      <g transform={`translate(${pad.l + 6},${H - 2})`} fontFamily="IBM Plex Sans, sans-serif">
        <line x1={0}   y1={0} x2={18}  y2={0} stroke={C.primary} strokeWidth={2}   strokeDasharray="7,3" />
        <text x={22}  y={3.5} fontSize={9.5} fill={C.textSub}>Planejado (baseline)</text>
        <line x1={140} y1={0} x2={158} y2={0} stroke={C.success} strokeWidth={2.5} />
        <text x={162} y={3.5} fontSize={9.5} fill={C.textSub}>Realizado</text>
        <line x1={225} y1={0} x2={243} y2={0} stroke={C.warning} strokeWidth={2}   strokeDasharray="5,3" />
        <text x={247} y={3.5} fontSize={9.5} fill={C.textSub}>Forecast IA</text>
      </g>
    </svg>
  );
}

// ─── Screen Layout Shell ─────────────────────────────────────────────────────
function ScreenShell({ title, subtitle, children, actions }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', minHeight:'100%' }}>
      <div style={{ padding:'14px 20px 10px', borderBottom:`1px solid ${C.border}`, display:'flex', alignItems:'center', justifyContent:'space-between', background:C.card }}>
        <div>
          <h1 style={{ margin:0, fontSize:16, fontWeight:800, color:C.text, letterSpacing:-0.3 }}>{title}</h1>
          {subtitle && <p style={{ margin:'2px 0 0', fontSize:11, color:C.textSub }}>{subtitle}</p>}
        </div>
        {actions && <div style={{ display:'flex', gap:8 }}>{actions}</div>}
      </div>
      <div style={{ flex:1, padding:16, overflowX:'hidden' }}>{children}</div>
    </div>
  );
}

// ─── Table helpers ───────────────────────────────────────────────────────────
function Th({ children, style }) {
  return <th style={{ padding:'7px 10px', textAlign:'left', fontSize:10.5, fontWeight:600, color:C.textSub, background:'#F8FAFC', borderBottom:`1px solid ${C.border}`, whiteSpace:'nowrap', letterSpacing:0.3, textTransform:'uppercase', ...style }}>{children}</th>;
}
function Td({ children, style }) {
  return <td style={{ padding:'8px 10px', fontSize:12, color:C.text, borderBottom:`1px solid ${C.borderSub}`, verticalAlign:'middle', ...style }}>{children}</td>;
}
function Table({ children, style }) {
  return <div style={{ overflowX:'auto', ...style }}><table style={{ width:'100%', borderCollapse:'collapse', fontSize:12 }}>{children}</table></div>;
}

// ─── SLA Countdown Badge ────────────────────────────────────────────────────
function SLABadge({ slaHours, slaRemaining }) {
  const ratio = slaRemaining / slaHours;
  const expired = slaRemaining <= 0;
  const color = expired ? C.danger : ratio > 0.5 ? C.success : ratio > 0.25 ? C.warning : C.danger;
  const bg    = expired ? '#FEE2E2' : ratio > 0.5 ? '#D1FAE5' : ratio > 0.25 ? '#FEF3C7' : '#FEE2E2';
  const label = expired ? 'VENCIDO' : slaRemaining < 1 ? `${Math.round(slaRemaining*60)}min` : `${slaRemaining.toFixed(0)}h`;
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:4, padding:'2px 7px', borderRadius:4, background:bg, color, fontWeight:700, fontSize:11, border:`1px solid ${color}40` }}>
      {expired ? '⚠ ' : ''}{label} restante
    </span>
  );
}

// ─── Btn ─────────────────────────────────────────────────────────────────────
function Btn({ children, variant = 'default', onClick, small, style }) {
  const map = {
    primary: { bg:C.primary, color:'#fff', border:C.primary },
    success: { bg:C.success, color:'#fff', border:C.success },
    danger:  { bg:C.danger,  color:'#fff', border:C.danger  },
    warning: { bg:C.warning, color:'#fff', border:C.warning },
    default: { bg:'#fff', color:C.text, border:C.border },
    ghost:   { bg:'transparent', color:C.textSub, border:C.border },
  };
  const s = map[variant] || map.default;
  return (
    <button onClick={onClick} style={{
      padding: small ? '4px 10px' : '6px 14px',
      fontSize: small ? 11 : 12, fontWeight:600, cursor:'pointer',
      background:s.bg, color:s.color, border:`1px solid ${s.border}`,
      borderRadius:5, fontFamily:'inherit', transition:'opacity 0.1s', ...style
    }}
    onMouseEnter={e => e.currentTarget.style.opacity='0.85'}
    onMouseLeave={e => e.currentTarget.style.opacity='1'}
    >{children}</button>
  );
}

// Export everything
Object.assign(window, {
  C, fmtBRL, fmtPct, statusColor, statusLabel,
  Sidebar, TopBar, Card, Badge, KPICard, DualBar, Gauge, Sparkline, CurvaS,
  ScreenShell, Th, Td, Table, SLABadge, Btn,
});
