/* ============================================================
   OVERLAY SECTIONS  (the on-air graphics)
   ============================================================ */
const { useRef, useEffect, useState } = React;

function cls(...a) { return a.filter(Boolean).join(" "); }

/* ---- animated count-up for the hero stat ---- */
function CountUp({ value, trigger }) {
  const ref = useRef(null);
  const decimals = (String(value).split(".")[1] || "").length;
  const target = parseFloat(String(value).replace(/,/g, "")) || 0;
  useEffect(() => {
    const el = ref.current; if (!el) return;
    if (!trigger) { el.textContent = fmt(target, decimals); return; }
    let raf, start;
    const from = target * 0.62;
    const dur = 1900;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      const e = 1 - Math.pow(1 - p, 3);
      el.textContent = fmt(from + (target - from) * e, decimals);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value, trigger]);
  function fmt(n, d) {
    return n.toLocaleString("en-US", { minimumFractionDigits: d, maximumFractionDigits: d });
  }
  return <span ref={ref}>{value}</span>;
}

/* ---- BUG ---- */
function Bug({ s, vis }) {
  return (
    <div className={cls("layer bug", !vis && "hidden-sect")}>
      <div className="bug-logo">
        <image-slot id="ucc-logo" fit="contain" src="assets/ucc-logo.png" placeholder="EVENT LOGO"></image-slot>
      </div>
      <div className="bug-sub">
        <span className="live-dot"><i></i>LIVE</span>
        <span className="bug-loc">{s.sub}</span>
      </div>
    </div>
  );
}

/* ---- RUN TELEMETRY ---- */
function statsFor(disc, r) {
  if (disc === "drag") return [
    { k: "Elapsed", v: r.et, u: "sec", lead: true },
    { k: "Trap Speed", v: r.mph, u: "mph" },
    { k: "Reaction", v: r.rt, u: "sec" },
  ];
  if (disc === "pull") return [
    { k: "Distance", v: r.dist, u: "ft", lead: true },
    { k: "Class", v: r.weight, u: "lb" },
    { k: "Result", v: r.hook, badge: true },
  ];
  return [
    { k: "Peak HP", v: r.hp, lead: true },
    { k: "Peak Torque", v: r.tq, u: "lb-ft" },
    { k: "Boost", v: r.boost, u: "psi" },
  ];
}
function RunReadout({ s, disc, vis, liveTick }) {
  const stats = statsFor(disc, s);
  const discName = disc === "drag" ? "Drag" : disc === "pull" ? "Sled Pull" : "Dyno";
  return (
    <div className={cls("layer run", !vis && "hidden-sect")}>
      <div className="run-shell">
        <div className="run-head">
          <div className="run-disc">Live <b>{discName}</b> Run</div>
          <div className="run-roundtag">{s.round}</div>
        </div>
        <div className="run-body">
          {stats.map((st, i) => (
            <div key={i} className={cls("run-stat", st.lead && "lead")}>
              <div className="k">{st.k}</div>
              <div className="v">
                {st.badge
                  ? <span style={{ fontSize: "38px" }}>{st.v}</span>
                  : <CountUp value={st.v} trigger={st.lead ? liveTick : 0} />}
                {st.u && <span className="u">{st.u}</span>}
              </div>
            </div>
          ))}
        </div>
        <div className="run-foot">
          <span className="nm">{s.name}</span>
          <span>{s.shop}</span>
          <span className="no">#{s.car}</span>
        </div>
      </div>
    </div>
  );
}

