/* Weather Squatch — overlay UI (React). Warm storybook chrome that floats over
   the scene. All copy is in the Squatch's friendly voice. */

const { useState: _useStateU, useEffect: _useEffectU, useRef: _useRefU } = React;

function TitleCard({ onStart, visible }) {
  return (
    <div className={"ws-center ws-fade " + (visible ? "in" : "out")} style={{ pointerEvents: visible ? "auto" : "none" }}>
      <div className="ws-title-wrap">
        <div className="ws-kicker">A LIVE FORECAST, DELIVERED BY A LARGE FRIEND</div>
        <h1 className="ws-title">Weather<span>Squatch</span></h1>
        <p className="ws-tag">Somewhere past the treeline, someone has been keeping an eye on the sky for you.</p>
        <button className="ws-btn ws-btn-lg" onClick={onStart}>Wander in →</button>
      </div>
    </div>
  );
}

function ZipPanel({ onSubmit, busy, error, visible }) {
  const [zip, setZip] = _useStateU("");
  const ref = _useRefU(null);
  _useEffectU(() => { if (visible && ref.current) setTimeout(() => ref.current.focus(), 400); }, [visible]);
  const ok = /^\d{5}$/.test(zip);
  const submit = (e) => { e.preventDefault(); if (ok && !busy) onSubmit(zip); };

  return (
    <div className={"ws-greet ws-fade " + (visible ? "in" : "out")} style={{ pointerEvents: visible ? "auto" : "none" }}>
      <div className="ws-bubble">
        <p className="ws-bubble-text">
          {error
            ? (error === "404"
              ? "Hmm. Squatch can't find that place, little buddy. Try another five numbers?"
              : "Well, shoot. Somethin' got tangled in the trees. Let's try that again?")
            : "Well hello there, little buddy! Where you from?"}
        </p>
        <form className="ws-zipform" onSubmit={submit}>
          <input
            ref={ref}
            className={"ws-zip" + (error ? " err" : "")}
            inputMode="numeric"
            pattern="\d{5}"
            maxLength={5}
            placeholder="ZIP"
            value={zip}
            disabled={busy}
            onChange={(e) => setZip(e.target.value.replace(/\D/g, "").slice(0, 5))}
            aria-label="5-digit ZIP code"
          />
          <button className="ws-btn" type="submit" disabled={!ok || busy}>
            {busy ? "Reading the signs…" : "Tell me"}
          </button>
        </form>
      </div>
    </div>
  );
}

function LoadingHint({ visible }) {
  const lines = [
    "Reading the signs…",
    "Consulting the clouds…",
    "Listening to the pond…",
    "Asking the wind politely…",
    "Squatch is thinking real hard.",
  ];
  const [i, setI] = _useStateU(0);
  _useEffectU(() => {
    if (!visible) return;
    const t = setInterval(() => setI((x) => (x + 1) % lines.length), 2400);
    return () => clearInterval(t);
  }, [visible]);
  return (
    <div className={"ws-loading ws-fade " + (visible ? "in" : "out")}>
      <div className="ws-loading-dot"></div>
      <span>{lines[i]}</span>
    </div>
  );
}

function Captions({ words, revealed, visible }) {
  // Sliding lower-third window: the words just spoken, plus a couple upcoming
  // shown faint — keeps it to ~2 readable lines instead of the whole script.
  const WINDOW = 14;
  const start = Math.max(0, Math.min(revealed, words.length) - WINDOW);
  const spoken = words.slice(start, revealed);
  const upcoming = words.slice(revealed, revealed + 3);
  return (
    <div className={"ws-captions ws-fade " + (visible ? "in" : "out")}>
      <p className="ws-caption-line">
        {spoken.map((w, i) => (<span key={"s" + (start + i)} className="ws-word on">{w} </span>))}
        {upcoming.map((w, i) => (<span key={"u" + (revealed + i)} className="ws-word">{w} </span>))}
      </p>
    </div>
  );
}

function ForecastCards({ city, state, periods }) {
  return (
    <div className="ws-forecast">
      <div className="ws-forecast-head">Your forecast for <strong>{city}, {state}</strong></div>
      <div className="ws-cards">
        {(periods || []).map((p, i) => (
          <div className="ws-card" key={i} style={{ transitionDelay: (i * 90) + "ms" }}>
            <div className="ws-card-name">{p.name}</div>
            <div className="ws-card-temp">{p.temperature}<span>°{p.temperatureUnit}</span></div>
            <div className="ws-card-cond">{p.shortForecast}</div>
            <div className="ws-card-wind">{p.windSpeed} {p.windDirection}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AgainButton({ onAgain }) {
  return (
    <button className="ws-again" onClick={onAgain}>Check another location →</button>
  );
}

Object.assign(window, { TitleCard, ZipPanel, LoadingHint, Captions, ForecastCards, AgainButton });
