/* global React, fmtNum, Units, WeatherData */

// =========================================================
// „Soulad s předpovědí“ (was „Sedí předpověď?“ — Lukáš 21. 10.: no „sedí“) — how well the forecast (the model in use) matches
// what the station measures right now. Written so anyone gets it:
//   • a verdict on top: how many of the five quantities match
//   • per quantity: what the station measures (big) and what the forecast
//     expected for this hour (small), plus a plain-word badge:
//       „v souladu“ (within tolerance) or „o 1,6 °C tepleji“ / „o 2,7 m/s slabší“
//   Narrow tiles stay one line per quantity (CSS steps on the tile width):
//   ≤ 380 px a difference shrinks to arrow + number („↓ 2,4“), ≤ 300 px the
//   quantity icons go and „v souladu“ is just ✓ — the full wording is the
//   badge's tooltip.
// Station side = mean of the last 60 min (gusts = peak), the same shape
// the models forecast (hourly mean + peak gust); falls back to the latest
// reading. Δ = station − forecast.
// =========================================================

window.CompareWidget = function CompareWidget({ station, hourly, config = {} }) {
  if (!hourly || !hourly.length) return <div className="muted">Načítání…</div>;
  const h0 = hourly[0];

  const avg = (vals) => {
    const xs = vals.filter(v => v != null && !isNaN(v));
    return xs.length ? xs.reduce((s, v) => s + v, 0) / xs.length : null;
  };
  const maxOf = (vals) => {
    const xs = vals.filter(v => v != null && !isNaN(v));
    return xs.length ? Math.max(...xs) : null;
  };
  const meas = station?.measurements || [];
  const recent = meas.filter(m => m.time && m.time.getTime() >= Date.now() - 3600000);
  const L = station?.latest || null;
  const sCur = recent.length ? {
    temp: avg(recent.map(m => m.temp)), humidity: avg(recent.map(m => m.humidity)),
    pressure: avg(recent.map(m => m.pressure)), wind: avg(recent.map(m => m.wind)),
    gust: maxOf(recent.map(m => m.gust)),
  } : L ? {
    temp: L.TeplotaVnejsi, humidity: L.VlhkostVnejsi, pressure: L.TlakRel, wind: L.Vitr, gust: L.VitrNarazy,
  } : null;

  if (!sCur) {
    return (
      <div className="fit-empty">
        <i className="bi bi-broadcast-pin" aria-hidden="true"></i>
        Stanice teď neposílá data — není s čím předpověď porovnat.
      </div>
    );
  }

  const windU = Units.windLabel();
  const id = v => v;
  // tol = still counts as „v souladu“ (WeatherData.SOULAD_TOL, base units —
  // the same numbers AUTO ranks the models by); more/less = how to say the
  // difference, shown in the chosen units.
  const TOL = WeatherData.SOULAD_TOL;
  const ROWS = [
    { key: 'temp',     label: 'Teplota',      icon: 'thermometer-half', f: h0.temp,     s: sCur.temp,     dec: 1, conv: id,         unit: '°C',  more: 'tepleji',  less: 'chladněji' },
    { key: 'humidity', label: 'Vlhkost',      icon: 'droplet-half',     f: h0.humidity, s: sCur.humidity, dec: 0, conv: id,         unit: '%',   more: 'vlhčeji',  less: 'sušeji' },
    { key: 'pressure', label: 'Tlak',         icon: 'speedometer2',     f: h0.pressure, s: sCur.pressure, dec: 0, conv: id,         unit: 'hPa', more: 'výš',      less: 'níž' },
    { key: 'wind',     label: 'Vítr',         icon: 'wind',             f: h0.wind,     s: sCur.wind,     dec: 1, conv: Units.wind, unit: windU, more: 'silnější', less: 'slabší' },
    { key: 'gust',     label: 'Nárazy větru', icon: 'tropical-storm',   f: h0.gust,     s: sCur.gust,     dec: 1, conv: Units.wind, unit: windU, more: 'silnější', less: 'slabší' },
  ];
  const ok = (v) => v != null && !isNaN(v);
  const rows = ROWS.map(r => {
    if (!ok(r.f) || !ok(r.s)) return { ...r, verdict: null };
    const d = r.conv(r.s) - r.conv(r.f);
    if (Math.abs(r.s - r.f) <= TOL[r.key]) return { ...r, verdict: { k: 'ok', txt: 'v souladu', short: null } };
    return { ...r, verdict: { k: d > 0 ? 'up' : 'down', short: window.czNum(Math.abs(d), r.dec),
                              txt: `o ${window.czNum(Math.abs(d), r.dec)} ${r.unit === '%' ? '%' : r.unit} ${d > 0 ? r.more : r.less}` } };
  });
  const judged = rows.filter(r => r.verdict);
  const good = judged.filter(r => r.verdict.k === 'ok').length;
  const mood = !judged.length ? null : good === judged.length ? 'great' : good >= judged.length - 1 ? 'good' : good >= judged.length / 2 ? 'fair' : 'poor';
  const moodText = { great: 'Měření je v souladu s předpovědí', good: 'Měření je téměř v souladu s předpovědí',
    fair: 'Měření je s předpovědí v souladu jen zčásti', poor: 'Měření se od předpovědi liší' }[mood];

  return (
    <div className="fit-widget">
      {mood && (
        <div className={`fit-verdict is-${mood}`}>
          <i className={`bi bi-${mood === 'great' || mood === 'good' ? 'check2-circle' : mood === 'fair' ? 'dash-circle' : 'x-circle'}`} aria-hidden="true"></i>
          <span className="fit-verdict-txt"><b>{moodText}</b><small>{good} z {judged.length} veličin v toleranci · stanice za poslední hodinu</small></span>
        </div>
      )}
      <ul className="fit-list">
        {rows.map(r => (
          <li key={r.key} className="fit-row"
              title={`${r.label}: stanice ${fmtNum(ok(r.s) ? r.conv(r.s) : null, r.dec)} ${r.unit}, předpověď na tuto hodinu ${fmtNum(ok(r.f) ? r.conv(r.f) : null, r.dec)} ${r.unit}`}>
            <i className={`bi bi-${r.icon} fit-ico`} aria-hidden="true"></i>
            <span className="fit-name">{r.label}<small>čekalo se {fmtNum(ok(r.f) ? r.conv(r.f) : null, r.dec)} {r.unit}</small></span>
            <span className="fit-val">{fmtNum(ok(r.s) ? r.conv(r.s) : null, r.dec)}<em>{r.unit}</em></span>
            {r.verdict
              ? <span className={`fit-badge is-${r.verdict.k}`} title={r.verdict.txt}>
                  <i className={`bi bi-${r.verdict.k === 'ok' ? 'check-lg' : r.verdict.k === 'up' ? 'arrow-up' : 'arrow-down'}`} aria-hidden="true"></i>
                  <span className="fb-long">{r.verdict.txt}</span>
                  {r.verdict.short != null && <span className="fb-short">{r.verdict.short}</span>}
                </span>
              : <span className="fit-badge is-na">bez dat</span>}
          </li>
        ))}
      </ul>
    </div>
  );
};
