/* global React, useApi, useMeta, Loading, ApiError, Tag, formatMoney */

// =========================================================================
// SHARE — auto-generated cards from real data.
//   Variant A: single market (top pick)
//   Variant B: leaderboard snapshot
// =========================================================================
function SharePage({ navigate, polymarketId }) {
  const [variant, setVariant] = React.useState('a');
  const [theme, setTheme]     = React.useState('dark');

  // When launched with a specific market id (Share button on the market page),
  // fetch that market directly so it's pre-selected. Otherwise fall back to
  // the top picks pool for the user to browse.
  const directMarket = useApi(
    () => polymarketId ? window.CloudLayerAPI.getMarket(polymarketId) : Promise.resolve(null),
    [polymarketId],
  );
  const picks    = useApi(() => window.CloudLayerAPI.listTopPicks(8), []);
  const official = useApi(() => window.CloudLayerAPI.leaderboardOfficial({ window: '30d' }), []);

  const candidates = picks.data?.items || [];
  const [pickId, setPickId] = React.useState(null);

  // Build a shareable pick payload — same shape as TopPick.snapshotMarket but
  // we synthesize it on the client when launched from a market page.
  function buildSnapshotFromMarket(m, predictions) {
    if (!m) return null;
    const consensus = predictions.length
      ? predictions.reduce((s, p) => s + p.yesProbability, 0) / predictions.length
      : (m.yesPrice ?? 0.5);
    const verdict = consensus >= 0.5 ? 'YES' : 'NO';
    return {
      polymarketId: m.polymarketId,
      question: m.question,
      category: m.category,
      yesPrice: m.yesPrice,
      yesProbability: consensus,
      verdict,
      volume: m.volume,
      endDate: m.endDate,
      edge: consensus - (m.yesPrice ?? 0.5),
      perModel: predictions.map((p) => ({
        modelId: p.modelId,
        modelLabel: p.modelLabel,
        yesProbability: p.yesProbability,
        verdict: p.verdict,
      })),
    };
  }

  const currentPick = React.useMemo(() => {
    if (polymarketId) {
      // Locked to the market the user clicked Share on.
      if (!directMarket.data) return null;
      const m = directMarket.data.market;
      // Latest prediction per model.
      const latest = {};
      for (const p of directMarket.data.predictions || []) {
        if (!latest[p.modelId]) latest[p.modelId] = p;
      }
      return buildSnapshotFromMarket(m, Object.values(latest));
    }
    if (!candidates.length) return null;
    return candidates.find((p) => p.polymarketId === pickId) || candidates[0];
  }, [polymarketId, directMarket.data, candidates, pickId]);

  // Embed URL — the standalone HTML the iframe loads. Per-market for Variant
  // A; the leaderboard snapshot for Variant B. The theme is carried as a
  // query param so the link the user copies preserves the look they were
  // previewing — open in dark, paste in dark; open in light, paste in light.
  const themeQs = theme === 'light' ? '?theme=light' : '';
  const embedSrc =
    variant === 'b'
      ? `${window.location.origin}/embed/leaderboard${themeQs}`
      : currentPick
      ? `${window.location.origin}/embed/market/${encodeURIComponent(currentPick.polymarketId)}${themeQs}`
      : '';
  const iframeSnippet = embedSrc
    ? `<iframe src="${embedSrc}" width="540" height="420" frameborder="0" loading="lazy" style="border:0;border-radius:8px;overflow:hidden;max-width:100%"></iframe>`
    : '';

  return (
    <div data-screen-label="05 Share">
      <div className="page-head">
        <div className="container">
          <div className="crumb">
            <span style={{ cursor: 'pointer' }} onClick={() => navigate('home')}>Benchmark</span>
            <span style={{ margin: '0 8px' }}>/</span>
            <span>Share</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 32 }}>
            <h1 style={{ flex: 1, margin: 0, fontSize: 64, fontFamily: 'var(--ff-display)', fontWeight: 300, letterSpacing: '-0.025em' }}>
              Share <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>cards</em>
            </h1>
            <div className="filter-row">
              <button className={`fchip ${variant === 'a' ? 'active' : ''}`} onClick={() => setVariant('a')}>Prediction</button>
              <button className={`fchip ${variant === 'b' ? 'active' : ''}`} onClick={() => setVariant('b')}>Leaderboard</button>
              <button className={`fchip ${theme === 'dark' ? 'active' : ''}`} onClick={() => setTheme('dark')}>Dark</button>
              <button className={`fchip ${theme === 'light' ? 'active' : ''}`} onClick={() => setTheme('light')}>Light</button>
            </div>
          </div>
        </div>
      </div>

      <section className="container" style={{ padding: '40px 32px 0' }}>
        {/* Only show the picker when the user landed here without a specific
            market locked in. When launched from a market page, the card is
            pre-selected and the picker would just be noise. */}
        {variant === 'a' && !polymarketId && (
          <div style={{ marginBottom: 24 }}>
            <div className="uppercase faint" style={{ marginBottom: 12 }}>Pick a market</div>
            {picks.error ? <ApiError error={picks.error} /> : picks.loading && !picks.data ? <Loading /> : (
              <div className="filter-row" style={{ flexWrap: 'wrap' }}>
                {candidates.map((p) => (
                  <button
                    key={p.polymarketId}
                    className={`fchip ${currentPick?.polymarketId === p.polymarketId ? 'active' : ''}`}
                    onClick={() => setPickId(p.polymarketId)}
                    style={{ maxWidth: 360, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
                    title={p.question}
                  >
                    {p.question.slice(0, 50)}{p.question.length > 50 ? '…' : ''}
                  </button>
                ))}
              </div>
            )}
          </div>
        )}

      </section>

      <section className="container" style={{ padding: '24px 32px 96px' }}>
        <div className="share-wrap" style={{ position: 'relative' }}>
          {/* Copy button — overlaid on the top-right of the preview card. One
              click copies the share URL (the oEmbed unfurl URL). Shows on
              both variants: market URL for A, leaderboard URL for B. */}
          {embedSrc && (
            <CardCopyButton embedSrc={embedSrc} theme={theme} />
          )}

          {variant === 'a' ? (
            <PredictionCard pick={currentPick} theme={theme} />
          ) : (
            <LeaderboardCard rows={official.data?.items || []} theme={theme} />
          )}
        </div>
      </section>
    </div>
  );
}

