// Pyrovolt — BLAZE Simulator (mini + full)
// Click modules to install → distribute power across dispensers with vehicles.

const MODULE_OPTIONS = [
  { id: 'm80', kw: 80, name: '80 kW Module' },
  { id: 'm160', kw: 160, name: '160 kW Module' },
  { id: 'm320', kw: 320, name: '320 kW Module' },
];

const VEHICLE_PRESETS = [
  { id: 'car', icon: '🚗', name: 'Turismo', capacity: 77, maxKw: 250 },
  { id: 'van', icon: '🚐', name: 'Furgón', capacity: 110, maxKw: 150 },
  { id: 'truck', icon: '🚛', name: 'Camión', capacity: 540, maxKw: 1000 },
  { id: 'bus', icon: '🚌', name: 'Autobús', capacity: 350, maxKw: 500 },
];

function BlazeSimulator({ compact = false }) {
  const [modules, setModules] = React.useState([{ id: 1, kw: 160 }, { id: 2, kw: 160 }]);
  const [nextId, setNextId] = React.useState(3);
  const [dispensers, setDispensers] = React.useState([
    { id: 'D1', type: 'MCS', max: 1000, vehicle: null, soc: 20 },
    { id: 'D2', type: 'CCS2', max: 500, vehicle: null, soc: 20 },
    { id: 'D3', type: 'CCS2', max: 400, vehicle: null, soc: 20 },
  ]);
  const [tick, setTick] = React.useState(0);
  const [pickerFor, setPickerFor] = React.useState(null);

  const totalInstalled = modules.reduce((s, m) => s + m.kw, 0);

  // Active charging dispensers
  const active = dispensers.filter(d => d.vehicle && d.soc < 100);
  const requested = active.reduce((s, d) => {
    const socFactor = d.soc < 20 ? 1 : d.soc < 80 ? 1 : (100 - d.soc) / 20;
    return s + Math.min(d.vehicle.maxKw, d.max) * socFactor;
  }, 0);

  // Actual delivered (cap at installed)
  const deliveryCap = Math.min(requested, totalInstalled);
  const scaling = requested > 0 ? deliveryCap / requested : 1;

  const perDispenser = dispensers.map(d => {
    if (!d.vehicle || d.soc >= 100) return 0;
    const socFactor = d.soc < 20 ? 1 : d.soc < 80 ? 1 : (100 - d.soc) / 20;
    const want = Math.min(d.vehicle.maxKw, d.max) * socFactor;
    return want * scaling;
  });

  // Tick SoC forward
  React.useEffect(() => {
    const t = setInterval(() => {
      setDispensers(prev => prev.map((d, i) => {
        if (!d.vehicle || d.soc >= 100) return d;
        const kw = perDispenser[i];
        // delta per second: kw / capacity * 100 (percent), then scaled for demo speed
        const delta = (kw / d.vehicle.capacity) * 100 * 0.18;
        return { ...d, soc: Math.min(100, d.soc + delta) };
      }));
      setTick(x => x + 1);
    }, 200);
    return () => clearInterval(t);
  }, [perDispenser.join(',')]);

  const addModule = (kw) => {
    if (modules.length >= 5) return;
    setModules([...modules, { id: nextId, kw }]);
    setNextId(nextId + 1);
  };
  const removeModule = (id) => setModules(modules.filter(m => m.id !== id));

  const attachVehicle = (dId, v) => {
    setDispensers(prev => prev.map(d => d.id === dId ? { ...d, vehicle: v, soc: Math.floor(10 + Math.random() * 30) } : d));
    setPickerFor(null);
  };
  const detach = (dId) => setDispensers(prev => prev.map(d => d.id === dId ? { ...d, vehicle: null, soc: 20 } : d));

  const utilPct = totalInstalled ? (deliveryCap / totalInstalled) * 100 : 0;

  return (
    <div className="sim-cabinet" style={{ padding: compact ? 16 : 24 }}>
      {/* Header row: big delivery + stats */}
      <div style={{ display: 'flex', alignItems: 'center', gap: compact ? 16 : 32, flexWrap: 'wrap', paddingBottom: 16, borderBottom: '1px solid var(--dark-line)' }}>
        <div>
          <div className="h-eyebrow" style={{ color: 'var(--dark-fg-mute)', marginBottom: 6 }}>Entregando</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: compact ? 44 : 64, fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1, color: deliveryCap > 0 ? '#A78BFA' : 'var(--dark-fg-mute)' }}>
              {deliveryCap >= 1000 ? (deliveryCap/1000).toFixed(2) : Math.round(deliveryCap)}
            </span>
            <span className="t-mono" style={{ color: 'var(--dark-fg-dim)' }}>{deliveryCap >= 1000 ? 'MW' : 'kW'}</span>
          </div>
        </div>
        <div style={{ height: 40, width: 1, background: 'var(--dark-line)' }}/>
        <div>
          <div className="h-eyebrow" style={{ color: 'var(--dark-fg-mute)', marginBottom: 6 }}>Instalado</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: compact ? 22 : 28, fontWeight: 600, letterSpacing: '-0.02em' }}>
            {totalInstalled} kW
          </div>
        </div>
        <div>
          <div className="h-eyebrow" style={{ color: 'var(--dark-fg-mute)', marginBottom: 6 }}>Utilización</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 80 }}>
              <div className="sim-slider-track">
                <div className={`sim-slider-fill ${utilPct > 90 ? 'crit' : utilPct > 70 ? 'warn' : 'volt'}`} style={{ width: `${utilPct}%` }}/>
              </div>
            </div>
            <div className="t-mono" style={{ color: 'var(--dark-fg)' }}>{Math.round(utilPct)}%</div>
          </div>
        </div>
        {requested > totalInstalled && (
          <div style={{ marginLeft: 'auto', padding: '6px 12px', borderRadius: 999, background: 'rgba(245, 158, 11, 0.1)', border: '1px solid rgba(245, 158, 11, 0.3)', color: '#F59E0B', fontSize: 11, fontFamily: 'var(--font-mono)' }}>
            ⚠ Demanda supera potencia ({Math.round(requested)} kW requeridos)
          </div>
        )}
      </div>

      {/* Modules row */}
      <div style={{ padding: '18px 0', borderBottom: '1px solid var(--dark-line)' }}>
        <div className="h-eyebrow" style={{ color: 'var(--dark-fg-mute)', marginBottom: 10 }}>
          Cabina · Módulos de potencia ({modules.length}/5)
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {modules.map(m => (
            <div key={m.id} className="sim-module active" style={{ position: 'relative' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--dark-fg)' }}>{m.kw} <span style={{ fontSize: 11, color: 'var(--dark-fg-mute)', fontWeight: 400 }}>kW</span></div>
              <div className="t-mono" style={{ color: 'var(--dark-fg-mute)', fontSize: 10 }}>MÓDULO</div>
              <button onClick={() => removeModule(m.id)} style={{ position: 'absolute', top: 4, right: 4, width: 18, height: 18, borderRadius: '50%', background: 'rgba(239,68,68,0.15)', color: '#EF4444', fontSize: 10, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
            </div>
          ))}
          {modules.length < 5 && (
            <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
              {MODULE_OPTIONS.map(opt => (
                <button key={opt.id} onClick={() => addModule(opt.kw)}
                  style={{ padding: '10px 14px', border: '1px dashed var(--dark-line-strong)', borderRadius: 10, background: 'transparent', color: 'var(--dark-fg-dim)', fontSize: 12, fontFamily: 'var(--font-mono)' }}>
                  + {opt.kw} kW
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Bus flow */}
      <div style={{ padding: '18px 0 10px', display: 'flex', justifyContent: 'center' }}>
        {deliveryCap > 0 ? (
          <div className="busflow" style={{ width: '50%', height: 3 }}/>
        ) : (
          <div style={{ width: '50%', height: 3, background: 'var(--dark-line)', borderRadius: 2 }}/>
        )}
      </div>

      {/* Dispensers */}
      <div style={{ display: 'grid', gridTemplateColumns: compact ? 'repeat(3, 1fr)' : 'repeat(3, 1fr)', gap: 12 }}>
        {dispensers.map((d, i) => {
          const kw = perDispenser[i];
          const charging = d.vehicle && d.soc < 100 && kw > 0;
          return (
            <div key={d.id} className={`sim-dispenser ${charging ? 'charging' : ''}`}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <span className="t-mono" style={{ color: 'var(--dark-fg-mute)', fontSize: 10 }}>{d.id}</span>
                <span className="t-mono" style={{ padding: '2px 8px', background: 'var(--dark-line)', borderRadius: 4, color: 'var(--dark-fg-dim)', fontSize: 9 }}>{d.type} · {d.max >= 1000 ? '1 MW' : `${d.max}kW`}</span>
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: compact ? 30 : 38, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1, color: charging ? '#A78BFA' : 'var(--dark-fg-mute)', marginBottom: 4, animation: charging ? 'pulse 2s ease-in-out infinite' : 'none' }}>
                {kw >= 1000 ? (kw/1000).toFixed(2) : Math.round(kw)}
                <span style={{ fontSize: 11, color: 'var(--dark-fg-mute)', marginLeft: 4, fontWeight: 400 }}>{kw >= 1000 ? 'MW' : 'kW'}</span>
              </div>
              {/* Vehicle bay */}
              {d.vehicle ? (
                <div style={{ marginTop: 8, padding: 10, borderRadius: 8, background: 'var(--dark-bg)', position: 'relative' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                    <span style={{ fontSize: 20 }}>{d.vehicle.icon}</span>
                    <span className="t-mono" style={{ color: 'var(--dark-fg-dim)', fontSize: 10 }}>{d.vehicle.name}</span>
                    <button onClick={() => detach(d.id)} style={{ color: 'var(--dark-fg-mute)', fontSize: 11 }}>×</button>
                  </div>
                  <div className="sim-slider-track">
                    <div className={`sim-slider-fill ${d.soc < 30 ? 'crit' : d.soc < 70 ? 'warn' : 'volt'}`} style={{ width: `${d.soc}%` }}/>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
                    <span className="t-mono" style={{ color: 'var(--dark-fg-mute)', fontSize: 9 }}>SoC {Math.round(d.soc)}%</span>
                    {d.soc >= 100 ? (
                      <span className="t-mono" style={{ color: '#A78BFA', fontSize: 9 }}>✓ Completa</span>
                    ) : (
                      <span className="t-mono" style={{ color: 'var(--dark-fg-dim)', fontSize: 9 }}>
                        {kw > 0 ? `${Math.round((d.vehicle.capacity * (100 - d.soc) / 100) / kw * 60)} min` : '—'}
                      </span>
                    )}
                  </div>
                </div>
              ) : (
                <button onClick={() => setPickerFor(d.id)} style={{ marginTop: 8, width: '100%', padding: 14, border: '1.5px dashed var(--dark-line-strong)', borderRadius: 8, color: 'var(--dark-fg-mute)', fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.05em' }}>
                  + CONECTAR VEHÍCULO
                </button>
              )}
            </div>
          );
        })}
      </div>

      {/* Picker modal */}
      {pickerFor && (
        <div onClick={() => setPickerFor(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(8px)', zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={e => e.stopPropagation()} style={{ background: 'var(--dark-bg-soft)', border: '1px solid var(--dark-line-strong)', borderRadius: 16, padding: 24, maxWidth: 400, width: '90%', color: 'var(--dark-fg)' }}>
            <div className="h-eyebrow" style={{ marginBottom: 16, color: 'var(--dark-fg-dim)' }}>Elige vehículo</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {VEHICLE_PRESETS.map(v => (
                <button key={v.id} onClick={() => attachVehicle(pickerFor, v)}
                  style={{ padding: 16, background: 'var(--dark-bg-elev)', border: '1px solid var(--dark-line)', borderRadius: 12, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, color: 'var(--dark-fg)', transition: 'all 200ms' }}>
                  <span style={{ fontSize: 32 }}>{v.icon}</span>
                  <span style={{ fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 500 }}>{v.name}</span>
                  <span className="t-mono" style={{ color: 'var(--dark-fg-mute)', fontSize: 10 }}>{v.capacity} kWh · {v.maxKw} kW</span>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function SimulatorPage({ navigate }) {
  return (
    <section className="dark" style={{ minHeight: '100vh', paddingTop: 140, paddingBottom: 100 }}>
      <div className="container">
        <div style={{ marginBottom: 40 }}>
          <div className="h-eyebrow" style={{ marginBottom: 20 }}>Simulador BLAZE</div>
          <h1 className="h-title" style={{ marginBottom: 20, maxWidth: '22ch' }}>
            Diseña tu cabina.<br/>Conecta vehículos.<br/>Ve la potencia moverse.
          </h1>
          <p className="t-lead">
            Configura los módulos de potencia de tu estación BLAZE, conecta hasta 3 surtidores con vehículos reales
            y observa cómo Pyrovolt reparte la energía dinámicamente. Sin fórmulas. Sin hojas de cálculo.
          </p>
        </div>
        <BlazeSimulator/>
        <div style={{ marginTop: 40, display: 'flex', gap: 12 }}>
          <a className="btn btn-primary btn-lg" href="/contact" onClick={(e) => { e.preventDefault(); navigate('contact'); }}>
            Pedir propuesta para este setup
          </a>
          <a className="btn btn-ghost btn-lg" href="/chargers" onClick={(e) => { e.preventDefault(); navigate('chargers'); }}>
            Ver especificaciones técnicas
          </a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { BlazeSimulator, SimulatorPage });
