/* ROI calculator — 3 sliders, live chart, monthly + annual + 3-year projection */

function ROI() {
  const [team, setTeam] = React.useState(10);
  const [hours, setHours] = React.useState(8);
  const [cost, setCost] = React.useState(28);
  const [automation, setAutomation] = React.useState(0.68);

  const weeklyHours = team * hours;
  const weeklyAutomated = weeklyHours * automation;
  const monthlyHours = weeklyAutomated * 4.33;
  const monthlySavings = monthlyHours * cost;
  const annualSavings = monthlySavings * 12;
  const threeYear = annualSavings * 3;
  // Inversión estimada ajustada a mercado español PYME: suelo 8.500€, ~750€ por persona en equipo
  const investmentEstimate = Math.max(8500, team * 750 + 4500);
  const paybackMonths = Math.max(1, Math.round(investmentEstimate / monthlySavings));
  const roiMultiple = (threeYear / investmentEstimate).toFixed(1);

  // chart data: 36 months, baseline flat vs Stratium growing
  const months = 36;
  const baseline = Array.from({length: months}, (_, i) => -monthlySavings * 0); // flat zero
  const stratium = Array.from({length: months}, (_, i) => {
    const ramp = Math.min(1, (i + 1) / 4); // ramp first 4 months
    return monthlySavings * (i + 1) * ramp - investmentEstimate;
  });
  const yMax = Math.max(...stratium, investmentEstimate);
  const yMin = Math.min(-investmentEstimate, ...stratium);
  const W = 580, H = 140, PAD = 8;
  const xScale = (i) => PAD + (i / (months - 1)) * (W - 2 * PAD);
  const yScale = (v) => PAD + (1 - (v - yMin) / (yMax - yMin || 1)) * (H - 2 * PAD);
  const zeroY = yScale(0);
  const breakEvenIdx = stratium.findIndex(v => v >= 0);
  const linePath = 'M ' + stratium.map((v, i) => `${xScale(i)} ${yScale(v)}`).join(' L ');
  const areaPath = linePath + ` L ${xScale(months-1)} ${zeroY} L ${xScale(0)} ${zeroY} Z`;
  const basePath = `M ${xScale(0)} ${zeroY} L ${xScale(months-1)} ${zeroY}`;

  const preset = (label, t, h, c) => () => { setTeam(t); setHours(h); setCost(c); };

  return (
    <section className="section" id="roi">
      <div className="section-inner">
        <span className="section-label reveal"><span className="num">§ 06</span>CALCULADORA ROI</span>
        <div className="section-head">
          <h2 className="section-title reveal reveal-delay-1">
            Traduce horas<br/>
            en <em>margen recuperado.</em>
          </h2>
          <p className="section-lede reveal reveal-delay-2">
            Ajusta tres variables de tu realidad. Proyección conservadora basada en 68% de automatización efectiva (mediana de 32 proyectos en España). Los números son tuyos, las hipótesis son transparentes.
          </p>
        </div>

        <div className="roi-panel reveal">
          <div className="roi-grid">
            <div className="roi-inputs">
              <div className="roi-input-group">
                <label>
                  <span>Equipo operativo</span>
                  <span className="val">{team} personas</span>
                </label>
                <input type="range" className="roi-slider" min="3" max="120" step="1" value={team} onChange={e => setTeam(+e.target.value)} />
                <div className="roi-presets">
                  <button className={team===3?'active':''} onClick={preset('',3,6,25)}>Micro</button>
                  <button className={team===10?'active':''} onClick={preset('',10,8,28)}>PYME</button>
                  <button className={team===25?'active':''} onClick={preset('',25,9,35)}>Scaleup</button>
                  <button className={team===60?'active':''} onClick={preset('',60,10,42)}>Mid-market</button>
                </div>
              </div>

              <div className="roi-input-group">
                <label>
                  <span>Horas repetitivas / persona / semana</span>
                  <span className="val">{hours}h</span>
                </label>
                <input type="range" className="roi-slider" min="2" max="25" step="1" value={hours} onChange={e => setHours(+e.target.value)} />
              </div>

              <div className="roi-input-group">
                <label>
                  <span>Coste medio hora (bruto + overhead)</span>
                  <span className="val">{cost} €</span>
                </label>
                <input type="range" className="roi-slider" min="18" max="95" step="1" value={cost} onChange={e => setCost(+e.target.value)} />
              </div>

              <div className="roi-input-group">
                <label>
                  <span>% automatización alcanzable</span>
                  <span className="val">{Math.round(automation * 100)}%</span>
                </label>
                <input type="range" className="roi-slider" min="0.4" max="0.92" step="0.01" value={automation} onChange={e => setAutomation(+e.target.value)} />
                <div style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--ink-3)', letterSpacing:'0.1em', marginTop:6}}>
                  MEDIANA OBSERVADA · 68% · RANGO 55–85%
                </div>
              </div>
            </div>

            <div>
              <div className="roi-results">
                <div className="roi-result-row hero-row">
                  <span className="k">Ahorro anual</span>
                  <span className="v">{Math.round(annualSavings).toLocaleString('es-ES')} €</span>
                </div>
                <div className="roi-result-row">
                  <span className="k">Ahorro mensual</span>
                  <span className="v">{Math.round(monthlySavings).toLocaleString('es-ES')} €</span>
                </div>
                <div className="roi-result-row">
                  <span className="k">Horas liberadas / mes</span>
                  <span className="v">{Math.round(monthlyHours).toLocaleString('es-ES')} h</span>
                </div>
                <div className="roi-result-row">
                  <span className="k">Inversión estimada</span>
                  <span className="v" style={{color:'var(--ink-2)'}}>{investmentEstimate.toLocaleString('es-ES')} €</span>
                </div>
                <div className="roi-result-row">
                  <span className="k">Payback</span>
                  <span className="v"><em>{paybackMonths}</em> <span style={{fontSize:14, color:'var(--ink-3)'}}>meses</span></span>
                </div>
                <div className="roi-result-row">
                  <span className="k">Retorno 36m</span>
                  <span className="v"><em>{roiMultiple}×</em></span>
                </div>
              </div>

              <div className="roi-chart">
                <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
                  <defs>
                    <linearGradient id="roi-grad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#4FD1E3" stopOpacity="0.4"/>
                      <stop offset="100%" stopColor="#4FD1E3" stopOpacity="0"/>
                    </linearGradient>
                  </defs>
                  <line className="axis" x1={PAD} y1={zeroY} x2={W-PAD} y2={zeroY}/>
                  <path className="area" d={areaPath}/>
                  <path className="baseline" d={basePath}/>
                  <path className="line" d={linePath}/>
                  {breakEvenIdx > 0 && (
                    <>
                      <line className="break-even" x1={xScale(breakEvenIdx)} y1={PAD} x2={xScale(breakEvenIdx)} y2={H-PAD}/>
                      <text x={xScale(breakEvenIdx) + 4} y={PAD + 10} fill="var(--gold)" fontFamily="var(--mono)" fontSize="9" letterSpacing="0.1em">BREAK-EVEN M{breakEvenIdx + 1}</text>
                    </>
                  )}
                </svg>
              </div>
              <div className="roi-chart-caption">
                <span>RETORNO NETO ACUMULADO · 36 MESES</span>
                <span className="leg">
                  <span><span className="ln acc"></span>STRATIUM</span>
                  <span><span className="ln sig"></span>STATUS QUO</span>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ROI });