function CardCopyButton({ embedSrc, theme }) {
  const [copied, setCopied] = React.useState(false);
  function copy() {
    try { navigator.clipboard.writeText(embedSrc); } catch {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  }
  // Inverted overlay per theme so it always reads against the card background:
  //   Dark card  → dark-ish overlay with light text
  //   Light card → white overlay with dark text
  const isLight = theme === 'light';
  const baseBg     = isLight ? 'rgba(255,255,255,0.92)' : 'rgba(20,21,26,0.78)';
  const baseBorder = isLight ? 'rgba(0,0,0,0.18)'       : 'rgba(255,255,255,0.22)';
  const baseFg     = isLight ? '#1a1a1f'                : '#ece9e2';
  return (
    <button
      type="button"
      onClick={copy}
      title="Copy share link — paste anywhere to unfold"
      style={{
        position: 'absolute',
        top: 16, right: 16,
        zIndex: 5,
        padding: '8px 14px',
        background: copied ? (isLight ? 'rgba(111,181,131,0.20)' : 'rgba(111,181,131,0.25)') : baseBg,
        color: copied ? (isLight ? '#2f7d4b' : 'var(--pos)') : baseFg,
        border: `1px solid ${copied ? 'rgba(111,181,131,0.55)' : baseBorder}`,
        borderRadius: 6,
        fontFamily: 'var(--ff-mono)',
        fontSize: 11.5,
        letterSpacing: '0.06em',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)',
        boxShadow: isLight ? '0 1px 2px rgba(0,0,0,0.04)' : '0 1px 2px rgba(0,0,0,0.3)',
        cursor: 'pointer',
        transition: 'background 120ms, border-color 120ms, color 120ms',
      }}
    >
      {copied ? '✓ Copied' : 'Copy'}
    </button>
  );
}

