/* AGYST — shared components & data */
const { useState, useEffect, useRef, useMemo } = React;

/* ——— Logo: actual brand mark ——— */
function Mark({ size = 22 }) {
  return (
    <img
      src="/static/logo.png"
      alt="AGYST"
      width={size}
      height={size}
      style={{ objectFit: "contain", display: "block" }}
    />
  );
}

function Wordmark({ size = 14, color = "currentColor" }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 10, color }}>
      <Mark size={26} />
      <span style={{ fontWeight: 600, letterSpacing: "0.22em", fontSize: size }}>AGYST</span>
    </span>
  );
}

/* ——— small icons ——— */
const Icon = {
  discord: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 14} height={p.size || 14} fill="currentColor" aria-hidden="true">
      <path d="M19.6 4.8A17 17 0 0 0 15.3 3.5l-.2.4a14.8 14.8 0 0 0-6.2 0l-.2-.4A17 17 0 0 0 4.4 4.8C1.7 8.8.9 12.8 1.3 16.7a17 17 0 0 0 5.2 2.6l.4-.6a12 12 0 0 1-1.9-.9l.4-.3a12 12 0 0 0 11.2 0l.4.3a12 12 0 0 1-1.9.9l.4.6a17 17 0 0 0 5.2-2.6c.5-4.5-.6-8.5-3.1-11.9zM8.5 14.5c-1 0-1.9-.9-1.9-2.1 0-1.1.8-2.1 1.9-2.1s1.9 1 1.9 2.1c0 1.1-.9 2.1-1.9 2.1zm7 0c-1 0-1.9-.9-1.9-2.1 0-1.1.8-2.1 1.9-2.1s1.9 1 1.9 2.1c0 1.1-.9 2.1-1.9 2.1z" />
    </svg>
  ),
  telegram: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 14} height={p.size || 14} fill="currentColor" aria-hidden="true">
      <path d="M22 3.2 2.4 10.6c-1.3.5-1.3 1.3-.2 1.6l4.9 1.5L18.7 6.6c.5-.3 1-.2.6.2l-9.2 8.3-.3 4.5c.5 0 .7-.2 1-.5l2.3-2.2 4.8 3.5c.9.5 1.5.2 1.7-.8l3.2-15c.3-1.3-.5-1.9-1.8-1.4z" />
    </svg>
  ),
  arrow: (p) => (
    <svg viewBox="0 0 16 16" width={p.size || 12} height={p.size || 12} fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
      <path d="M3 8h10M9 4l4 4-4 4" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  bolt: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="M13 3 4 14h7l-1 7 9-11h-7l1-7z" strokeLinejoin="round" />
    </svg>
  ),
  shield: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="M12 3 4 6v6c0 4.5 3.4 8.6 8 9 4.6-.4 8-4.5 8-9V6l-8-3z" strokeLinejoin="round" />
    </svg>
  ),
  trophy: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="M7 4h10v4a5 5 0 0 1-10 0V4zM5 5H3v2a3 3 0 0 0 3 3M19 5h2v2a3 3 0 0 1-3 3M9 14h6v2H9zM8 18h8v2H8z" strokeLinejoin="round" />
    </svg>
  ),
  flame: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
      <path d="M12 3s4 4 4 8a4 4 0 0 1-8 0c0-1 .5-2 1-3-2 1-4 4-4 7a7 7 0 0 0 14 0c0-5-4-8-7-12z" strokeLinejoin="round" />
    </svg>
  ),
};

/* ——— Mock market data ——— */
const MARKETS = [
  { sym: "NVDA",  name: "NVIDIA Corp.",        px: 142.86,  chg: +2.34, vol: "284.1M", spark: 22 },
  { sym: "TSLA",  name: "Tesla, Inc.",         px:  248.71, chg: -1.12, vol: "172.6M", spark: 18 },
  { sym: "SPY",   name: "SPDR S&P 500",        px:  583.42, chg: +0.41, vol:  "92.3M", spark: 14 },
  { sym: "AAPL",  name: "Apple Inc.",          px:  221.18, chg: +0.86, vol: "118.4M", spark: 17 },
  { sym: "META",  name: "Meta Platforms",      px:  612.04, chg: +1.94, vol:  "44.8M", spark: 24 },
  { sym: "MSFT",  name: "Microsoft Corp.",     px:  428.50, chg: +0.22, vol:  "38.1M", spark: 12 },
  { sym: "COIN",  name: "Coinbase Global",     px:  274.66, chg: +4.12, vol:  "26.7M", spark: 28 },
  { sym: "MSTR",  name: "MicroStrategy",       px:  348.92, chg: +6.47, vol:  "32.9M", spark: 30 },
  { sym: "GOOG",  name: "Alphabet Inc.",       px:  176.40, chg: -0.34, vol:  "29.5M", spark: 15 },
  { sym: "AMZN",  name: "Amazon.com",          px:  216.78, chg: +1.18, vol:  "41.2M", spark: 19 },
  { sym: "AMD",   name: "Advanced Micro Dev.", px:  138.22, chg: +2.92, vol:  "62.3M", spark: 26 },
  { sym: "PLTR",  name: "Palantir Tech.",      px:   78.31, chg: +3.74, vol:  "55.8M", spark: 27 },
];