/* ---- STANDINGS ---- */
function Standings({ s, vis }) {
  const rows = s.rows.slice(0, 20);
  return (
    <div className={cls("layer standings", !vis && "hidden-sect")}>
      <div className="stand-head">
        <div className="stand-title">{s.title}</div>
        <div className="stand-meta">{s.meta}</div>
      </div>
      <div className="stand-list">
        {rows.map((r, i) => {
          const dl = r.d === "up" ? "▲" : r.d === "dn" ? "▼" : "—";
          const dcl = r.d === "up" ? "up" : r.d === "dn" ? "dn" : "";
          return (
            <div key={i} className={cls("srow", i < 3 && `t${i + 1}`, i === s.highlight && "me")}>
              <div className="pos">{i + 1}</div>
              <div className="car">{r.car}</div>
              <div className="nm">{r.name}<small>{r.shop}</small></div>
              <div className="pts">{Number(r.pts).toLocaleString("en-US")}
                <span className={cls("delta", dcl)}>{dl}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---- LOWER THIRD ---- */
function LowerThird({ s, vis }) {
  return (
    <div className={cls("layer lower", !vis && "hidden-sect")}>
      <div className="lt-num">{s.car}</div>
      <div className="lt-body">
        <div className="lt-tag">{s.tag}</div>
        <div className="lt-name">{s.name}</div>
        <div className="lt-meta">
          <b>{s.shop}</b>
          <span className="dot"></span>
          <span>{s.truck}</span>
          <span className="dot"></span>
          <span>{s.home}</span>
        </div>
      </div>
    </div>
  );
}

/* ---- UP NEXT ---- */
function UpNext({ s, vis }) {
  return (
    <div className={cls("layer upnext", !vis && "hidden-sect")}>
      <div className="un-bar">
        <div className="un-label">{s.label}</div>
        <div className="un-name">{s.name}</div>
        <div className="un-no">#{s.car}</div>
      </div>
    </div>
  );
}

/* ---- DRAG MATCHUP (head-to-head lower third) ---- */
function DragMatchup({ s, vis }) {
  const L = s.left, R = s.right;
  return (
    <div className={cls("layer matchup", !vis && "hidden-sect")}>
      <div className="mu-banner"><span>{s.klass}{s.round ? ` · ${s.round}` : ""}</span></div>
      <div className="mu-bar">
        <div className="mu-side l">
          <div className="mu-num">{L.car}</div>
          <div className="mu-info">
            <div className="mu-name">{L.name}</div>
            <div className="mu-meta"><span>{L.home}</span><span className="dot"></span><span>{L.truck}</span></div>
          </div>
        </div>
        <div className="mu-center">
          <div className="mu-logo">
            <image-slot id="ucc-logo-mu" fit="contain" src="assets/ucc-logo.png" placeholder="LOGO"></image-slot>
          </div>
          <div className="mu-vs">
            <span className="dial l">{L.dial}</span>
            <b>VS</b>
            <span className="dial r">{R.dial}</span>
          </div>
        </div>
        <div className="mu-side r">
          <div className="mu-info">
            <div className="mu-name">{R.name}</div>
            <div className="mu-meta"><span>{R.truck}</span><span className="dot"></span><span>{R.home}</span></div>
          </div>
          <div className="mu-num">{R.car}</div>
        </div>
      </div>
      <div className="mu-next">
        <div className="mu-next-tag">{s.tag}</div>
        <div className="mu-next-pair">
          <span className="chip l">{s.next.left.car}</span>
          <span className="nm">{s.next.left.name}</span>
          <b>VS</b>
          <span className="nm">{s.next.right.name}</span>
          <span className="chip r">{s.next.right.car}</span>
        </div>
        <div className="mu-next-class">{s.next.klass}</div>
      </div>
    </div>
  );
}

/* ---- TICKER ---- */
function Ticker({ s, spon, vis, sponVis }) {
  const trackRef = useRef(null);
  const halfRef = useRef(null);
  useEffect(() => {
    const half = halfRef.current, track = trackRef.current;
    if (!half || !track) return;
    const w = half.offsetWidth;
    const pxPerSec = Math.max(40, s.speed * 4);
    track.style.animationDuration = (w / pxPerSec) + "s";
  }, [s.items, s.speed]);
  const items = s.items;
  const Half = ({ r }) => (
    <span ref={r} style={{ display: "inline-flex" }}>
      {items.map((it, i) => (
        <span key={i} className="tk-item">
          <span className="tag">{it.tag}</span>{it.text}
        </span>
      ))}
    </span>
  );
  return (
    <div className={cls("layer ticker", !vis && "hidden-sect")}>
      <div className="tk-cap">{s.label}</div>
      <div className="tk-track-wrap">
        <div className="tk-track" ref={trackRef}>
          <Half r={halfRef} />
          <Half r={null} />
        </div>
      </div>
      {sponVis && (
        <div className="tk-spon">
          <span className="sp-lab">{spon.label}</span>
          {Array.from({ length: spon.slots }).map((_, i) => (
            <div className="sp-slot" key={i}>
              <image-slot id={`ucc-spon-${i}`} shape="rect" placeholder="SPONSOR"></image-slot>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- INTERMISSION ---- */
function Intermission({ s, vis, clock }) {
  if (!vis) return null;
  const mm = String(Math.floor(clock / 60)).padStart(2, "0");
  const ss = String(clock % 60).padStart(2, "0");
  return (
    <div className="intermission">
      <div className="im-inner">
        <div className="im-logo">
          <image-slot id="ucc-logo-big" fit="contain" src="assets/ucc-logo.png" placeholder="EVENT LOGO"></image-slot>
        </div>
        <div className="im-eyebrow">{s.eyebrow}</div>
        <div className="im-title">{s.title}</div>
        <div className="im-sub">{s.sub}</div>
        <div className="im-clock"><b>{mm}</b>:{ss}
          <span className="lab">Resuming In</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Bug, RunReadout, Standings, LowerThird, UpNext, DragMatchup, Ticker, Intermission });
