// Cover.jsx — opening title card. Captures nickname, previews the
// 6-round loop, shows the top of the leaderboard.

const { useState: useStateCV, useEffect: useEffectCV, useRef: useRefCV } = React;

const NICK_STORAGE = "agent-trading-nickname-v1";

// Editor preview URLs carry single-use tokens — anyone else who opens
// them will hit a "preview token" error. Treat these as "no URL yet"
// and prompt the host to paste their published link.
function looksLikePreviewUrl(url) {
  if (!url) return true;
  const u = url.toLowerCase();
  return (
    u.includes("preview") ||
    u.includes("?token=") ||
    u.includes("&token=") ||
    u.includes("openmind.app") ||
    u.includes("sandbox") ||
    u.startsWith("about:") ||
    u.startsWith("blob:") ||
    u.startsWith("data:") ||
    u.includes("localhost")
  );
}

function Cover({ onStart }) {
  const [nick, setNick] = useStateCV(() => {
    try { return localStorage.getItem(NICK_STORAGE) || ""; } catch (e) { return ""; }
  });
  const [error, setError] = useStateCV(null);
  const [shareOpen, setShareOpen] = useStateCV(false);
  const [shareUrl, setShareUrl] = useStateCV(() => {
    // Try the parent frame URL first, but only keep it if it looks like a
    // real shareable link. Editor-preview URLs carry expiring tokens that
    // 404 for anyone else, so we blank those out and let the host paste
    // their published share URL.
    let url = "";
    try { url = window.parent.location.href; } catch (e) {
      try { url = window.location.href; } catch (e2) {}
    }
    if (looksLikePreviewUrl(url)) return "";
    return url;
  });
  const inputRef = useRefCV(null);

  useEffectCV(() => {
    if (inputRef.current && !nick) {
      // Don't autofocus on mobile (keyboard pops); just place caret on click.
    }
  }, []);

  const submit = () => {
    const clean = nick.trim().slice(0, 20);
    if (!clean) {
      setError("Pick a handle first.");
      inputRef.current?.focus();
      return;
    }
    try { localStorage.setItem(NICK_STORAGE, clean); } catch (e) {}
    onStart(clean);
  };

  const dieRoll = () => {
    const s = window.lbSuggestNickname();
    setNick(s);
    setError(null);
  };

  return (
    <div style={{
      display: "flex",
      flexDirection: "column",
      height: "100%",
      padding: "0 20px 20px",
      gap: 14,
      boxSizing: "border-box",
      overflowY: "auto",
    }}>
      {/* Hero */}
      <div style={{ paddingTop: 8 }}>
        <div style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 8,
          marginBottom: 4,
        }}>
          <div className="ds-overline" style={{ color: "var(--color-brand-primary)" }}>
            Agent Trading Desk
          </div>
          <button
            onClick={() => setShareOpen(true)}
            style={{
              height: 28,
              padding: "0 10px 0 8px",
              background: "var(--color-surface-default)",
              color: "var(--color-text-primary)",
              border: "1px solid var(--color-border-subtle)",
              borderRadius: "var(--radius-pill)",
              fontFamily: "var(--font-family-sans)",
              fontWeight: 600,
              fontSize: 11,
              letterSpacing: "0.04em",
              cursor: "pointer",
              display: "inline-flex",
              alignItems: "center",
              gap: 5,
              flexShrink: 0,
            }}
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="7" height="7" rx="1" />
              <rect x="14" y="3" width="7" height="7" rx="1" />
              <rect x="3" y="14" width="7" height="7" rx="1" />
              <path d="M14 14h3v3M21 17v4M14 21h3M21 14h-3" />
            </svg>
            Share QR
          </button>
        </div>
        <h1 style={{
          margin: 0,
          fontFamily: "var(--font-family-sans)",
          fontWeight: 600,
          fontSize: 28,
          lineHeight: "33px",
          letterSpacing: "-0.018em",
          color: "var(--color-text-primary)",
          textWrap: "balance",
        }}>
          Trade like you've got a quant desk behind you.
        </h1>
        <p style={{
          margin: "9px 0 0",
          fontSize: 13.5,
          lineHeight: "19px",
          color: "var(--color-text-secondary)",
          textWrap: "pretty",
        }}>
          Your AI agent scans the overnight markets, drafts the strategies, and runs the risk
          checks. You make the calls. Every session you book P&amp;L, climb the board, and get
          sharper — <strong style={{ color: "var(--color-text-primary)", fontWeight: 600 }}>this is where good traders become great.</strong>
        </p>
      </div>

      {/* Nickname input */}
      <div style={{
        background: "var(--color-surface-promo)",
        border: "1px solid rgba(196,31,62,0.20)",
        borderRadius: "var(--radius-md)",
        padding: "12px 14px 14px",
        display: "flex",
        flexDirection: "column",
        gap: 8,
      }}>
        <div className="ds-overline" style={{ fontSize: 10, color: "var(--color-brand-mark)" }}>
          Your trader handle
        </div>
        <div style={{
          display: "flex",
          gap: 8,
          alignItems: "stretch",
        }}>
          <input
            ref={inputRef}
            value={nick}
            maxLength={20}
            onChange={(e) => { setNick(e.target.value); setError(null); }}
            onKeyDown={(e) => { if (e.key === "Enter") submit(); }}
            placeholder="AlphaWolf"
            style={{
              flex: 1,
              height: 42,
              padding: "0 12px",
              background: "var(--color-surface-default)",
              border: error ? "2px solid var(--color-danger)" : "1px solid var(--color-border-subtle)",
              borderRadius: "var(--radius-sm)",
              fontFamily: "var(--font-family-sans)",
              fontSize: 15,
              fontWeight: 600,
              color: "var(--color-text-primary)",
              letterSpacing: "-0.003em",
              outline: "none",
              minWidth: 0,
            }}
          />
          <button
            type="button"
            onClick={dieRoll}
            aria-label="Suggest a nickname"
            style={{
              width: 42, height: 42,
              padding: 0,
              background: "var(--color-surface-default)",
              border: "1px solid var(--color-border-subtle)",
              borderRadius: "var(--radius-sm)",
              cursor: "pointer",
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              color: "var(--color-text-secondary)",
              flexShrink: 0,
            }}
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M19 8.71 13.13 2.84a2 2 0 0 0-2.83 0L2.84 10.3a2 2 0 0 0 0 2.83L8.71 19a2 2 0 0 0 2.83 0l7.46-7.46a2 2 0 0 0 0-2.83Z" />
              <circle cx="7.5" cy="13.5" r=".5" fill="currentColor" />
              <circle cx="13" cy="8.5" r=".5" fill="currentColor" />
              <circle cx="13" cy="13" r=".5" fill="currentColor" />
              <circle cx="13" cy="17" r=".5" fill="currentColor" />
              <circle cx="9" cy="8.5" r=".5" fill="currentColor" />
            </svg>
          </button>
        </div>
        <div style={{
          minHeight: 14,
          fontSize: 11,
          color: error ? "var(--color-danger)" : "var(--color-text-secondary)",
          fontWeight: error ? 600 : 400,
        }}>
          {error || "Best score per handle survives across sessions."}
        </div>
      </div>

      <button
        onClick={submit}
        style={{
          width: "100%",
          boxSizing: "border-box",
          height: 52,
          background: "var(--color-brand-primary)",
          color: "var(--color-text-on-brand)",
          border: "none",
          borderRadius: "var(--radius-sm)",
          fontFamily: "var(--font-family-sans)",
          fontWeight: 600,
          fontSize: 16,
          cursor: "pointer",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 8,
        }}
      >
        Begin
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="9 18 15 12 9 6" />
        </svg>
      </button>

      {shareOpen && (
        <ShareModal
          url={shareUrl}
          onChangeUrl={setShareUrl}
          onClose={() => setShareOpen(false)}
        />
      )}
    </div>
  );
}

