/* global React, Icon, Reveal */
const { useState: useStateCalc, useMemo: useMemoCalc } = React;

/* ===========================================================
   Calculadora interactiva de ahorro y dimensionamiento
   Lógica simplificada con valores plausibles para Chile.
   =========================================================== */

const REGIONS = [
  { v: 'arica', label: 'Arica y Parinacota', psh: 7.1 },
  { v: 'tarapaca', label: 'Tarapacá', psh: 7.4 },
  { v: 'antofagasta', label: 'Antofagasta', psh: 7.8 },
  { v: 'atacama', label: 'Atacama', psh: 7.5 },
  { v: 'coquimbo', label: 'Coquimbo', psh: 6.8 },
  { v: 'valparaiso', label: 'Valparaíso', psh: 5.6 },
  { v: 'metropolitana', label: 'Metropolitana', psh: 5.4 },
  { v: 'libertador', label: "O'Higgins", psh: 5.5 },
  { v: 'maule', label: 'Maule', psh: 5.2 },
  { v: 'nuble', label: 'Ñuble', psh: 5.0 },
  { v: 'biobio', label: 'Biobío', psh: 4.7 },
  { v: 'araucania', label: 'La Araucanía', psh: 4.3 },
  { v: 'rios', label: 'Los Ríos', psh: 4.0 },
  { v: 'lagos', label: 'Los Lagos', psh: 3.8 },
];

const SECTORS = [
  { v: 'mineria', label: 'Minería' },
  { v: 'retail', label: 'Retail / Multi-sucursal' },
  { v: 'manufactura', label: 'Manufactura' },
  { v: 'agro', label: 'Agroindustria' },
  { v: 'logistica', label: 'Logística' },
  { v: 'publico', label: 'Servicio público' },
  { v: 'otro', label: 'Otro' },
];

const PROJECT_TYPES = [
  { v: 'autoconsumo', label: 'Autoconsumo' },
  { v: 'inyeccion', label: 'Inyección a red' },
  { v: 'pmgd', label: 'PMGD' },
];

function fmtCLP(n) {
  if (n >= 1e9) return `$${(n / 1e9).toLocaleString('es-CL', { maximumFractionDigits: 2 })} mM`;
  if (n >= 1e6) return `$${(n / 1e6).toLocaleString('es-CL', { maximumFractionDigits: 1 })} M`;
  if (n >= 1e3) return `$${(n / 1e3).toLocaleString('es-CL', { maximumFractionDigits: 0 })} K`;
  return `$${n.toLocaleString('es-CL', { maximumFractionDigits: 0 })}`;
}
function fmtInt(n) { return n.toLocaleString('es-CL', { maximumFractionDigits: 0 }); }

function calc({ kwhMonth, region, projectType }) {
  const psh = (REGIONS.find((r) => r.v === region) || REGIONS[5]).psh;
  const yieldRatio = 0.78; // performance ratio
  const dailyKwh = kwhMonth / 30;
  // Size kWp to cover ~85% of daytime consumption baseline
  const coverage = projectType === 'pmgd' ? 1.4 : projectType === 'inyeccion' ? 1.1 : 0.85;
  const kWp = (dailyKwh * coverage) / (psh * yieldRatio);
  const m2 = kWp * 6; // ~6 m² per kWp
  const capexClpPerKwp = projectType === 'pmgd' ? 750_000 : 850_000;
  const capexLow = Math.round(kWp * capexClpPerKwp * 0.92);
  const capexHigh = Math.round(kWp * capexClpPerKwp * 1.08);
  const annualKwh = kWp * psh * 365 * yieldRatio;
  const tarifa = 130; // CLP/kWh promedio industrial
  const annualSavings = annualKwh * tarifa;
  const monthlySavings = annualSavings / 12;
  const payback = ((capexLow + capexHigh) / 2) / annualSavings;
  // TIR for ~25y project life — clamp to realistic range for Chile industrial PV (12–22%).
  const tir = Math.max(12, Math.min(22, 100 / payback));
  const co2 = annualKwh * 0.4 / 1000; // ton/year (0.4 kg/kWh factor for SEN-ish)
  return {
    kWp: Math.round(kWp * 10) / 10,
    m2: Math.round(m2),
    capexLow,
    capexHigh,
    monthlySavings: Math.round(monthlySavings),
    payback: Math.round(payback * 10) / 10,
    tir: Math.round(tir * 10) / 10,
    co2: Math.round(co2 * 10) / 10,
    annualKwh: Math.round(annualKwh),
  };
}