function PredictionCard({ pick, theme }) {
  const { models } = useMeta();
  if (!pick) {
    return (
      <div className={`sharecard ${theme === 'light' ? 'light' : ''}`}>
        <div className="dim" style={{ position: 'relative', zIndex: 1 }}>No pick available yet.</div>
      </div>
    );
  }
  const isYes = pick.verdict === 'YES';
  const pct = Math.round(pick.yesProbability * 100);
  const days = pick.endDate ? Math.max(0, Math.round((new Date(pick.endDate).getTime() - Date.now()) / 86_400_000)) : null;

  return (
    <div className={`sharecard ${theme === 'light' ? 'light' : ''}`} style={{ position: 'relative' }}>
      <div className="gridlines" />
      <div style={{ position: 'relative', zIndex: 1, height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em' }}>
            <span style={{ color: 'var(--accent)' }}>●</span> CloudLayer
          </div>
          <div className="mono faint" style={{ fontSize: 14, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            {pick.category} · {formatMoney(pick.volume)} volume
          </div>
        </div>

        <div>
          <h2 style={{
            fontFamily: 'var(--ff-display)', fontSize: 56, fontWeight: 400,
            lineHeight: 1.05, letterSpacing: '-0.02em', margin: 0, maxWidth: 1000,
          }}>{pick.question}</h2>
          <div style={{ marginTop: 24, display: 'flex', alignItems: 'baseline', gap: 18 }}>
            <span className="mono tnum" style={{ fontSize: 96, fontWeight: 500, color: isYes ? 'var(--pos)' : 'var(--neg)', lineHeight: 1 }}>
              {pct}<span style={{ fontSize: 36, color: theme === 'light' ? 'rgba(0,0,0,0.4)' : 'var(--fg-faint)' }}>%</span>
            </span>
            <span style={{ fontFamily: 'var(--ff-display)', fontStyle: 'italic', fontSize: 56, color: isYes ? 'var(--pos)' : 'var(--neg)' }}>
              {isYes ? 'YES' : 'NO'}
            </span>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {(pick.perModel || []).slice(0, 6).map((m) => {
            const w = `${Math.round(m.yesProbability * 100)}%`;
            const mm = models.find((x) => x.id === m.modelId);
            return (
              <div key={m.modelId} style={{ display: 'grid', gridTemplateColumns: '110px 1fr 60px', alignItems: 'center', gap: 12 }}>
                <span className="mono" style={{ fontSize: 12, letterSpacing: '0.05em' }}>{m.modelLabel || mm?.short}</span>
                <div className="barlane">
                  <div className="fill" style={{ width: w, background: mm?.color || '#888' }} />
                  <div className="marker" style={{ left: `${Math.round((pick.yesPrice || 0.5) * 100)}%` }} />
                </div>
                <span className="mono tnum" style={{ fontSize: 14, textAlign: 'right' }}>{w}</span>
              </div>
            );
          })}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span className="mono faint" style={{ fontSize: 13 }}>
            {days == null ? '' : days === 0 ? 'resolves today' : `resolves in ${days} days`}
          </span>
          <span className="mono" style={{ fontSize: 13, letterSpacing: '0.05em' }}>
            cloudlayer · /market/{(pick.polymarketId || '').slice(0, 24)}
          </span>
        </div>
      </div>
    </div>
  );
}

function LeaderboardCard({ rows, theme }) {
  const top = rows.slice(0, 5);
  const weekLabel = new Date().toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
  return (
    <div className={`sharecard ${theme === 'light' ? 'light' : ''}`} style={{ position: 'relative' }}>
      <div className="gridlines" />
      <div style={{ position: 'relative', zIndex: 1, height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div style={{ fontFamily: 'var(--ff-display)', fontSize: 22, fontWeight: 500 }}>
            <span style={{ color: 'var(--accent)' }}>●</span> CloudLayer · This week in model forecasting
          </div>
          <div className="mono faint" style={{ fontSize: 14 }}>{weekLabel}</div>
        </div>

        <div>
          {top.length === 0 ? (
            <div className="dim">No data yet.</div>
          ) : top.map((row) => (
            <div key={row.modelId} style={{
              display: 'grid', gridTemplateColumns: '60px 1fr 120px 100px',
              alignItems: 'center', padding: '14px 0', borderBottom: '1px solid rgba(255,255,255,0.06)',
            }}>
              <span className={`rnk ${row.rank === 1 ? 't1' : row.rank === 2 ? 't2' : row.rank === 3 ? 't3' : ''}`}
                    style={{ fontSize: 24 }}>#{row.rank}</span>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                <span style={{ width: 12, height: 12, borderRadius: '50%', background: row.color }} />
                <span style={{ fontFamily: 'var(--ff-display)', fontSize: 22 }}>{row.modelLabel}</span>
              </span>
              <span className="mono tnum" style={{ fontSize: 24, textAlign: 'right' }}>
                {row.total === 0 ? '—' : `${Math.round(row.accuracy * 100)}%`}
              </span>
              <span className="mono faint" style={{ fontSize: 13, textAlign: 'right' }}>
                {row.total ? `${row.correct} / ${row.total}` : ''}
              </span>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span className="mono faint" style={{ fontSize: 13 }}>Full data at cloudlayer</span>
          <span className="mono" style={{ fontSize: 13, letterSpacing: '0.05em' }}>cloudlayer/leaderboard</span>
        </div>
      </div>
    </div>
  );
}

// =========================================================================
// EmbedCopier — small panel with the iframe snippet + copy buttons. Two
// copy actions: the full HTML iframe tag (paste into a site / Notion /
// Substack), and the raw URL (works on Twitter/X — they unfurl into a card
// via the OG tags on the embed page).
// =========================================================================
function EmbedCopier({ embedSrc, snippet }) {
  const [copiedUrl, setCopiedUrl]   = React.useState(false);
  const [copiedHtml, setCopiedHtml] = React.useState(false);
  function copy(text, which) {
    try { navigator.clipboard.writeText(text); } catch {}
    if (which === 'url') { setCopiedUrl(true); setTimeout(() => setCopiedUrl(false), 1500); }
    else { setCopiedHtml(true); setTimeout(() => setCopiedHtml(false), 1500); }
  }
  return (
    <div className="panel" style={{ marginBottom: 24 }}>
      <div className="panel-header">
        <h3>Share</h3>
        <span className="mono faint" style={{ fontSize: 11 }}>auto-unfolds when pasted</span>
      </div>
      <div className="panel-body" style={{ display: 'grid', gap: 14 }}>
        {/* Primary action — one big copy button. Like Spotify's share. */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'minmax(0,1fr) auto',
          gap: 12, alignItems: 'stretch',
          border: '1px solid var(--border)', borderRadius: 6,
          background: 'var(--bg)',
          padding: 4,
        }}>
          <input
            readOnly
            value={embedSrc}
            onFocus={(e) => e.target.select()}
            style={{
              background: 'transparent', border: 0, outline: 'none',
              fontFamily: 'var(--ff-mono)', fontSize: 12, color: 'var(--fg)',
              padding: '10px 12px', minWidth: 0,
            }}
          />
          <button
            type="button"
            className="btn btn-accent"
            onClick={() => copy(embedSrc, 'url')}
            style={{ padding: '8px 18px', minWidth: 90 }}
          >
            {copiedUrl ? '✓ Copied' : 'Copy link'}
          </button>
        </div>
        <div className="dim" style={{ fontSize: 12.5, lineHeight: 1.55 }}>
          Paste anywhere — Slack, Notion, Substack, Discord, X. The card preview renders inline via Open Graph + oEmbed, exactly like a Spotify link.
        </div>

        {/* Secondary — explicit iframe snippet for power users who paste into
            raw HTML (custom site, blog template, embed widget). */}
        <details style={{ marginTop: 4 }}>
          <summary className="mono faint" style={{ fontSize: 11, cursor: 'pointer', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            Embed HTML (iframe)
          </summary>
          <div className="prompt-block" style={{ background: '#0a0b0e', marginTop: 8 }}>
            <div className="ph">
              <div className="ph-l">
                <span className="badge">html</span>
                <span>raw iframe</span>
              </div>
              <button
                type="button"
                className={`copy-btn ${copiedHtml ? 'copied' : ''}`}
                onClick={() => copy(snippet, 'html')}
              >
                {copiedHtml ? 'copied' : 'copy'}
              </button>
            </div>
            <pre style={{ fontSize: 11.5 }}>{snippet}</pre>
          </div>
        </details>
      </div>
    </div>
  );
}

window.SharePage = SharePage;
window.EmbedCopier = EmbedCopier;