function LBRow({ rank, entry }) {
  const medals = { 1: "#C9A146", 2: "#9CA1AA", 3: "#8B5A1A" };
  const isYou = !!entry.isYou;
  return (
    <div style={{
      display: "flex",
      alignItems: "center",
      gap: 10,
      padding: "5px 0",
      borderTop: rank === 1 ? "none" : "1px solid var(--color-border-subtle)",
    }}>
      <span style={{
        width: 22, height: 22,
        borderRadius: "50%",
        background: medals[rank] || "var(--color-surface-subtle)",
        color: "#fff",
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: "var(--font-family-sans)",
        fontWeight: 700,
        fontSize: 10,
        fontVariantNumeric: "tabular-nums",
        flexShrink: 0,
        border: rank > 3 ? "1px solid var(--color-border-subtle)" : "none",
      }}>{rank}</span>
      <span style={{
        flex: 1,
        fontFamily: "var(--font-family-sans)",
        fontSize: 13,
        fontWeight: isYou ? 700 : 600,
        color: isYou ? "var(--color-brand-primary)" : "var(--color-text-primary)",
        letterSpacing: "-0.003em",
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      }}>
        {entry.nickname}{isYou ? " (you)" : ""}
      </span>
      <span style={{
        fontFamily: "var(--font-family-sans)",
        fontSize: 13,
        fontWeight: 700,
        color: isYou ? "var(--color-brand-primary)" : "var(--color-text-primary)",
        fontVariantNumeric: "tabular-nums",
        letterSpacing: "-0.005em",
      }}>
        ${entry.score.toLocaleString()}
      </span>
    </div>
  );
}