function Calculator({ onRequestPreFactibility }) {
  const [kwh, setKwh] = useStateCalc(50000);
  const [region, setRegion] = useStateCalc('valparaiso');
  const [sector, setSector] = useStateCalc('manufactura');
  const [ptype, setPtype] = useStateCalc('autoconsumo');

  const out = useMemoCalc(() => calc({ kwhMonth: kwh, region, projectType: ptype }), [kwh, region, ptype]);

  return (
    <section id="calculadora" className="section bg-blue-deep" style={{ position: 'relative', overflow: 'hidden' }}>
      {/* subtle grid */}
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        backgroundImage: 'linear-gradient(rgba(255,255,255,.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.04) 1px, transparent 1px)',
        backgroundSize: '80px 80px',
        maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 80%)',
        WebkitMaskImage: 'radial-gradient(ellipse at center, black 30%, transparent 80%)',
      }} />
      <div className="container" style={{ position: 'relative' }}>
        <div className="section-head">
          <div>
            <p className="eyebrow mb-3" style={{ color: 'rgba(255,255,255,.5)' }}>03 — Calculadora técnica</p>
            <h2 className="h-1" style={{ color: '#fff' }}>Dimensiona tu planta en 60 segundos.</h2>
          </div>
          <p style={{ color: 'rgba(255,255,255,.7)', maxWidth: 560 }}>
            Estimación referencial usando radiación solar real por región (NASA POWER) y tarifas industriales chilenas promedio.
            El estudio detallado requiere visita técnica.
          </p>
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 32,
        }} className="calc-grid">
          {/* INPUTS */}
          <div style={{
            background: 'rgba(0,0,0,.25)',
            border: '1px solid rgba(255,255,255,.08)',
            borderRadius: 14,
            padding: 28,
          }}>
            <div className="flex items-center justify-between mb-6">
              <p className="mono" style={{ color: 'var(--solar)', fontSize: 12, letterSpacing: '.08em', textTransform: 'uppercase', margin: 0 }}>
                INPUTS · Parámetros del proyecto
              </p>
              <span className="badge badge-onblue mono">Live</span>
            </div>

            {/* Consumo */}
            <div className="mb-6">
              <label className="label" style={{ color: 'rgba(255,255,255,.9)' }}>Consumo mensual</label>
              <div className="flex items-center gap-3 mb-3">
                <input
                  type="number"
                  className="input"
                  value={kwh}
                  onChange={(e) => setKwh(Math.max(10000, Math.min(1000000, Number(e.target.value) || 0)))}
                  style={{ maxWidth: 180, background: 'rgba(255,255,255,.06)', color: '#fff', border: '1px solid rgba(255,255,255,.18)' }}
                />
                <span className="mono" style={{ color: 'rgba(255,255,255,.6)', fontSize: 13 }}>kWh / mes</span>
              </div>
              <input
                type="range"
                className="slider"
                min={10000}
                max={1000000}
                step={5000}
                value={kwh}
                onChange={(e) => setKwh(Number(e.target.value))}
              />
              <div className="flex items-center justify-between mt-2" style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'rgba(255,255,255,.45)' }}>
                <span>10.000</span>
                <span>{fmtInt(kwh)} kWh</span>
                <span>1.000.000</span>
              </div>
            </div>

            {/* Region */}
            <div className="mb-6">
              <label className="label" style={{ color: 'rgba(255,255,255,.9)' }}>Región</label>
              <select
                className="select"
                value={region}
                onChange={(e) => setRegion(e.target.value)}
                style={{ background: 'rgba(255,255,255,.06)', color: '#fff', border: '1px solid rgba(255,255,255,.18)' }}
              >
                {REGIONS.map((r) => (
                  <option key={r.v} value={r.v} style={{ color: '#000' }}>{r.label}</option>
                ))}
              </select>
              <div className="help" style={{ color: 'rgba(255,255,255,.5)' }}>
                Radiación: {(REGIONS.find((r) => r.v === region) || REGIONS[5]).psh.toFixed(1)} kWh/m²/día (PSH)
              </div>
            </div>

            {/* Sector */}
            <div className="mb-6">
              <label className="label" style={{ color: 'rgba(255,255,255,.9)' }}>Sector industrial</label>
              <select
                className="select"
                value={sector}
                onChange={(e) => setSector(e.target.value)}
                style={{ background: 'rgba(255,255,255,.06)', color: '#fff', border: '1px solid rgba(255,255,255,.18)' }}
              >
                {SECTORS.map((s) => (
                  <option key={s.v} value={s.v} style={{ color: '#000' }}>{s.label}</option>
                ))}
              </select>
            </div>

            {/* Project type */}
            <div className="mb-2">
              <label className="label" style={{ color: 'rgba(255,255,255,.9)' }}>Tipo de proyecto</label>
              <div className="pill-row" style={{ width: '100%', display: 'flex' }}>
                {PROJECT_TYPES.map((p) => (
                  <button
                    key={p.v}
                    className={`pill ${ptype === p.v ? 'is-active' : ''}`}
                    onClick={() => setPtype(p.v)}
                    style={{ flex: 1 }}
                  >
                    {p.label}
                  </button>
                ))}
              </div>
              <div className="help" style={{ color: 'rgba(255,255,255,.5)' }}>
                {ptype === 'autoconsumo' && 'Autoconsumo: cubre demanda diurna, sin inyección significativa.'}
                {ptype === 'inyeccion' && 'Inyección a red: excedentes valorizados bajo Net Billing.'}
                {ptype === 'pmgd' && 'PMGD: hasta 9 MW con tarifas estabilizadas a nodo.'}
              </div>
            </div>
          </div>

          {/* OUTPUTS */}
          <div>
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(2, 1fr)',
              gap: 16,
            }}>
              <OutputCard
                tag="kWp"
                value={out.kWp.toLocaleString('es-CL')}
                suffix=" kWp"
                label="Potencia recomendada"
                highlight
              />
              <OutputCard
                tag="m²"
                value={fmtInt(out.m2)}
                suffix=" m²"
                label="Superficie estimada"
                helper="techo o terreno"
              />
              <OutputCard
                tag="CAPEX"
                value={`${fmtCLP(out.capexLow)} – ${fmtCLP(out.capexHigh)}`}
                label="Inversión estimada (CLP)"
                helper="rango referencial"
              />
              <OutputCard
                tag="AHORRO"
                value={fmtCLP(out.monthlySavings)}
                suffix=" / mes"
                label="Ahorro mensual estimado"
                helper="CLP, tarifa industrial 130 CLP/kWh"
              />
              <OutputCard
                tag="PAYBACK"
                value={out.payback.toLocaleString('es-CL')}
                suffix=" años"
                label="Recuperación de inversión"
                highlight
              />
              <OutputCard
                tag="TIR"
                value={out.tir.toFixed(1)}
                suffix="%"
                label="Tasa interna de retorno"
              />
              <OutputCard
                tag="CO₂"
                value={out.co2.toLocaleString('es-CL')}
                suffix=" t/año"
                label="Emisiones evitadas"
                green
              />
              <OutputCard
                tag="GEN"
                value={fmtInt(Math.round(out.annualKwh / 1000))}
                suffix=" MWh/año"
                label="Generación estimada"
              />
            </div>

            <div className="mt-6 flex items-center justify-between" style={{
              padding: 20, borderRadius: 12,
              background: 'linear-gradient(135deg, rgba(255,184,0,.12) 0%, rgba(255,184,0,.05) 100%)',
              border: '1px solid rgba(255,184,0,.35)',
              flexWrap: 'wrap', gap: 16
            }}>
              <div>
                <p style={{ margin: 0, color: '#fff', fontSize: 16, fontWeight: 600 }}>¿Quieres una pre-factibilidad detallada?</p>
                <p style={{ margin: '4px 0 0', color: 'rgba(255,255,255,.65)', fontSize: 13 }}>
                  Memoria PVsyst, layout preliminar, TIR/VPN auditable y estructura financiera. Entrega en 5 días hábiles.
                </p>
              </div>
              <button className="btn btn-primary" onClick={() => onRequestPreFactibility(out)}>
                Solicitar pre-factibilidad <Icon.Arrow />
              </button>
            </div>

            <p className="mono" style={{ color: 'rgba(255,255,255,.4)', fontSize: 11, marginTop: 16 }}>
              Disclaimer: cifras referenciales basadas en datos NASA POWER y tarifas industriales chilenas promedio (~130 CLP/kWh).
              Estudio detallado requiere análisis de perfil horario, contrato eléctrico vigente y levantamiento técnico de sitio.
            </p>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 960px) {
          .calc-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

function OutputCard({ tag, value, suffix = '', label, helper, highlight, green }) {
  return (
    <div className={`calc-output ${highlight ? 'highlight' : ''}`}>
      <div className="flex items-center justify-between mb-3">
        <span className="badge badge-onblue mono">{tag}</span>
        {green && <Icon.Leaf />}
      </div>
      <div style={{
        fontFamily: 'var(--mono)',
        fontSize: 28,
        fontWeight: 500,
        letterSpacing: '-0.02em',
        color: highlight ? 'var(--solar)' : '#fff',
        lineHeight: 1.1,
      }}>
        {value}<span style={{ fontSize: 14, color: 'rgba(255,255,255,.5)', fontWeight: 400 }}>{suffix}</span>
      </div>
      <div className="stat-label on-blue" style={{ marginTop: 6 }}>{label}</div>
      {helper && <div className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,.4)', marginTop: 4, letterSpacing: '.04em', textTransform: 'uppercase' }}>{helper}</div>}
    </div>
  );
}

Object.assign(window, { Calculator });
