/* eslint-disable */
/* global React, ReactDOM, I */

const { useState, useEffect, useRef } = React;

// ====== Ambient flow background (simplified, no chrome) ======
const GLITCH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&*+▓▒░◇◆";
function randChar() { return GLITCH_CHARS[Math.floor(Math.random() * GLITCH_CHARS.length)]; }
function randStr(len) { return Array.from({ length: len }, randChar).join(""); }

function BgFlow() {
  // Lengths only — actual labels stay hidden as glitching characters
  const lens = [4, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3];
  const cx = 500, cy = 500;
  const R = 380;
  const N = lens.length;
  const sources = lens.map((len, i) => {
    const angle = (i / N) * Math.PI * 2 - Math.PI / 2 + Math.PI / N;
    return {
      id: "s" + i,
      len,
      x: cx + R * Math.cos(angle),
      y: cy + R * Math.sin(angle),
    };
  });

  // Glitch labels: per-source random strings re-rolled on a tick
  const [labels, setLabels] = useState(() => sources.map(s => randStr(s.len)));
  useEffect(() => {
    const id = setInterval(() => {
      setLabels(prev => prev.map((lbl, i) => (
        Math.random() < 0.45 ? randStr(sources[i].len) : lbl
      )));
    }, 110);
    return () => clearInterval(id);
  }, []);

  // Per-source accent flicker: which char (if any) glows accent right now
  const [accents, setAccents] = useState(() => sources.map(() => -1));
  useEffect(() => {
    const id = setInterval(() => {
      setAccents(sources.map(s => Math.random() < 0.25 ? Math.floor(Math.random() * s.len) : -1));
    }, 180);
    return () => clearInterval(id);
  }, []);

  return (
    <svg viewBox="0 0 1000 1000" preserveAspectRatio="xMidYMid meet" style={{position:"absolute", inset:0, width:"100%", height:"100%"}}>
      <defs>
        <radialGradient id="bg-core" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.6" />
          <stop offset="60%" stopColor="var(--accent)" stopOpacity="0.15" />
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
        </radialGradient>
      </defs>

      {/* concentric orbit rings */}
      {[R, R * 0.72, R * 0.42].map((r, i) => (
        <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke="var(--border-1)" strokeWidth="1" strokeDasharray="2 5" opacity={0.7 - i * 0.15} />
      ))}

      {/* pulsing rings */}
      {[0, 1, 2].map(i => (
        <circle key={i} cx={cx} cy={cy} r="100" fill="none" stroke="var(--accent)" strokeWidth="1" opacity="0.5"
                style={{ animation: `pulse-ring 4s ${i * 1.3}s ease-out infinite`, transformOrigin: `${cx}px ${cy}px` }} />
      ))}

      {/* core glow */}
      <circle cx={cx} cy={cy} r="160" fill="url(#bg-core)" />

      {/* Center — official TON logo */}
      <image
        href="ton-logo.svg"
        x={cx - 90}
        y={cy - 90}
        width="180"
        height="180"
        style={{ filter: "drop-shadow(0 0 30px color-mix(in oklab, var(--accent), transparent 40%))" }}
      />

      {/* paths + nodes + animated packets */}
      {sources.map((s, i) => {
        const pathId = `bg-path-${s.id}`;
        const angle = Math.atan2(s.y - cy, s.x - cx);
        const tx = (s.x + cx) / 2 + Math.cos(angle + Math.PI / 2) * 36;
        const ty = (s.y + cy) / 2 + Math.sin(angle + Math.PI / 2) * 36;
        const d = `M ${s.x.toFixed(1)} ${s.y.toFixed(1)} Q ${tx.toFixed(1)} ${ty.toFixed(1)} ${cx} ${cy}`;
        const dur = 4 + (i % 5) * 0.55;
        const begin = i * 0.45;
        const label = labels[i] || "";
        const accentIdx = accents[i];
        return (
          <g key={s.id}>
            <path id={pathId} d={d} fill="none" stroke="var(--border-2)" strokeWidth="1" strokeDasharray="3 5" opacity="0.6" />
            <circle cx={s.x} cy={s.y} r="22" fill="var(--bg-1)" stroke="var(--border-2)" strokeWidth="1" />
            {/* glitching label, rendered character-by-character so one can flash accent */}
            <text x={s.x} y={s.y + 4} textAnchor="middle" fontFamily="var(--font-mono)" fontWeight="500" fontSize="11" fill="var(--ink-2)">
              {label.split("").map((ch, j) => (
                <tspan key={j} fill={j === accentIdx ? "var(--accent)" : undefined} opacity={Math.random() > 0.92 ? 0.4 : 1}>{ch}</tspan>
              ))}
            </text>
            <circle r="4" fill="var(--accent)">
              <animateMotion dur={`${dur}s`} repeatCount="indefinite" begin={`${begin}s`} keyTimes="0;0.85;1" keyPoints="0;0.96;1">
                <mpath href={`#${pathId}`} />
              </animateMotion>
              <animate attributeName="opacity" values="0;1;1;0" keyTimes="0;0.1;0.92;1" dur={`${dur}s`} repeatCount="indefinite" begin={`${begin}s`} />
            </circle>
          </g>
        );
      })}
    </svg>
  );
}

// ====== Phases of the headline carousel ======
const PHASES = [
  { l1: [{w: "Move"}, {w: "it"}, {w: "all"}],          l2: [{w: "to"}, {w: "TON.", cls: "accent"}] },
  { l1: [{w: "THIS"}, {w: "IS"}],                       l2: [{w: "TOTW"}, {w: "REBØRN.", cls: "accent"}] },
  { l1: [{w: "All-in"}],                                l2: [{w: "TON.", cls: "accent"}] },
];

