/* Gridea — interactive forecast widget */
const { useState: useStateF, useMemo: useMemoF } = React;

// Baseline monthly consumption profile (MWh) — degree-day driven
// Each month has an inferred heating share and cooling share
const BASELINE_MONTHS = [
  { name: 'Jaan', mwh: 280, heat: 0.65, cool: 0.0 },
  { name: 'Veebr', mwh: 250, heat: 0.62, cool: 0.0 },
  { name: 'Märts', mwh: 210, heat: 0.55, cool: 0.0 },
  { name: 'Apr',  mwh: 160, heat: 0.32, cool: 0.0 },
  { name: 'Mai',  mwh: 130, heat: 0.12, cool: 0.05 },
  { name: 'Juuni', mwh: 110, heat: 0.0, cool: 0.18 },
  { name: 'Juuli', mwh: 105, heat: 0.0, cool: 0.25 },
  { name: 'Aug',  mwh: 110, heat: 0.0, cool: 0.22 },
  { name: 'Sept', mwh: 140, heat: 0.18, cool: 0.08 },
  { name: 'Okt',  mwh: 180, heat: 0.42, cool: 0.0 },
  { name: 'Nov',  mwh: 230, heat: 0.58, cool: 0.0 },
  { name: 'Dets', mwh: 270, heat: 0.63, cool: 0.0 },
];
const BASELINE_PRICE = 102.5; // €/MWh blended

