/* global React, Icon, Reveal, CountUp */
const { useEffect: useEffectMid, useState: useStateMid } = React;

/* ===========================================================
   Dashboard mockup
   =========================================================== */
function Dashboard() {
  // Live-ish data simulation
  const [now, setNow] = useStateMid(8.42);
  useEffectMid(() => {
    const id = setInterval(() => {
      setNow((v) => Math.max(6.5, Math.min(9.8, v + (Math.random() - 0.5) * 0.3)));
    }, 1800);
    return () => clearInterval(id);
  }, []);

  // sparkline data — hours of the day
  const hours = Array.from({ length: 24 }, (_, h) => {
    if (h < 7 || h > 19) return 0;
    const peak = 12;
    const v = Math.max(0, 9 - Math.abs(h - peak) * 1.1);
    return v + (Math.sin(h * 1.3) * 0.4);
  });
  const maxH = Math.max(...hours);

  return (
    <section className="section">
      <div className="container">
        <div className="section-head">
          <div>
            <p className="eyebrow mb-3">04 — Plataforma de monitoreo</p>
            <h2 className="h-1">Lo que ve tu equipo después de la puesta en marcha.</h2>
          </div>
          <p className="muted">
            Dashboard 24/7 con producción en tiempo real, ahorro acumulado, alertas operacionales y reportes exportables.
            Acceso por usuario y por planta para grupos multi-sitio.
          </p>
        </div>

        <div className="dash">
          {/* Window chrome */}
          <div className="dash-bar">
            <span className="dash-dot" style={{ background: '#FF5F57' }} />
            <span className="dash-dot" style={{ background: '#FEBC2E' }} />
            <span className="dash-dot" style={{ background: '#28C840' }} />
            <span style={{ flex: 1, textAlign: 'center', color: 'rgba(255,255,255,.5)' }}>
              monitor.slf.cl / planta · MAULE-AGRO-04
            </span>
            <span className="mono" style={{ color: 'rgba(255,255,255,.4)' }}>● en línea</span>
          </div>

          <div style={{ padding: 24 }}>
            {/* Header row */}
            <div className="flex items-center justify-between mb-6" style={{ flexWrap: 'wrap', gap: 16 }}>
              <div>
                <p style={{ margin: 0, color: 'rgba(255,255,255,.5)', fontSize: 12, fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '.06em' }}>
                  Planta Agroindustrial · Linares, Maule
                </p>
                <h3 style={{ margin: '4px 0 0', color: '#fff', fontSize: 22, fontWeight: 600 }}>
                  MAULE-AGRO-04 · 1.840 kWp
                </h3>
              </div>
              <div className="flex items-center gap-3">
                <span className="badge badge-onblue" style={{ background: 'rgba(22,163,74,.18)', borderColor: 'rgba(22,163,74,.4)', color: '#86EFAC' }}>
                  <span className="pulse-dot" /> 100% disponibilidad
                </span>
                <span className="badge badge-onblue mono">Vivo · 12:42</span>
              </div>
            </div>

            {/* KPI row */}
            <div className="dash-kpi" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 24 }}>
              <DashKpi label="Producción ahora" value={now.toFixed(2)} unit="kW" big accent />
              <DashKpi label="Generado hoy" value="11.482" unit="kWh" />
              <DashKpi label="Mes acumulado" value="241.5" unit="MWh" />
              <DashKpi label="Ahorro acumulado" value="$84.6 M" unit="CLP · año" green />
            </div>

            {/* Chart */}
            <div style={{
              background: 'rgba(0,0,0,.25)',
              border: '1px solid rgba(255,255,255,.06)',
              borderRadius: 10,
              padding: 20,
              marginBottom: 16,
            }}>
              <div className="flex items-center justify-between mb-4">
                <p style={{ margin: 0, color: '#fff', fontSize: 14, fontWeight: 500 }}>Curva de generación · hoy</p>
                <div className="flex items-center gap-4 mono" style={{ fontSize: 11, color: 'rgba(255,255,255,.5)' }}>
                  <span className="flex items-center gap-2"><span style={{ width: 8, height: 8, background: '#FFB800', borderRadius: 2 }} />Real</span>
                  <span className="flex items-center gap-2"><span style={{ width: 8, height: 8, border: '1px dashed rgba(255,255,255,.4)', borderRadius: 2 }} />Esperado</span>
                </div>
              </div>
              {/* Bar chart */}
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 140 }}>
                {hours.map((v, h) => (
                  <div key={h} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                    <div style={{
                      width: '100%',
                      height: `${(v / (maxH || 1)) * 100}%`,
                      background: h === 12 ? '#FFB800' : (v > 0 ? 'rgba(255,184,0,.6)' : 'transparent'),
                      borderRadius: 2,
                      minHeight: v > 0 ? 4 : 0,
                      transition: 'height .4s',
                    }} />
                    <span className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,.3)' }}>{h.toString().padStart(2, '0')}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Bottom row */}
            <div className="dash-bottom" style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 12 }}>
              <div style={{
                background: 'rgba(0,0,0,.25)',
                border: '1px solid rgba(255,255,255,.06)',
                borderRadius: 10,
                padding: 16,
              }}>
                <p style={{ margin: '0 0 12px', color: '#fff', fontSize: 13, fontWeight: 500 }}>Inversores · 4 strings</p>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
                  {[
                    { id: 'INV-01', val: 412, st: 'ok' },
                    { id: 'INV-02', val: 408, st: 'ok' },
                    { id: 'INV-03', val: 415, st: 'ok' },
                    { id: 'INV-04', val: 397, st: 'warn' },
                  ].map((inv) => (
                    <div key={inv.id} style={{
                      background: 'rgba(255,255,255,.03)',
                      border: `1px solid ${inv.st === 'warn' ? 'rgba(255,184,0,.4)' : 'rgba(255,255,255,.08)'}`,
                      borderRadius: 6,
                      padding: 10,
                    }}>
                      <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,.5)', letterSpacing: '.06em' }}>{inv.id}</div>
                      <div className="mono" style={{ fontSize: 18, color: '#fff', fontWeight: 500, marginTop: 4 }}>{inv.val}<span style={{ fontSize: 10, color: 'rgba(255,255,255,.5)' }}> kW</span></div>
                      <div className="mono" style={{ fontSize: 9, color: inv.st === 'warn' ? '#FFB800' : '#86EFAC', marginTop: 2 }}>
                        {inv.st === 'warn' ? '● aviso menor' : '● ok'}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div style={{
                background: 'rgba(0,0,0,.25)',
                border: '1px solid rgba(255,255,255,.06)',
                borderRadius: 10,
                padding: 16,
              }}>
                <p style={{ margin: '0 0 12px', color: '#fff', fontSize: 13, fontWeight: 500 }}>Alertas activas</p>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <div className="flex items-start gap-3">
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#FFB800', marginTop: 7, flex: '0 0 auto' }} />
                    <div>
                      <p className="mono" style={{ margin: 0, fontSize: 12, color: '#fff' }}>INV-04 · derate 4%</p>
                      <p className="mono" style={{ margin: 0, fontSize: 10, color: 'rgba(255,255,255,.45)' }}>11:38 — revisión programada jue.</p>
                    </div>
                  </div>
                  <div className="flex items-start gap-3">
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#16A34A', marginTop: 7, flex: '0 0 auto' }} />
                    <div>
                      <p className="mono" style={{ margin: 0, fontSize: 12, color: '#fff' }}>Limpieza completada · sector B</p>
                      <p className="mono" style={{ margin: 0, fontSize: 10, color: 'rgba(255,255,255,.45)' }}>ayer 17:20 — ganancia +2.1%</p>
                    </div>
                  </div>
                </div>
                <button className="btn btn-sm btn-onblue mt-4 w-full" style={{ justifyContent: 'center' }}>
                  <Icon.Download /> Exportar reporte mensual
                </button>
              </div>
            </div>
          </div>
        </div>

        <style>{`
          @media (max-width: 720px) {
            .dash-kpi { grid-template-columns: repeat(2, 1fr) !important; }
            .dash-bottom { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

function DashKpi({ label, value, unit, big, accent, green }) {
  return (
    <div style={{
      background: 'rgba(0,0,0,.25)',
      border: '1px solid rgba(255,255,255,.06)',
      borderRadius: 10,
      padding: 14,
    }}>
      <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,.5)', letterSpacing: '.06em', textTransform: 'uppercase' }}>{label}</div>
      <div className="mono" style={{
        fontSize: big ? 28 : 22, fontWeight: 500,
        color: accent ? '#FFB800' : green ? '#86EFAC' : '#fff',
        marginTop: 4, letterSpacing: '-0.02em',
      }}>
        {value}<span style={{ fontSize: 11, color: 'rgba(255,255,255,.5)', marginLeft: 4 }}>{unit}</span>
      </div>
    </div>
  );
}

/* ===========================================================
   Casos de éxito
   =========================================================== */
function Cases() {
  const cases = [
    {
      sector: 'Agroindustria',
      where: 'Linares · Maule',
      title: 'Frutícola exportadora · Riego y frío',
      kwp: 1840,
      saving: 38,
      payback: 5.4,
      placeholder: 'Fotografía real de planta SLF — agroindustria, Maule. Pendiente de autorización.',
      href: 'SLF Energia - Caso Antofagasta.html',
    },
    {
      sector: 'Manufactura',
      where: 'Quilicura · RM',
      title: 'Industria de envases · Autoconsumo',
      kwp: 980,
      saving: 31,
      payback: 6.8,
      placeholder: 'Fotografía real de cubierta SLF — manufactura, RM. Pendiente de autorización.',
      href: 'SLF Energia - Caso Antofagasta.html',
    },
    {
      sector: 'Minería (proveedor)',
      where: 'Antofagasta',
      title: 'Servicios mineros · Faena remota',
      kwp: 2450,
      saving: 44,
      payback: 4.4,
      placeholder: 'Fotografía real de instalación SLF — proveedor minería, II Región. Pendiente.',
      href: 'SLF Energia - Caso Antofagasta.html',
    },
  ];

  return (
    <section id="casos" className="section bg-off">
      <div className="container">
        <div className="section-head">
          <div>
            <p className="eyebrow mb-3">05 — Casos de éxito</p>
            <h2 className="h-1">Proyectos en operación, no renders.</h2>
          </div>
          <a href="SLF Energia - Caso Antofagasta.html" className="flex items-center gap-2" style={{ fontSize: 14, color: 'var(--pv-blue)', fontWeight: 500 }}>
            Ver todos los casos <Icon.ArrowSmall />
          </a>
        </div>

        <div className="grid grid-3">
          {cases.map((c, i) => (
            <Reveal key={c.title} delay={i * 100}>
              <a href={c.href} className="card card-hover" style={{ display: 'block', overflow: 'hidden' }}>
                <div className="ph-img" style={{ aspectRatio: '4/3' }}>
                  <span className="badge badge-onblue mono" style={{
                    position: 'absolute', top: 12, left: 12, background: 'rgba(11,37,69,.8)', color: '#fff', borderColor: 'transparent'
                  }}>{c.sector}</span>
                  <span className="ph-tag">{c.placeholder}</span>
                </div>
                <div style={{ padding: 24 }}>
                  <p className="mono" style={{ margin: 0, fontSize: 11, color: 'var(--slate)', letterSpacing: '.06em', textTransform: 'uppercase' }}>
                    {c.where}
                  </p>
                  <h3 className="h-3 mt-2 mb-4">{c.title}</h3>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, padding: '16px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
                    <div>
                      <div className="mono" style={{ fontSize: 22, fontWeight: 500, color: 'var(--pv-blue)', letterSpacing: '-0.02em' }}>
                        <CountUp to={c.kwp} />
                      </div>
                      <div className="stat-label">kWp instalados</div>
                    </div>
                    <div>
                      <div className="mono" style={{ fontSize: 22, fontWeight: 500, color: 'var(--pv-blue)', letterSpacing: '-0.02em' }}>
                        <CountUp to={c.saving} suffix="%" />
                      </div>
                      <div className="stat-label">ahorro mensual</div>
                    </div>
                    <div>
                      <div className="mono" style={{ fontSize: 22, fontWeight: 500, color: 'var(--pv-blue)', letterSpacing: '-0.02em' }}>
                        <CountUp to={c.payback} decimals={1} />
                      </div>
                      <div className="stat-label">años payback</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2 mt-4" style={{ color: 'var(--pv-blue)', fontSize: 14, fontWeight: 500 }}>
                    Leer caso completo <Icon.ArrowSmall />
                  </div>
                </div>
              </a>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ===========================================================
   Sector público y licitaciones
   =========================================================== */
function PublicSector() {
  return (
    <section id="sector-publico" className="section" style={{ background: 'var(--pv-blue)', color: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(ellipse at 90% 0%, rgba(255,184,0,.08), transparent 50%)'
      }} />
      <div className="container" style={{ position: 'relative' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'center' }} className="psec-grid">
          <div>
            <p className="eyebrow mb-3" style={{ color: 'rgba(255,255,255,.5)' }}>06 — Sector público</p>
            <h2 className="h-1" style={{ color: '#fff', marginBottom: 24 }}>
              Proveedor habilitado del Estado de Chile.
            </h2>
            <p className="lead" style={{ color: 'rgba(255,255,255,.78)' }}>
              SLF Energía es proveedor registrado en ChileCompra, participa activamente en licitaciones de Mercado Público y tiene experiencia con municipios, hospitales, FFAA y universidades.
            </p>

            <div className="grid grid-2 mt-8 mb-8" style={{ gap: 16 }}>
              {[
                { n: 23, l: 'Licitaciones adjudicadas' },
                { n: 14, l: 'Municipios atendidos' },
                { n: 6, l: 'Hospitales y CESFAM' },
                { n: 9, l: 'Universidades / institutos' },
              ].map((s) => (
                <div key={s.l} style={{
                  background: 'rgba(255,255,255,.04)',
                  border: '1px solid rgba(255,255,255,.12)',
                  borderRadius: 10,
                  padding: 16,
                }}>
                  <div className="stat-num on-blue" style={{ fontSize: 32 }}>
                    <CountUp to={s.n} />
                  </div>
                  <div className="stat-label on-blue">{s.l}</div>
                </div>
              ))}
            </div>

            <div className="flex items-center gap-3 flex-wrap">
              <a className="btn btn-primary" href="SLF Energia - Sector Publico.html">
                <Icon.Download /> Descargar dossier para licitaciones
              </a>
              <a className="btn btn-onblue" href="SLF Energia - Contacto.html">
                Hablar con licitaciones
              </a>
            </div>
          </div>

          <div>
            <div style={{
              background: 'rgba(255,255,255,.04)',
              border: '1px solid rgba(255,255,255,.12)',
              borderRadius: 14,
              padding: 28,
            }}>
              <div className="flex items-center justify-between mb-4">
                <p className="mono" style={{ margin: 0, fontSize: 11, letterSpacing: '.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,.5)' }}>
                  Dossier · Mercado Público
                </p>
                <span className="badge badge-onblue mono">v.2026.05</span>
              </div>
              <ul className="clean" style={{ color: 'rgba(255,255,255,.85)' }}>
                {[
                  'Resolución de habilitación ChileCompra',
                  'Certificaciones SEC vigentes',
                  'ISO 9001 / ISO 14001 + póliza de RC',
                  'Currículum técnico del equipo',
                  'Listado de proyectos públicos ejecutados',
                  'Garantías y fianzas estándar',
                  'Capacidad financiera y patrimonial',
                ].map((it) => (
                  <li key={it} className="flex items-center gap-3" style={{ borderBottom: '1px solid rgba(255,255,255,.08)', padding: '12px 0' }}>
                    <Icon.Check />
                    <span style={{ fontSize: 14 }}>{it}</span>
                  </li>
                ))}
              </ul>
              <p className="mono" style={{ color: 'rgba(255,255,255,.4)', fontSize: 11, marginTop: 16 }}>
                PDF · 42 páginas · actualizado mayo 2026
              </p>
            </div>
          </div>
        </div>
        <style>{`@media (max-width: 900px) { .psec-grid { grid-template-columns: 1fr !important; gap: 32px !important; } }`}</style>
      </div>
    </section>
  );
}

Object.assign(window, { Dashboard, Cases, PublicSector });
