// Small atoms shared across the page
const { useEffect, useState, useRef } = React;

function Countdown({ target }) {
  const [t, setT] = useState(() => diff(target));
  useEffect(() => {
    const id = setInterval(() => setT(diff(target)), 1000);
    return () => clearInterval(id);
  }, [target]);
  return (
    <div className="countdown">
      <Cell n={t.d} l="días" />
      <Cell n={t.h} l="horas" />
      <Cell n={t.m} l="min" />
      <Cell n={t.s} l="seg" />
    </div>
  );
}
function Cell({ n, l }) {
  return (
    <div className="cell">
      <div className="num">{String(n).padStart(2, "0")}</div>
      <div className="lab">{l}</div>
    </div>
  );
}
function diff(target) {
  const now = new Date();
  let ms = Math.max(0, target.getTime() - now.getTime());
  const d = Math.floor(ms / 86400000); ms -= d * 86400000;
  const h = Math.floor(ms / 3600000); ms -= h * 3600000;
  const m = Math.floor(ms / 60000); ms -= m * 60000;
  const s = Math.floor(ms / 1000);
  return { d, h, m, s };
}

function Marquee({ items, reverse = false, tall = false }) {
  const row = items.concat(items);
  return (
    <div className={`marquee ${reverse ? "reverse" : ""} ${tall ? "tall" : ""}`}>
      <div className="marquee-track">
        {row.map((it, i) => (
          <span className="marquee-item" key={i}>
            {it.icon === "dot" && <span className="dot"></span>}
            {it.icon === "star" && <span className="star">✦</span>}
            <span>{it.text}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

function Waveform({ playing, bars = 36 }) {
  const arr = React.useMemo(
    () => Array.from({ length: bars }, () => 0.2 + Math.random() * 0.8),
    [bars]
  );
  return (
    <div className="waveform">
      {arr.map((h, i) => (
        <span
          key={i}
          className={`bar ${playing ? "on" : ""}`}
          style={{
            height: `${h * 100}%`,
            animationDelay: `${(i * 50) % 700}ms`,
          }}
        />
      ))}
    </div>
  );
}

function GlitchText({ children, className = "" }) {
  const ref = useRef(null);
  const [txt, setTxt] = useState(children);
  const orig = useRef(children);
  useEffect(() => { orig.current = children; setTxt(children); }, [children]);
  const onEnter = () => {
    const chars = "▓▒░▞▚▙▜█01⌁⌇⌬";
    let i = 0;
    const total = 8;
    const id = setInterval(() => {
      i++;
      const t = orig.current
        .split("")
        .map((c, idx) =>
          c === " " ? " " : idx < (orig.current.length * i) / total ? c : chars[Math.floor(Math.random() * chars.length)]
        )
        .join("");
      setTxt(t);
      if (i >= total) { clearInterval(id); setTxt(orig.current); }
    }, 28);
  };
  return (
    <span ref={ref} className={className} onMouseEnter={onEnter}>{txt}</span>
  );
}

function Cursor() {
  const ref = useRef(null);
  const [variant, setVariant] = useState("");
  useEffect(() => {
    const el = ref.current;
    const move = (e) => {
      el.style.left = e.clientX + "px";
      el.style.top = e.clientY + "px";
    };
    const over = (e) => {
      const t = e.target;
      if (t.closest && t.closest("[data-cursor='hot']")) setVariant("hot");
      else if (t.closest && t.closest("a, button, .tier, .pm, .set-card, .gphoto, input, textarea, select")) setVariant("dot");
      else setVariant("");
    };
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseover", over);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseover", over);
    };
  }, []);
  return <div ref={ref} className={`cursor ${variant}`} aria-hidden="true" />;
}

Object.assign(window, { Countdown, Marquee, Waveform, GlitchText, Cursor });