function ForecastWidget() {
  const [winterDelta, setWinterDelta] = useStateF(0);  // °C deviation from normal
  const [summerDelta, setSummerDelta] = useStateF(0);
  const [scenario, setScenario] = useStateF('typical');

  // Apply scenario presets
  const applyScenario = (s) => {
    setScenario(s);
    if (s === 'typical') { setWinterDelta(0); setSummerDelta(0); }
    else if (s === 'cold') { setWinterDelta(-4); setSummerDelta(-2); }
    else if (s === 'hot') { setWinterDelta(3); setSummerDelta(4); }
    else if (s === 'extreme') { setWinterDelta(-6); setSummerDelta(5); }
  };

  // Calculate adjusted consumption per month
  // Each °C colder in winter → +5% on heating portion; each °C warmer in summer → +6% on cooling
  const monthData = useMemoF(() => {
    return BASELINE_MONTHS.map(m => {
      // Heating responds inversely to winter temp (colder = more heating)
      const heatMultiplier = 1 + (-winterDelta) * 0.05;
      // Cooling responds to summer temp (warmer = more cooling)
      const coolMultiplier = 1 + summerDelta * 0.06;
      const heatPart = m.mwh * m.heat * heatMultiplier;
      const coolPart = m.mwh * m.cool * coolMultiplier;
      const basePart = m.mwh * (1 - m.heat - m.cool);
      const adjusted = basePart + heatPart + coolPart;
      return { ...m, adjusted };
    });
  }, [winterDelta, summerDelta]);

  const totalBase = useMemoF(() => BASELINE_MONTHS.reduce((s, m) => s + m.mwh, 0), []);
  const totalAdj = useMemoF(() => monthData.reduce((s, m) => s + m.adjusted, 0), [monthData]);
  const costBase = totalBase * BASELINE_PRICE;
  const costAdj = totalAdj * BASELINE_PRICE;
  const deltaCost = costAdj - costBase;
  const deltaPct = (costAdj - costBase) / costBase * 100;

  const maxBar = Math.max(...monthData.map(m => Math.max(m.adjusted, m.mwh))) * 1.05;

  const winterLabel = winterDelta === 0 ? 'Normaalne' : winterDelta < 0 ? `${winterDelta}°C külmem` : `+${winterDelta}°C soojem`;
  const summerLabel = summerDelta === 0 ? 'Normaalne' : summerDelta < 0 ? `${summerDelta}°C jahedam` : `+${summerDelta}°C kuumem`;

  const winterCls = winterDelta < -1 ? 'cold' : winterDelta > 1 ? 'warm' : '';
  const summerCls = summerDelta > 1 ? 'warm' : summerDelta < -1 ? 'cold' : '';

  return (
    <div className="forecast-widget">
      <div className="forecast-header">
        <div>
          <div style={{ fontSize: 12, color: 'var(--d-subtle)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 8 }}>
            Eelarve · 2027 prognoos
          </div>
          <div className="forecast-total">
            €{Math.round(costAdj).toLocaleString('et-EE')}<span className="unit"></span>
          </div>
          <div className="forecast-baseline">
            Baseline €{Math.round(costBase).toLocaleString('et-EE')}
            <span className={`delta ${Math.abs(deltaPct) < 0.5 ? 'flat' : deltaPct > 0 ? 'up' : 'down'}`}>
              {deltaPct > 0 ? '+' : ''}{deltaPct.toFixed(1)}%
              {' '}({deltaCost > 0 ? '+' : '−'}€{Math.abs(Math.round(deltaCost)).toLocaleString('et-EE')})
            </span>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 12, color: 'var(--d-subtle)', marginBottom: 8, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>Stsenaarium</div>
          <div className="scenario-chips">
            <button className={`chip ${scenario === 'typical' ? 'active' : ''}`} onClick={() => applyScenario('typical')}>Tüüpiline aasta</button>
            <button className={`chip ${scenario === 'cold' ? 'active' : ''}`} onClick={() => applyScenario('cold')}>Külm talv</button>
            <button className={`chip ${scenario === 'hot' ? 'active' : ''}`} onClick={() => applyScenario('hot')}>Kuum suvi</button>
            <button className={`chip ${scenario === 'extreme' ? 'active' : ''}`} onClick={() => applyScenario('extreme')}>Ekstreemne aasta</button>
          </div>
        </div>
      </div>

      <div className="forecast-sliders">
        <div className="slider-row">
          <div className="slider-row-head">
            <div>
              <div className="slider-label">
                <GIcon name="snow" size={14} className="" />{' '}
                Talve temperatuur
              </div>
              <div className="slider-sub">Mõjutab kütteenergiat (sept–aprill)</div>
            </div>
            <div className={`slider-val ${winterCls}`}>{winterDelta > 0 ? '+' : ''}{winterDelta}°C</div>
          </div>
          <input
            type="range" min={-8} max={6} step={1} value={winterDelta}
            className="slider-input"
            onChange={(e) => { setWinterDelta(+e.target.value); setScenario('custom'); }}
          />
          <div className="slider-track-marks">
            <span>−8°C</span><span>−4°C</span><span style={{ color: 'var(--d-muted)' }}>0</span><span>+3°C</span><span>+6°C</span>
          </div>
          <div style={{ fontSize: 12, color: 'var(--d-muted)' }}>{winterLabel} vs ajalooline keskmine</div>
        </div>

        <div className="slider-row">
          <div className="slider-row-head">
            <div>
              <div className="slider-label">
                <GIcon name="sun" size={14}/>{' '}
                Suve temperatuur
              </div>
              <div className="slider-sub">Mõjutab jahutusenergiat (juuni–aug)</div>
            </div>
            <div className={`slider-val ${summerCls}`}>{summerDelta > 0 ? '+' : ''}{summerDelta}°C</div>
          </div>
          <input
            type="range" min={-4} max={8} step={1} value={summerDelta}
            className="slider-input"
            onChange={(e) => { setSummerDelta(+e.target.value); setScenario('custom'); }}
          />
          <div className="slider-track-marks">
            <span>−4°C</span><span>−2°C</span><span style={{ color: 'var(--d-muted)' }}>0</span><span>+4°C</span><span>+8°C</span>
          </div>
          <div style={{ fontSize: 12, color: 'var(--d-muted)' }}>{summerLabel} vs ajalooline keskmine</div>
        </div>
      </div>

      <div style={{ position: 'relative' }}>
        <div style={{ fontSize: 12, color: 'var(--d-muted)', marginBottom: 4 }}>
          Kuine tarbimine · MWh
        </div>
        {/* Scroll wrapper: 12 month columns have an intrinsic ~507px minimum, so on
            a phone the chart scrolls inside this box instead of dragging the page. */}
        <div className="forecast-chart-scroll">
        <div className="forecast-chart">
          <div className="fc-axis">
            <div className="fc-axis-line"/>
            <div className="fc-axis-line"/>
            <div className="fc-axis-line"/>
            <div className="fc-axis-line"/>
            <div className="fc-axis-line"/>
          </div>
          {monthData.map((m, i) => {
            const adjPct = (m.adjusted / maxBar) * 100;
            const basePct = (m.mwh / maxBar) * 100;
            const isWinter = m.heat > 0.3;
            const isSummer = m.cool > 0.1;
            const cls = m.adjusted > m.mwh + 4 ? (isWinter ? 'cold' : isSummer ? 'warm' : '') :
                        m.adjusted < m.mwh - 4 ? (isWinter ? 'warm' : isSummer ? 'cold' : '') : '';
            return (
              <div className="fc-col" key={m.name}>
                <div className="fc-bar-wrap">
                  <div className="fc-bar-baseline" style={{ bottom: `${basePct}%` }}/>
                  <div className={`fc-bar ${cls}`} style={{ height: `${adjPct}%` }}>
                    {/* Value badge for cold/warm months */}
                    {Math.abs(m.adjusted - m.mwh) > 6 && (
                      <div style={{
                        position: 'absolute', top: -22, left: '50%', transform: 'translateX(-50%)',
                        fontSize: 10, fontFamily: 'var(--mono)', whiteSpace: 'nowrap',
                        color: m.adjusted > m.mwh ? 'var(--red)' : 'var(--green)', fontWeight: 600,
                      }}>
                        {m.adjusted > m.mwh ? '+' : '−'}{Math.abs(Math.round(m.adjusted - m.mwh))}
                      </div>
                    )}
                  </div>
                </div>
                <div className="fc-month-label">{m.name}</div>
              </div>
            );
          })}
        </div>
        </div>
      </div>

      <div className="forecast-legend">
        <span className="forecast-legend-item">
          <span className="forecast-legend-swatch" style={{ background: 'var(--brand)' }}/>
          Prognoositav tarbimine
        </span>
        <span className="forecast-legend-item">
          <span className="forecast-legend-swatch" style={{ background: 'var(--d-text)', opacity: 0.5, height: 2, marginTop: 5 }}/>
          Tüüpiline aasta (baseline)
        </span>
        <span className="forecast-legend-item">
          <span className="forecast-legend-swatch" style={{ background: 'oklch(0.72 0.13 240)' }}/>
          Külm kuu
        </span>
        <span className="forecast-legend-item">
          <span className="forecast-legend-swatch" style={{ background: 'var(--amber)' }}/>
          Kuum kuu
        </span>
        <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 11 }}>
          {Math.round(totalAdj).toLocaleString('et-EE')} MWh · €{BASELINE_PRICE.toFixed(2)}/MWh
        </span>
      </div>
    </div>
  );
}

window.ForecastWidget = ForecastWidget;