const TICKER = [
  ["NVDA", 142.86, +1.66], ["TSLA", 248.71, -0.45], ["SPY", 583.42, +0.41],
  ["AAPL", 221.18, +0.39], ["MSFT", 428.50, +0.22], ["META", 612.04, +0.32],
  ["GOOG", 176.40, -0.34], ["AMZN", 216.78, +1.18], ["COIN", 274.66, +4.12],
  ["MSTR", 348.92, +6.47], ["AMD",  138.22, +2.92], ["PLTR",  78.31, +3.74],
  ["QQQ",  502.18, +0.62], ["IWM",  220.91, -0.18], ["NFLX", 712.55, +1.04],
  ["AVGO", 1684.20,+2.18], ["BABA",  98.42, -0.92], ["UBER",  72.18, +0.55],
];

/* ——— Sparkline ——— */
function Sparkline({ seed = 1, color = "#0E2542", w = 160, h = 36, up = true }) {
  const pts = useMemo(() => {
    const n = 32;
    let v = 50;
    const out = [];
    let s = seed * 9301 + 49297;
    const rand = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    for (let i = 0; i < n; i++) {
      v += (rand() - 0.5 + (up ? 0.18 : -0.18)) * 8;
      v = Math.max(10, Math.min(90, v));
      out.push(v);
    }
    return out;
  }, [seed, up]);
  const path = pts.map((p, i) => `${i === 0 ? "M" : "L"}${(i / (pts.length - 1)) * w},${h - (p / 100) * h}`).join(" ");
  const area = `${path} L${w},${h} L0,${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none" aria-hidden="true">
      <path d={area} fill={color} fillOpacity="0.08" />
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}

/* ——— Mini embed chart for the chat embed ——— */
function MiniChart({ color = "#6FA6CC", w = 320, h = 60 }) {
  const pts = [62,58,56,60,55,52,48,50,46,42,44,40,38,42,38,34,36,32,28,30,26,28,22,20,18,22,18,14,16,12];
  const path = pts.map((p, i) => `${i === 0 ? "M" : "L"}${(i / (pts.length - 1)) * w},${(p / 80) * h}`).join(" ");
  const area = `${path} L${w},${h} L0,${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none" aria-hidden="true">
      <defs>
        <linearGradient id="mcg" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.35" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#mcg)" />
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  );
}

/* ——— Ticker tape ——— */
function TickerTape() {
  const items = [...TICKER, ...TICKER];
  return (
    <div className="tape" aria-label="Live ticker">
      <div className="tape-track">
        {items.map((t, i) => {
          const [sym, px, chg] = t;
          const up = chg >= 0;
          return (
            <span className="tape-item" key={i}>
              <span className="sym">{sym}</span>
              <span className="px">{px.toFixed(2)}</span>
              <span className={up ? "chg-up" : "chg-dn"}>{up ? "+" : ""}{chg.toFixed(2)}%</span>
              <span className="dot-sm"></span>
            </span>
          );
        })}
      </div>
    </div>
  );
}

