// World Cup Weather Ops — shared helpers & atoms (exposed on window).
// Class-based + cqw-sized (see /events.css), mirroring the digital-signs
// approach. Dynamic values (flag image, temperatures, threshold colors) stay
// inline in JS; layout + type live in the stylesheet.

const DASH = '—';
const wcWxSrc = (code) => `/assets/wx/${String(code).padStart(2, '0')}.svg`;

const WCCtx = React.createContext({ unit: 'F', accent: '#F05514' });
const useWC = () => React.useContext(WCCtx);

const teamInfo = (code) => (window.WC && window.WC.teams && window.WC.teams[code]) || { code, name: code, flag: null };

function wcConvert(f, unit) {
  if (f == null || Number.isNaN(f)) return null;
  return unit === 'C' ? Math.round((f - 32) * 5 / 9) : Math.round(f);
}

// Big temperature with muted degree+unit. Renders "—" when value is null.
function Temp({ f, unit = 'F', showUnit = true }) {
  const v = wcConvert(f, unit);
  return (
    <span className="aw-events__temp">
      <span className="aw-events__temp-val">{v == null ? DASH : `${v}°`}</span>
      {showUnit && v != null && <span className="aw-events__temp-unit">{unit}</span>}
    </span>
  );
}

// `cqw` sizes the icon relative to the 16:9 stage width.
function WxIcon({ code, cqw = 2.08 }) {
  const style = { width: `${cqw}cqw`, height: `${cqw}cqw`, display: 'block' };
  if (code == null) return <span style={style} />;
  return <img className="aw-events__wxicon" src={wcWxSrc(code)} alt="" style={style} />;
}

// Real FIFA square flag image; neutral chip fallback if missing/failed.
function FlagChip({ code, size = 'md' }) {
  const info = teamInfo(code);
  const [failed, setFailed] = React.useState(false);
  const cls = `aw-events__flag aw-events__flag--${size}`;
  if (!info.flag || failed) {
    return <span className={cls}><span className="aw-events__flag-fallback">{code}</span></span>;
  }
  return (
    <span className={cls}>
      <img src={info.flag} alt={info.name || code} onError={() => setFailed(true)} />
    </span>
  );
}

function TeamLine({ code, big }) {
  return (
    <span className="aw-events__team">
      <FlagChip code={code} size={big ? 'lg' : 'md'} />
      <span className="aw-events__team-code">{code}</span>
    </span>
  );
}

// tiny labelled stat (renders "—" for null values). `color` is data-driven.
function Stat({ label, value, sub, color = '#fff' }) {
  const empty = value == null || value === '';
  return (
    <div className="aw-events__stat">
      <span className="aw-events__stat-label">{label}</span>
      <span className="aw-events__stat-value" style={{ color: empty ? 'rgba(255,255,255,0.4)' : color }}>
        {empty ? DASH : value}
        {!empty && sub && <span className="aw-events__stat-sub">{sub}</span>}
      </span>
    </div>
  );
}

// horizontal meter (0..100) — color is data-driven.
function Meter({ pct, color, h = 4 }) {
  return (
    <span style={{ display: 'block', width: '100%', height: h, borderRadius: 999, background: 'rgba(255,255,255,0.10)', overflow: 'hidden' }}>
      <span style={{ display: 'block', width: `${Math.max(2, Math.min(100, pct))}%`, height: '100%', background: color, borderRadius: 999 }} />
    </span>
  );
}

function Drop({ cqw = 0.7 }) {
  return <img src="/assets/rainfall.svg" alt="" style={{ width: `${cqw}cqw`, height: `${cqw}cqw`, display: 'block', opacity: 0.85 }} />;
}

// hourly micro-strip (temp + icon + pop)
function HourStrip({ hourly, unit }) {
  if (!hourly || hourly.length === 0) return null;
  return (
    <div className="aw-events__hstrip">
      {hourly.map((h, i) => {
        const t = wcConvert(h.temp, unit);
        return (
          <div key={i} className="aw-events__hcol">
            <div className="aw-events__htime">{h.t}</div>
            <div className="aw-events__hicon"><WxIcon code={h.code} cqw={1.8} /></div>
            <div className="aw-events__htemp">{t == null ? DASH : `${t}°`}</div>
            <div className="aw-events__hpop"><Drop cqw={0.7} />{h.pop == null ? DASH : `${h.pop}%`}</div>
          </div>
        );
      })}
    </div>
  );
}

function kickText(m) { return `${m.time} ${m.ampm} ${m.tz}`.trim(); }

Object.assign(window, {
  WCCtx, useWC, wcConvert, wcWxSrc, DASH, teamInfo,
  Temp, WxIcon, FlagChip, TeamLine, Stat, Meter, Drop, HourStrip, kickText,
});
