// ============================================
// SECTIONS 1 — Industries, Live Dashboard, Depreciation Slider, ROI Calculator
// ============================================
const { useState: useS1, useEffect: useE1, useRef: useR1, useMemo: useM1 } = React;

// ---------- INDUSTRIES ----------
function Industries() {
  const items = [
    { id: '001', name: 'Manufactura', desc: 'Líneas de producción, OEE y maquinaria industrial', c: 'var(--lime)' },
    { id: '002', name: 'Ingeniería', desc: 'Instrumentación, calibraciones y trazabilidad metrológica', c: 'var(--violet)' },
    { id: '003', name: 'Contabilidad', desc: 'Causaciones, cuentas contables y estados financieros', c: 'var(--magenta)' },
    { id: '004', name: 'Logística', desc: 'Flota vehicular, traslados entre sedes y rutas', c: 'var(--cyan)' },
    { id: '005', name: 'Salud', desc: 'Equipo médico, calibración y hoja de vida clínica', c: 'var(--red)' },
    { id: '006', name: 'Sector Público', desc: 'Bienes del estado, depreciación fiscal y auditorías', c: 'var(--amber)' },
  ];

  return (
    <section className="block" id="industrias">
      <div className="container">
        <div className="industries-grid">
          <div className="reveal">
            <div className="eyebrow"><span className="dot"></span><span>INDUSTRIAS · MULTI-SECTOR</span></div>
            <h2 className="section-h">Hecho para <span className="glow">tu sector</span></h2>
            <p className="section-sub">
              Una plataforma adaptada a la realidad de cada industria, con módulos específicos
              para cada caso de uso. Reportes automáticos, multi-empresa, multi-sede y con
              API abierta para integraciones.
            </p>
            <div className="check-list">
              {['Reportes contables automáticos', 'Multi-empresa y multi-sede', 'Integración con software contable', 'API abierta para integraciones'].map(c => (
                <div className="check-item" key={c}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" strokeWidth="2.5"><path d="M5 13l4 4L19 7"/></svg>
                  <span>{c}</span>
                </div>
              ))}
            </div>
            <a className="btn btn-ghost" style={{marginTop: 28}} href="https://wa.me/573017287922?text=Estoy%20interesado%20en%20Mi%20Activo%20360...">
              Hablar con un asesor →
            </a>
          </div>
          <div className="ind-cards reveal-stagger reveal">
            {items.map(it => (
              <div key={it.id} className="ind-card hover-target">
                <span className="ind-id mono">{it.id}</span>
                <div className="ind-icon" style={{ color: it.c, background: `${it.c}22`, borderColor: `${it.c}44`, boxShadow: `0 0 16px ${it.c}33` }}>
                  <IndIcon name={it.name} color={it.c}/>
                </div>
                <div className="ind-name">{it.name}</div>
                <div className="ind-desc">{it.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function IndIcon({name, color}) {
  const paths = {
    'Manufactura': <path d="M4 20V9l5 3V9l5 3V9l5 3v8H4zM7 20v-5M11 20v-5M15 20v-5"/>,
    'Ingeniería': <path d="M12 3v18M3 12h18M5.6 5.6l12.8 12.8M18.4 5.6L5.6 18.4"/>,
    'Contabilidad': <path d="M5 5h14v14H5zM8 9h8M8 13h5M8 17h3"/>,
    'Logística': <path d="M3 17h13l2-6h3l1 3v4M6 17v2M16 17v2M6 11h10l-1 6"/>,
    'Salud': <path d="M12 3v18M3 12h18M7 7h10M7 17h10"/>,
    'Sector Público': <path d="M4 20h16M6 20V9l6-5 6 5v11M10 14h4v6"/>,
  };
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{filter: `drop-shadow(0 0 4px ${color})`}}>
      {paths[name] || <circle cx="12" cy="12" r="8"/>}
    </svg>
  );
}

// ---------- LIVE DASHBOARD (sticky-build) ----------
function LiveDashboard() {
  const [kpis, setKpis] = useS1({
    total: 248, value: 4.23, maint: 12, alerts: 5, util: 87.3,
  });
  const [pulses, setPulses] = useS1([]);
  const [eventFeed, setEventFeed] = useS1([
    { t: '14:22:01', m: 'ACT-2024-091 asignado a Sede Norte', c: 'cyan' },
    { t: '14:21:47', m: 'Mantenimiento preventivo completado · Compresor A-12', c: 'lime' },
    { t: '14:21:15', m: 'Alerta: garantía por vencer (7 días)', c: 'amber' },
  ]);

  useE1(() => {
    const id = setInterval(() => {
      setKpis(k => ({
        total: k.total + (Math.random() > 0.5 ? 1 : 0),
        value: +(k.value + (Math.random() - 0.4) * 0.04).toFixed(2),
        maint: Math.max(5, Math.min(20, k.maint + (Math.random() > 0.5 ? 1 : -1))),
        alerts: Math.max(0, Math.min(12, k.alerts + (Math.random() > 0.7 ? 1 : -1))),
        util: Math.max(75, Math.min(98, +(k.util + (Math.random() - 0.5) * 1.5).toFixed(1))),
      }));
      // event feed
      const events = [
        { m: 'QR escaneado · Servidor R-740 · Sede Principal', c: 'cyan' },
        { m: 'Depreciación mensual calculada · $12.4M', c: 'lime' },
        { m: 'Nuevo activo registrado · Impresora HP LaserJet', c: 'cyan' },
        { m: 'Carga masiva Excel · 142 activos importados', c: 'amber' },
        { m: 'Consumible asignado · 2 resmas papel carta', c: 'violet' },
        { m: 'Mantenimiento programado · En 3 días', c: 'amber' },
        { m: 'Alerta: stock bajo · Tóner impresora', c: 'magenta' },
        { m: 'Usuario confirmó recibido · Lapiceros BIC', c: 'lime' },
      ];
      const ev = events[Math.floor(Math.random() * events.length)];
      const now = new Date();
      const tstr = `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}`;
      setEventFeed(f => [{ t: tstr, ...ev }, ...f].slice(0, 6));
    }, 1600);
    return () => clearInterval(id);
  }, []);

  return (
    <section className="block" id="sistema">
      <div className="container">
        <div className="section-head-center reveal">
          <div className="eyebrow" style={{margin: '0 auto'}}><span className="dot"></span><span>EL SISTEMA · LIVE</span></div>
          <h2 className="section-h">Todo lo que pasa en tu operación, <span className="glow">en vivo</span></h2>
          <p className="section-sub" style={{margin: '0 auto'}}>
            Dashboards que se actualizan en tiempo real, alertas inteligentes y reportes
            automáticos para tomar decisiones con datos.
          </p>
        </div>

        <div className="live-dash reveal">
          <div className="ld-top">
            <div className="ld-top-l">
              <span className="mono kbd" style={{color: 'var(--lime)'}}>● LIVE</span>
              <span className="mono" style={{color: 'var(--ink-3)', fontSize: 11, letterSpacing: '0.1em'}}>OPERATION DASHBOARD · v4.2.1</span>
            </div>
            <div className="ld-top-r mono" style={{fontSize: 11, color: 'var(--ink-3)'}}>
              <LiveClock />
            </div>
          </div>

          <div className="ld-body">
            {/* KPI column */}
            <div className="ld-kpis">
              {[
                { l: 'ACTIVOS TOTALES', v: kpis.total, s: '+3 hoy', c: 'cyan' },
                { l: 'VALOR EN LIBROS', v: `$${kpis.value.toFixed(2)}B`, s: 'COP', c: 'lime' },
                { l: 'EN MANTENIMIENTO', v: kpis.maint, s: 'equipos', c: 'amber' },
                { l: 'ALERTAS ACTIVAS', v: kpis.alerts, s: 'req. atención', c: 'magenta' },
                { l: 'UTILIZACIÓN', v: `${kpis.util}%`, s: 'flota', c: 'violet' },
              ].map(k => (
                <div className="ld-kpi" key={k.l}>
                  <div className="ld-kpi-l mono">{k.l}</div>
                  <div className={`ld-kpi-v text-${k.c}`}>{k.v}</div>
                  <div className="ld-kpi-s mono">{k.s}</div>
                  <div className="ld-kpi-bar"><div className="ld-kpi-bar-fill" style={{background: `var(--${k.c})`, width: `${60 + Math.random()*40}%`}}></div></div>
                </div>
              ))}
            </div>

            {/* Center - multi chart */}
            <div className="ld-center">
              <div className="ld-chart-head">
                <span className="mono" style={{fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.12em'}}>DEPRECIACIÓN ACUMULADA · 12M</span>
                <div className="ld-chart-legend">
                  <span><i style={{background:'var(--cyan)'}}></i>Lineal</span>
                  <span><i style={{background:'var(--amber)'}}></i>Saldo Dec.</span>
                </div>
              </div>
              <LiveAreaChart/>

              <div className="ld-subgrid">
                <div className="ld-panel">
                  <div className="ld-panel-t mono">ACTIVOS POR ESTADO</div>
                  <DonutChart/>
                </div>
                <div className="ld-panel">
                  <div className="ld-panel-t mono">DISTRIBUCIÓN DE FLOTA</div>
                  <div className="ld-fleet">
                    {[
                      { n: 'Maquinaria', v: 34, c: 'var(--amber)' },
                      { n: 'Vehículos', v: 28, c: 'var(--cyan)' },
                      { n: 'Equipos TI', v: 42, c: 'var(--violet)' },
                      { n: 'Edificios', v: 8, c: 'var(--lime)' },
                    ].map(f => (
                      <div key={f.n} className="ld-fleet-row">
                        <span>{f.n}</span>
                        <div className="ld-fleet-bar"><div style={{background: f.c, width: `${f.v*2}%`}}></div></div>
                        <span className="mono" style={{color: f.c}}>{f.v}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Right — event feed */}
            <div className="ld-feed">
              <div className="ld-feed-head mono">
                <span>EVENT STREAM</span>
                <span className="text-lime">● {eventFeed.length} events</span>
              </div>
              <div className="ld-feed-list">
                {eventFeed.map((e, i) => (
                  <div key={e.t + i} className="ld-feed-item" style={{opacity: 1 - i*0.12}}>
                    <span className="mono" style={{color: 'var(--ink-3)', fontSize: 10}}>{e.t}</span>
                    <span className={`text-${e.c}`} style={{fontSize: 11}}>{e.m}</span>
                    <span className={`ld-feed-dot text-${e.c}`}>●</span>
                  </div>
                ))}
              </div>

              <div className="ld-map">
                <div className="ld-map-t mono">UBICACIONES · COLOMBIA</div>
                <SiteMap/>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function LiveClock() {
  const [t, setT] = useS1(new Date());
  useE1(() => {
    const id = setInterval(() => setT(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const pad = n => String(n).padStart(2, '0');
  return <span>SYS TIME · {pad(t.getHours())}:{pad(t.getMinutes())}:{pad(t.getSeconds())} · BOGOTÁ</span>;
}

function LiveAreaChart() {
  const [pts, setPts] = useS1(() => {
    return Array.from({length: 36}, (_, i) => ({
      a: 25 + Math.sin(i*0.35)*10 + Math.random()*6,
      b: 18 + Math.cos(i*0.28)*8 + Math.random()*5,
    }));
  });
  useE1(() => {
    const id = setInterval(() => {
      setPts(p => {
        const n = [...p.slice(1)];
        const last = p[p.length-1];
        n.push({
          a: Math.max(10, Math.min(55, last.a + (Math.random()-0.5)*5)),
          b: Math.max(8, Math.min(45, last.b + (Math.random()-0.5)*4)),
        });
        return n;
      });
    }, 1200);
    return () => clearInterval(id);
  }, []);
  const W = 520, H = 160;
  const sx = W / (pts.length-1);
  const pathA = pts.map((p,i) => `${i===0?'M':'L'} ${i*sx} ${H-p.a*2.4}`).join(' ');
  const pathB = pts.map((p,i) => `${i===0?'M':'L'} ${i*sx} ${H-p.b*2.4}`).join(' ');
  const fillA = `${pathA} L ${W} ${H} L 0 ${H} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="ld-area" preserveAspectRatio="none">
      <defs>
        <linearGradient id="areaA" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="var(--cyan)" stopOpacity="0.4"/>
          <stop offset="100%" stopColor="var(--cyan)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[0,1,2,3].map(i => <line key={i} x1="0" x2={W} y1={H*i/3} y2={H*i/3} stroke="rgba(120,160,220,0.08)" strokeDasharray="3 3"/>)}
      <path d={fillA} fill="url(#areaA)"/>
      <path d={pathA} stroke="var(--cyan)" strokeWidth="1.8" fill="none" style={{filter:'drop-shadow(0 0 4px var(--cyan))'}}/>
      <path d={pathB} stroke="var(--amber)" strokeWidth="1.5" fill="none" strokeDasharray="4 3" style={{filter:'drop-shadow(0 0 3px var(--amber))'}}/>
      {pts.map((p,i) => i===pts.length-1 && (
        <g key="dot">
          <circle cx={i*sx} cy={H-p.a*2.4} r="4" fill="var(--cyan)">
            <animate attributeName="r" values="4;7;4" dur="1.2s" repeatCount="indefinite"/>
          </circle>
          <circle cx={i*sx} cy={H-p.a*2.4} r="3" fill="var(--cyan)" style={{filter:'drop-shadow(0 0 8px var(--cyan))'}}/>
        </g>
      ))}
    </svg>
  );
}

function DonutChart() {
  const data = [
    { n: 'Activos', v: 166, c: 'var(--cyan)' },
    { n: 'Mantenim.', v: 57, c: 'var(--amber)' },
    { n: 'Baja temp.', v: 19, c: 'var(--violet)' },
    { n: 'Dado de baja', v: 6, c: 'var(--red)' },
  ];
  const total = data.reduce((s,d) => s+d.v, 0);
  let offset = 0;
  const C = 2 * Math.PI * 34;
  return (
    <div className="ld-donut-wrap">
      <svg width="110" height="110" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="34" fill="none" stroke="rgba(120,160,220,0.1)" strokeWidth="10"/>
        {data.map(d => {
          const len = (d.v/total) * C;
          const el = <circle key={d.n} cx="50" cy="50" r="34" fill="none" stroke={d.c} strokeWidth="10"
            strokeDasharray={`${len} ${C-len}`} strokeDashoffset={-offset} transform="rotate(-90 50 50)"
            style={{filter: `drop-shadow(0 0 4px ${d.c})`, transition: 'stroke-dasharray 0.6s'}}/>;
          offset += len;
          return el;
        })}
        <text x="50" y="48" textAnchor="middle" fontFamily="var(--display)" fontSize="18" fontWeight="600" fill="var(--ink-0)">{total}</text>
        <text x="50" y="62" textAnchor="middle" fontFamily="var(--mono)" fontSize="7" fill="var(--ink-3)" letterSpacing="1">TOTAL</text>
      </svg>
      <div className="ld-donut-legend">
        {data.map(d => (
          <div key={d.n}><i style={{background: d.c, boxShadow: `0 0 6px ${d.c}`}}></i>{d.n} <b>{d.v}</b></div>
        ))}
      </div>
    </div>
  );
}

function SiteMap() {
  const sites = [
    { x: 35, y: 55, n: 'Bogotá', val: 86, active: true },
    { x: 28, y: 40, n: 'Medellín', val: 52 },
    { x: 22, y: 72, n: 'Cali', val: 38 },
    { x: 40, y: 30, n: 'Bucaramanga', val: 28 },
    { x: 20, y: 18, n: 'Barranquilla', val: 44 },
  ];
  return (
    <svg viewBox="0 0 100 100" className="ld-map-svg">
      {/* Rough Colombia silhouette */}
      <path d="M 25 15 L 45 18 L 50 30 L 48 45 L 52 55 L 48 70 L 38 85 L 28 90 L 18 80 L 15 60 L 18 40 L 22 25 Z"
        fill="rgba(6,182,212,0.06)" stroke="rgba(6,182,212,0.3)" strokeWidth="0.5"/>
      {sites.map(s => (
        <g key={s.n}>
          <circle cx={s.x} cy={s.y} r={s.active ? 4 : 2} fill="var(--cyan)" opacity="0.4">
            <animate attributeName="r" values={`${s.active?4:2};${s.active?9:5};${s.active?4:2}`} dur="2s" repeatCount="indefinite"/>
            <animate attributeName="opacity" values="0.5;0;0.5" dur="2s" repeatCount="indefinite"/>
          </circle>
          <circle cx={s.x} cy={s.y} r="1.5" fill="var(--cyan)" style={{filter:'drop-shadow(0 0 2px var(--cyan))'}}/>
          <text x={s.x+4} y={s.y+1} fontSize="3" fontFamily="var(--mono)" fill="var(--ink-1)">{s.n} · {s.val}</text>
        </g>
      ))}
    </svg>
  );
}

// ---------- DEPRECIATION SLIDER ----------
function DepreciationLab() {
  const [years, setYears] = useS1(6);
  const [method, setMethod] = useS1('linea');
  const [cost, setCost] = useS1(500);
  const useful = 10;
  const salvage = 50;

  const series = useM1(() => {
    const pts = [];
    for (let y = 0; y <= useful; y++) {
      let val;
      if (method === 'linea') {
        val = cost - ((cost - salvage) / useful) * y;
      } else if (method === 'saldo') {
        const rate = 0.2;
        val = cost * Math.pow(1 - rate, y);
      } else {
        // sum of digits
        const n = useful;
        const sum = n * (n+1) / 2;
        let acc = cost;
        for (let i = 1; i <= y; i++) {
          acc -= ((cost - salvage) * (n - i + 1)) / sum;
        }
        val = acc;
      }
      pts.push(Math.max(salvage, val));
    }
    return pts;
  }, [method, cost]);

  const current = series[years] || salvage;
  const accumulated = cost - current;
  const pct = ((cost - current) / (cost - salvage)) * 100;

  return (
    <section className="block" id="depreciacion">
      <div className="container">
        <div className="section-head reveal">
          <div className="eyebrow magenta"><span className="dot"></span><span>LAB · DEPRECIACIÓN</span></div>
          <h2 className="section-h">Calcula cualquier <span className="glow">método</span> en segundos</h2>
          <p className="section-sub">
            Arrastra el slider y mira cómo cambia el valor en libros. El sistema hace esto
            automáticamente para miles de activos y por cualquier método.
          </p>
        </div>

        <div className="dep-lab reveal">
          <div className="dep-lab-controls">
            <div className="dep-field">
              <label className="mono">COSTO DE ADQUISICIÓN</label>
              <div className="dep-cost-row">
                <span className="mono" style={{color: 'var(--cyan)'}}>$</span>
                <input type="range" min="50" max="2000" step="10" value={cost} onChange={e => setCost(+e.target.value)}/>
                <span className="mono dep-cost-v">${cost}M</span>
              </div>
            </div>
            <div className="dep-field">
              <label className="mono">MÉTODO</label>
              <div className="dep-methods">
                {[
                  { k: 'linea', l: 'Línea Recta' },
                  { k: 'saldo', l: 'Saldo Decreciente' },
                  { k: 'suma', l: 'Suma Dígitos' },
                ].map(m => (
                  <button key={m.k} className={`dep-method hover-target ${method===m.k?'active':''}`} onClick={() => setMethod(m.k)}>
                    {m.l}
                  </button>
                ))}
              </div>
            </div>
            <div className="dep-field">
              <label className="mono">AÑO EN CURSO · {years}/{useful}</label>
              <input type="range" min="0" max={useful} step="1" value={years} onChange={e => setYears(+e.target.value)} className="dep-year"/>
            </div>
          </div>

          <div className="dep-lab-chart">
            <DepChart series={series} currentYear={years}/>
            <div className="dep-readout">
              <div>
                <div className="mono" style={{fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.1em'}}>VALOR EN LIBROS</div>
                <div className="dep-readout-v text-cyan">${current.toFixed(0)}M</div>
              </div>
              <div>
                <div className="mono" style={{fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.1em'}}>DEPRECIACIÓN ACUM.</div>
                <div className="dep-readout-v text-magenta">${accumulated.toFixed(0)}M</div>
              </div>
              <div>
                <div className="mono" style={{fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.1em'}}>% VIDA ÚTIL</div>
                <div className="dep-readout-v text-amber">{pct.toFixed(0)}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function DepChart({ series, currentYear }) {
  const W = 600, H = 240, pad = 30;
  const maxV = Math.max(...series);
  const minV = Math.min(...series);
  const sx = (W - pad*2) / (series.length-1);
  const sy = v => H - pad - ((v - minV) / (maxV - minV || 1)) * (H - pad*2);

  const path = series.map((v, i) => `${i===0?'M':'L'} ${pad + i*sx} ${sy(v)}`).join(' ');
  const fill = `${path} L ${pad + (series.length-1)*sx} ${H-pad} L ${pad} ${H-pad} Z`;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="dep-chart-svg">
      <defs>
        <linearGradient id="depFill" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="var(--cyan)" stopOpacity="0.4"/>
          <stop offset="100%" stopColor="var(--cyan)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* Grid */}
      {[0,1,2,3,4].map(i => (
        <line key={i} x1={pad} x2={W-pad} y1={pad + i*(H-pad*2)/4} y2={pad + i*(H-pad*2)/4} stroke="rgba(120,160,220,0.1)" strokeDasharray="3 3"/>
      ))}
      {series.map((_, i) => (
        <line key={`v${i}`} x1={pad + i*sx} x2={pad + i*sx} y1={pad} y2={H-pad} stroke="rgba(120,160,220,0.06)"/>
      ))}
      <path d={fill} fill="url(#depFill)" style={{transition: 'd 0.4s'}}/>
      <path d={path} fill="none" stroke="var(--cyan)" strokeWidth="2" style={{filter: 'drop-shadow(0 0 4px var(--cyan))', transition: 'd 0.4s'}}/>
      {/* Current year indicator */}
      <line x1={pad + currentYear*sx} x2={pad + currentYear*sx} y1={pad} y2={H-pad} stroke="var(--amber)" strokeDasharray="4 3" strokeWidth="1"/>
      <circle cx={pad + currentYear*sx} cy={sy(series[currentYear])} r="6" fill="var(--amber)" style={{filter:'drop-shadow(0 0 8px var(--amber))'}}>
        <animate attributeName="r" values="6;9;6" dur="1.5s" repeatCount="indefinite"/>
      </circle>
      <circle cx={pad + currentYear*sx} cy={sy(series[currentYear])} r="3" fill="var(--ink-0)"/>
      {series.map((v, i) => i % 2 === 0 && (
        <text key={`t${i}`} x={pad + i*sx} y={H-pad+14} textAnchor="middle" fontSize="9" fontFamily="var(--mono)" fill="var(--ink-3)">Año {i}</text>
      ))}
    </svg>
  );
}

// ---------- ROI CALCULATOR ----------
function ROICalc() {
  const [assets, setAssets] = useS1(300);
  const [hoursPerMonth, setHoursPerMonth] = useS1(40);
  const [hourlyRate, setHourlyRate] = useS1(35000);

  const monthlySaving = hoursPerMonth * hourlyRate * 0.7; // 70% time saved
  const annualSaving = monthlySaving * 12;
  const assetLosses = assets * 12000 * 0.68; // 68% reduction in lost assets ($12K avg)
  const totalAnnual = annualSaving + assetLosses;
  const roi = Math.round(totalAnnual / 1000);

  const fmt = n => new Intl.NumberFormat('es-CO').format(Math.round(n));

  return (
    <section className="block" id="roi">
      <div className="container">
        <div className="roi-wrap reveal">
          <div className="roi-left">
            <div className="eyebrow lime"><span className="dot"></span><span>CALCULADORA · ROI</span></div>
            <h2 className="section-h">¿Cuánto <span className="glow">ahorrás</span> al mes?</h2>
            <p className="section-sub">
              Ajustá los valores y calculá tu retorno real. Basado en datos de clientes:
              reducción del 68% en activos perdidos y 70% menos tiempo en gestión manual.
            </p>

            <div className="roi-controls">
              <ROIField
                label="ACTIVOS FIJOS EN TU EMPRESA"
                value={assets}
                onChange={setAssets}
                min={50} max={5000} step={50}
                display={fmt(assets)}
              />
              <ROIField
                label="HORAS/MES EN GESTIÓN MANUAL"
                value={hoursPerMonth}
                onChange={setHoursPerMonth}
                min={5} max={200} step={5}
                display={`${hoursPerMonth}h`}
              />
              <ROIField
                label="COSTO/HORA (COP)"
                value={hourlyRate}
                onChange={setHourlyRate}
                min={10000} max={120000} step={5000}
                display={`$${fmt(hourlyRate)}`}
              />
            </div>
          </div>

          <div className="roi-right">
            <div className="roi-result">
              <div className="roi-result-t mono">AHORRO ANUAL ESTIMADO</div>
              <div className="roi-result-v">
                <span className="roi-currency">$</span>
                <CountUp value={totalAnnual}/>
              </div>
              <div className="roi-result-s mono">COP · ESTIMACIÓN</div>

              <div className="roi-breakdown">
                <div className="roi-break">
                  <div className="mono" style={{fontSize: 10, color: 'var(--ink-3)'}}>TIEMPO AHORRADO (ANUAL)</div>
                  <div className="text-cyan mono" style={{fontSize: 18, marginTop: 4}}>${fmt(annualSaving)}</div>
                </div>
                <div className="roi-break">
                  <div className="mono" style={{fontSize: 10, color: 'var(--ink-3)'}}>REDUCCIÓN PÉRDIDAS (ANUAL)</div>
                  <div className="text-lime mono" style={{fontSize: 18, marginTop: 4}}>${fmt(assetLosses)}</div>
                </div>
                <div className="roi-break">
                  <div className="mono" style={{fontSize: 10, color: 'var(--ink-3)'}}>ROI ESTIMADO</div>
                  <div className="text-amber mono" style={{fontSize: 18, marginTop: 4}}>×{Math.round(totalAnnual / (assets * 24000))}</div>
                </div>
              </div>

              <a className="btn btn-primary" style={{marginTop: 28, width: '100%', justifyContent: 'center'}} href="https://wa.me/573017287922?text=Estoy%20interesado%20en%20Mi%20Activo%20360...">
                Agendar demo personalizada
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ROIField({label, value, onChange, min, max, step, display}) {
  return (
    <div className="roi-field">
      <div className="roi-field-top">
        <label className="mono">{label}</label>
        <span className="mono roi-val text-cyan">{display}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(+e.target.value)} className="hover-target"/>
    </div>
  );
}

function CountUp({ value }) {
  const [displayed, setDisplayed] = useS1(value);
  const prev = useR1(value);
  useE1(() => {
    const start = prev.current;
    const diff = value - start;
    const dur = 800;
    const t0 = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - t0) / dur);
      const eased = 1 - Math.pow(1-p, 3);
      setDisplayed(Math.round(start + diff * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
      else prev.current = value;
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return <span>{new Intl.NumberFormat('es-CO').format(displayed)}</span>;
}

window.Industries = Industries;
window.LiveDashboard = LiveDashboard;
window.DepreciationLab = DepreciationLab;
window.ROICalc = ROICalc;