/* ——— Chat demo (animated) ——— */
function ChatDemo({ platform = "discord" }) {
  const isTg = platform === "telegram";
  const handle = isTg ? "@vince_h" : "vince";
  const botName = "AGYST";

  const sequence = useMemo(() => ([
    { type: "user", name: handle, ts: "9:42 AM", body: <><span className="cmd">/price NVDA</span></> },
    {
      type: "bot",
      name: botName,
      ts: "9:42 AM",
      body: (
        <div className="embed">
          <div className="row">
            <div>
              <div className="ttl">NVDA · NVIDIA Corp.</div>
              <div className="sub">HIP-3 · NVDA-USDC PERP</div>
            </div>
            <div className="sub">HYPERLIQUID</div>
          </div>
          <div>
            <span className="px">$142.86</span>
            <span className="chg">+2.34% · 24h</span>
          </div>
          <div style={{ marginTop: 10 }}>
            <MiniChart />
          </div>
          <div className="grid-kv">
            <div>
              <div className="k">24h Vol</div>
              <div className="v">$284.1M</div>
            </div>
            <div>
              <div className="k">Open Interest</div>
              <div className="v">$58.4M</div>
            </div>
            <div>
              <div className="k">Funding (8h)</div>
              <div className="v" style={{ color: "#B8DCBE" }}>+0.0124%</div>
            </div>
            <div>
              <div className="k">Spread</div>
              <div className="v">0.02 bps</div>
            </div>
          </div>
          <div className="actions">
            <span className="pill go">/buy</span>
            <span className="pill">/sell</span>
            <span className="pill">/watch</span>
            <span className="pill">/chart 1H</span>
          </div>
        </div>
      ),
    },
    { type: "user", name: handle, ts: "9:43 AM", body: <><span className="cmd">/buy NVDA size:500 type:market</span></> },
    {
      type: "bot",
      name: botName,
      ts: "9:43 AM",
      body: (
        <div className="embed fill-receipt">
          <div className="row">
            <div>
              <div className="ttl">✓ Filled · LONG NVDA</div>
              <div className="sub">Settled on Hyperliquid · 8.2s</div>
            </div>
            <div className="sub" style={{ color: "#B8DCBE" }}>0xA4..91F</div>
          </div>
          <div className="grid-kv" style={{ marginTop: 12 }}>
            <div>
              <div className="k">Size</div>
              <div className="v">500 NVDA</div>
            </div>
            <div>
              <div className="k">Avg. Fill</div>
              <div className="v">$142.88</div>
            </div>
            <div>
              <div className="k">Notional</div>
              <div className="v">$71,440</div>
            </div>
            <div>
              <div className="k">Fee</div>
              <div className="v">$3.21</div>
            </div>
          </div>
          <div className="actions">
            <span className="pill">+12.4 XP → CLAN.RONIN</span>
          </div>
        </div>
      ),
    },
  ]), [platform]);

  const [shown, setShown] = useState(1);
  const [typing, setTyping] = useState(false);

  useEffect(() => {
    setShown(1);
    setTyping(false);
    let cancelled = false;
    const tick = async (i) => {
      if (cancelled) return;
      await new Promise(r => setTimeout(r, i === 0 ? 700 : 1200));
      if (cancelled) return;
      if (sequence[i].type === "bot") {
        setTyping(true);
        await new Promise(r => setTimeout(r, 900));
        if (cancelled) return;
        setTyping(false);
      }
      setShown(s => Math.min(sequence.length, s + 1));
    };
    const run = async () => {
      for (let i = 1; i < sequence.length; i++) {
        await tick(i);
      }
      await new Promise(r => setTimeout(r, 4200));
      if (!cancelled) {
        setShown(1);
        run();
      }
    };
    const t = setTimeout(run, 300);
    return () => { cancelled = true; clearTimeout(t); };
  }, [sequence]);

  const channel = isTg ? "@agystbot · private chat" : "# trading-floor · agyst";

  return (
    <div className="term" role="presentation">
      <div className="term-head">
        <div className="tabs">
          <span className="tab active">{isTg ? "TELEGRAM" : "DISCORD"}</span>
          <span className="tab">SLASH COMMANDS</span>
        </div>
        <div className="right">
          <span className="pulse"></span>
          <span>{channel}</span>
        </div>
      </div>
      <div className="term-body">
        {sequence.slice(0, shown).map((m, i) => (
          <div className="chat-line" key={i}>
            <div className={`avatar ${m.type === "user" ? "av-user" : "av-bot"}`}>
              {m.type === "user" ? "V" : <Mark size={14} />}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="name">
                <span style={{ fontWeight: 600 }}>{m.name}</span>
                {m.type === "bot" && <span className="tag">BOT</span>}
                <span className="ts">{m.ts}</span>
              </div>
              <div className="body">{m.body}</div>
            </div>
          </div>
        ))}
        {typing && (
          <div className="chat-line">
            <div className="avatar av-bot"><Mark size={14} /></div>
            <div>
              <div className="name">
                <span style={{ fontWeight: 600 }}>{botName}</span>
                <span className="tag">BOT</span>
              </div>
              <div className="body" style={{ display: "flex", gap: 4, alignItems: "center", paddingTop: 4 }}>
                <Dot delay={0} /><Dot delay={140} /><Dot delay={280} />
              </div>
            </div>
          </div>
        )}
        {!typing && shown === sequence.length && (
          <div style={{ paddingLeft: 40, marginTop: 4 }}>
            <span className="caret"></span>
          </div>
        )}
      </div>
    </div>
  );
}

function Dot({ delay }) {
  return (
    <span style={{
      display: "inline-block", width: 5, height: 5, borderRadius: "50%",
      background: "rgba(236,233,226,0.5)",
      animation: `tdot 1s ease-in-out ${delay}ms infinite`,
    }} />
  );
}

(function injectTypingKeyframes() {
  if (document.getElementById("__agyst_kf")) return;
  const s = document.createElement("style");
  s.id = "__agyst_kf";
  s.textContent = `@keyframes tdot { 0%,100% { opacity: 0.25; transform: translateY(0); } 50% { opacity: 1; transform: translateY(-2px); } }`;
  document.head.appendChild(s);
})();

Object.assign(window, {
  Mark, Wordmark, Icon,
  MARKETS, TICKER,
  Sparkline, MiniChart, TickerTape, ChatDemo,
});