function Headline({ phase, exiting }) {
  const p = PHASES[phase];
  const words = [...p.l1, ...p.l2];
  return (
    <div className={"headline" + (exiting ? " exiting" : "")} aria-hidden={exiting}>
      <div className="line">
        {p.l1.map((w, i) => (
          <span key={i} className={"word " + (w.cls || "")} style={{ ["--i"]: i }}>{w.w}</span>
        ))}
      </div>
      <div className="line">
        {p.l2.map((w, i) => (
          <span key={i} className={"word " + (w.cls || "")} style={{ ["--i"]: p.l1.length + i }}>{w.w}</span>
        ))}
      </div>
    </div>
  );
}

function HeadlineCarousel({ onSettled }) {
  const [phase, setPhase] = useState(0);
  const [leaving, setLeaving] = useState(null);
  const settledRef = useRef(false);

  useEffect(() => {
    const HOLDS = [3000, 3200]; // phase 0 → 1, then 1 → 2
    if (phase < 2) {
      const t = setTimeout(() => {
        setLeaving(phase);
        setPhase(p => p + 1);
        setTimeout(() => setLeaving(null), 700);
      }, HOLDS[phase]);
      return () => clearTimeout(t);
    }
    // Phase 2 (final) — wait for the entrance animation, then signal settled
    if (!settledRef.current) {
      const t = setTimeout(() => {
        settledRef.current = true;
        onSettled && onSettled();
      }, 1100);
      return () => clearTimeout(t);
    }
  }, [phase, onSettled]);

  return (
    <div className="headline-stage">
      {leaving !== null && <Headline phase={leaving} exiting />}
      <Headline phase={phase} key={phase} />
    </div>
  );
}

// ====== Countdown ======
const LAUNCH = new Date("2026-06-01T12:00:00Z").getTime();

function Countdown() {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, LAUNCH - now);
  const d = Math.floor(diff / 86400000);
  const h = Math.floor((diff % 86400000) / 3600000);
  const m = Math.floor((diff % 3600000) / 60000);
  const s = Math.floor((diff % 60000) / 1000);
  const pad = (n) => String(n).padStart(2, "0");

  return (
    <div className="countdown">
      <div className="unit"><span className="n">{pad(d)}</span><span className="l">DAYS</span></div>
      <div className="unit"><span className="n">{pad(h)}</span><span className="l">HRS</span></div>
      <div className="unit"><span className="n">{pad(m)}</span><span className="l">MIN</span></div>
      <div className="unit"><span className="n" style={{color:"var(--accent)"}}>{pad(s)}</span><span className="l">SEC</span></div>
    </div>
  );
}

// ====== Email signup ======
function Signup() {
  const [email, setEmail] = useState("");
  const [sent, setSent] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    if (!email.includes("@")) return;
    setSent(true);
    setTimeout(() => { setSent(false); setEmail(""); }, 3000);
  };
  return (
    <form className="email-input" onSubmit={submit}>
      <input
        type="email"
        placeholder="you@wallet.ton"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        disabled={sent}
      />
      <button type="submit" className="btn btn--primary btn--sm" style={{minWidth: 110}}>
        {sent ? <><I.check size={14} /> on the list</> : <>Notify me <I.arrow size={14} /></>}
      </button>
    </form>
  );
}

// ====== Holding root ======
function HoldingPage() {
  const [settled, setSettled] = useState(false);

  // Settle reveal animation for body content
  return (
    <div className="holding">
      {/* Crosshairs */}
      <span className="crosshair tl" />
      <span className="crosshair tr" />
      <span className="crosshair bl" />
      <span className="crosshair br" />

      {/* Background flow diagram + grid */}
      <div className="holding-bg">
        <div className="diagram-bg">
          <BgFlow />
        </div>
      </div>

      {/* Top bar */}
      <div className="holding-top">
        <div className="brand-tag" aria-label="all-in ton">
          <span className="bt-bracket">&lt;</span>
          <span className="bt-name">all-in&nbsp;ton</span>
          <span className="bt-bracket">/&gt;</span>
          <span className="bt-cursor" aria-hidden="true" />
        </div>
        <div className="status-line">
          <span className="live-dot" />
          <span className="status-text">PRE-LAUNCH · SEASON 01 · SUMMER 2026</span>
        </div>
      </div>

      {/* Center stage */}
      <div className="holding-stage">
        <div className="holding-stage-inner">
          <HeadlineCarousel onSettled={() => setSettled(true)} />

          <div className={"holding-cta" + (settled ? " in" : "")}>
            <a className="btn btn--primary" href="https://t.me/totw_chat" target="_blank" rel="noopener" title="Telegram">
              <I.tg size={14} /> Join Telegram
            </a>
            <a className="btn btn--ghost" href="https://x.com/totwrebuorn" target="_blank" rel="noopener" title="X">
              <I.x size={14} /> Follow on X
            </a>
          </div>
        </div>
      </div>

      {/* Bottom bar */}
      <div className="holding-bottom">
        <div className="col" style={{gap:6}}>
          <span style={{color:"var(--ink-3)"}}>EST. ARRIVAL · JUN 01 · 2026 · 12:00 UTC</span>
          <Countdown />
        </div>

        <div className="col" style={{gap:8, alignItems:"flex-end"}}>
          <div className="social-row">
            <a className="ico" href="https://t.me/totw_chat" target="_blank" rel="noopener" title="Telegram"><I.tg size={16} /></a>
            <a className="ico" href="https://x.com/totwrebuorn" target="_blank" rel="noopener" title="X"><I.x size={16} /></a>
          </div>
          <span style={{color:"var(--ink-3)"}}>v0.0.1 · pre-release · build 042</span>
        </div>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<HoldingPage />);