function QRCode({ value }) {
  const svgHtml = React.useMemo(() => {
    if (!window.qrcode) {
      return '<div style="font-size:11px;color:#888;padding:20px;text-align:center;">QR library not loaded</div>';
    }
    try {
      const qr = window.qrcode(0, "M");
      qr.addData(value || " ");
      qr.make();
      return qr.createSvgTag({ cellSize: 8, margin: 2, scalable: true });
    } catch (e) {
      return '<div style="font-size:11px;color:#888;padding:20px;text-align:center;">URL too long for QR</div>';
    }
  }, [value]);
  return (
    <div
      style={{ width: "100%", height: "100%", display: "flex" }}
      dangerouslySetInnerHTML={{ __html: svgHtml }}
    />
  );
}

function ShareModal({ url, onChangeUrl, onClose }) {
  const [copied, setCopied] = useStateCV(false);
  const hasUrl = url && url.trim().length > 0 && !looksLikePreviewUrl(url);
  const copy = async () => {
    if (!hasUrl) return;
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch (e) {}
  };
  return (
    <div
      onClick={onClose}
      style={{
        position: "absolute",
        inset: 0,
        background: "rgba(0,0,0,0.55)",
        zIndex: 50,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 16,
        animation: "cvFadeIn 160ms var(--ease-standard)",
      }}
    >
      <style>{`
        @keyframes cvFadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes cvPopIn { from { opacity: 0; transform: scale(0.95) } to { opacity: 1; transform: scale(1) } }
      `}</style>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--color-surface-default)",
          borderRadius: "var(--radius-lg)",
          padding: "16px 16px 14px",
          boxShadow: "var(--shadow-4)",
          width: "100%",
          maxWidth: 340,
          display: "flex",
          flexDirection: "column",
          gap: 12,
          animation: "cvPopIn 220ms var(--ease-standard)",
        }}
      >
        <div style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}>
          <span style={{
            fontFamily: "var(--font-family-sans)",
            fontWeight: 700,
            fontSize: 11,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            color: "var(--color-brand-primary)",
          }}>Share with the room</span>
          <button
            onClick={onClose}
            aria-label="Close"
            style={{
              background: "none",
              border: "none",
              padding: 4,
              cursor: "pointer",
              color: "var(--color-text-muted)",
              display: "flex",
            }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>
        </div>

        <div style={{
          fontFamily: "var(--font-family-sans)",
          fontSize: 12.5,
          lineHeight: "17px",
          color: "var(--color-text-secondary)",
          textAlign: "center",
        }}>
          Have everyone scan to join the simulation on their own device.
        </div>

        <div style={{
          background: "#fff",
          border: "1px solid var(--color-border-subtle)",
          borderRadius: "var(--radius-md)",
          padding: 10,
          alignSelf: "center",
          width: 240,
          height: 240,
          boxSizing: "border-box",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}>
          {hasUrl ? (
            <QRCode value={url} />
          ) : (
            <div style={{
              textAlign: "center",
              padding: 16,
              color: "var(--color-text-muted)",
              fontSize: 12,
              lineHeight: "17px",
              fontFamily: "var(--font-family-sans)",
            }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginBottom: 8 }}>
                <rect x="3" y="3" width="7" height="7" rx="1" />
                <rect x="14" y="3" width="7" height="7" rx="1" />
                <rect x="3" y="14" width="7" height="7" rx="1" />
                <line x1="14" y1="14" x2="21" y2="21" />
                <line x1="21" y1="14" x2="14" y2="21" />
              </svg>
              <div style={{ fontWeight: 600 }}>Paste your share URL below</div>
              <div style={{ fontSize: 10.5, marginTop: 4, lineHeight: "14px" }}>
                The QR will generate from it.
              </div>
            </div>
          )}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          <span style={{
            fontSize: 9,
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            fontWeight: 700,
            color: "var(--color-text-muted)",
          }}>Share URL (your published link)</span>
          <input
            value={url}
            onChange={(e) => onChangeUrl(e.target.value)}
            placeholder="https://your-published-link.example/sim"
            style={{
              width: "100%",
              padding: "8px 10px",
              background: "var(--color-surface-subtle)",
              border: "1px solid var(--color-border-subtle)",
              borderRadius: "var(--radius-sm)",
              fontFamily: "var(--font-family-mono, monospace)",
              fontSize: 11,
              color: "var(--color-text-primary)",
              outline: "none",
              boxSizing: "border-box",
              letterSpacing: "-0.005em",
            }}
          />
          <span style={{
            fontSize: 10,
            lineHeight: "14px",
            color: looksLikePreviewUrl(url) && url
              ? "var(--color-danger)"
              : "var(--color-text-muted)",
            fontWeight: looksLikePreviewUrl(url) && url ? 600 : 400,
          }}>
            {looksLikePreviewUrl(url) && url
              ? "That looks like a preview URL — it'll error for others. Paste your published share link."
              : "Editor previews don't share — paste the link you'd send a stakeholder."}
          </span>
        </div>

        <div style={{ display: "flex", gap: 8 }}>
          <button
            onClick={copy}
            disabled={!hasUrl}
            style={{
              flex: 1,
              height: 40,
              background: copied ? "var(--color-success)" : "var(--color-surface-default)",
              color: copied ? "#fff" : (hasUrl ? "var(--color-text-primary)" : "var(--color-text-muted)"),
              border: copied ? "none" : "1px solid var(--color-border-subtle)",
              borderRadius: "var(--radius-sm)",
              fontFamily: "var(--font-family-sans)",
              fontWeight: 600,
              fontSize: 13,
              cursor: hasUrl ? "pointer" : "not-allowed",
              transition: "background var(--motion-base) var(--ease-standard)",
            }}
          >
            {copied ? "Copied" : "Copy link"}
          </button>
          <button
            onClick={onClose}
            style={{
              flex: 1,
              height: 40,
              background: "var(--color-brand-primary)",
              color: "var(--color-text-on-brand)",
              border: "none",
              borderRadius: "var(--radius-sm)",
              fontFamily: "var(--font-family-sans)",
              fontWeight: 600,
              fontSize: 13,
              cursor: "pointer",
            }}
          >
            Done
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Cover, LBRow, QRCode, ShareModal });
