/* For-agents page — design tokens JSON export.
   Surfaces /brand.json (W3C Design Tokens format) so agents can consume
   the brand programmatically. Mirrors the canonical file at the site
   root with in-page Copy / Download / View raw actions. */

const TOKENS_FALLBACK = `{
  "$description": "Nexus ReGen design tokens — fallback. Live /brand.json failed to load."
}`;

function S_Tokens() {
  const [tokensText, setTokensText] = useState(null);
  const [tokensJson, setTokensJson] = useState(null);
  const [copied, setCopied] = useState(false);
  const [loadError, setLoadError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch('/brand.json', { cache: 'no-store' })
      .then(r => r.ok ? r.text() : Promise.reject(new Error('not ok')))
      .then(t => {
        if (cancelled) return;
        try {
          const parsed = JSON.parse(t);
          /* Re-stringify with 2-space indent so the on-page render is
             always pretty even if the file is minified. */
          setTokensText(JSON.stringify(parsed, null, 2));
          setTokensJson(parsed);
        } catch (e) {
          setTokensText(t);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setLoadError(true);
          setTokensText(TOKENS_FALLBACK);
        }
      });
    return () => { cancelled = true; };
  }, []);

  const onCopy = () => {
    if (!tokensText) return;
    copy(tokensText);
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
  };

  /* Quick stats for the hero card — counted from the parsed JSON. */
  const stats = useMemo(() => {
    if (!tokensJson) return null;
    const countLeaves = (obj) => {
      if (!obj || typeof obj !== 'object') return 0;
      if ('$value' in obj) return 1;
      return Object.values(obj).reduce((n, v) => n + countLeaves(v), 0);
    };
    const total = countLeaves(tokensJson);
    const colors = countLeaves(tokensJson.color);
    return { total, colors };
  }, [tokensJson]);

  const recipes = [
    {
      title: 'JS / TS',
      lang: 'ts',
      body: `const tokens = await fetch("https://brand.nexusregen.com/brand.json").then(r => r.json());`,
      note: 'Fetch and consume directly. The file is plain JSON, no auth required.',
    },
    {
      title: 'Style Dictionary',
      lang: 'bash',
      body: `curl -o tokens/brand.json https://brand.nexusregen.com/brand.json`,
      note: 'Drop into your tokens/ source folder and reference from style-dictionary.config.js. The W3C $value / $type shape is supported natively.',
    },
    {
      title: 'Tailwind',
      lang: 'js',
      body: `import tokens from "./brand.json" assert { type: "json" };
// Map tokens.color.* into theme.extend.colors in tailwind.config.js`,
      note: 'A dedicated Tailwind preset will land in a follow-up section.',
    },
  ];

  return (
    <Section
      id="tokens"
      eyebrow="03 · For agents"
      title="Design tokens — JSON export"
      intro="Every colour, type face, radius, spacing step and shadow in the brand, exported as a single W3C Design Tokens JSON document. Fetch it, parse it, map it into your design-tokens pipeline of choice."
    >
      <Block title="The file">
        <Card pad={20} style={{
          background: 'var(--brand-600)', color: '#fff', border: 'none',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          gap: 16, flexWrap: 'wrap',
        }}>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11,
              color: 'var(--accent-400)', letterSpacing: '.14em', fontWeight: 700 }}>
              CANONICAL · W3C DESIGN TOKENS
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', marginTop: 4 }}>
              brand.nexusregen.com<span style={{ opacity: .65 }}>/brand.json</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--brand-100)', marginTop: 6, lineHeight: 1.5 }}>
              {loadError
                ? 'Couldn\'t load the live file. Showing a fallback below.'
                : (tokensText
                    ? (stats
                        ? `${stats.total} tokens · ${stats.colors} colours · ${tokensText.length.toLocaleString()} chars`
                        : `${tokensText.length.toLocaleString()} chars`)
                    : 'Loading…')}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0, flexWrap: 'wrap' }}>
            <button
              onClick={onCopy}
              disabled={!tokensText}
              style={{
                background: copied ? 'var(--accent-400)' : '#fff',
                color: 'var(--brand-700)',
                border: 'none',
                padding: '10px 16px', borderRadius: 8,
                fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700,
                cursor: tokensText ? 'pointer' : 'not-allowed',
                opacity: tokensText ? 1 : .55,
              }}
            >{copied ? '✓ Copied' : '⧉ Copy brand.json'}</button>
            <a href="/brand.json" target="_blank" rel="noopener" style={{
              background: 'transparent', color: '#fff',
              border: '1px solid rgba(255,255,255,.3)',
              padding: '10px 16px', borderRadius: 8,
              fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600,
              textDecoration: 'none',
            }}>View raw ↗</a>
            <a href="/brand.json" download="brand.json" style={{
              background: 'transparent', color: '#fff',
              border: '1px solid rgba(255,255,255,.3)',
              padding: '10px 16px', borderRadius: 8,
              fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600,
              textDecoration: 'none',
            }}>↓ Download</a>
          </div>
        </Card>
      </Block>

      <Block title="Quick consumers" note="One-liners for the most common pipelines.">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          {recipes.map(r => (
            <Card key={r.title} pad={20}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)' }}>{r.title}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700,
                  letterSpacing: '.12em', color: 'var(--text-quaternary)', textTransform: 'uppercase' }}>{r.lang}</div>
              </div>
              <pre style={{
                margin: '12px 0 0', padding: 12,
                background: 'var(--brand-950)', color: '#E8EAFB',
                borderRadius: 8,
                fontFamily: 'var(--font-mono)', fontSize: 12,
                lineHeight: 1.55,
                overflowX: 'auto',
                whiteSpace: 'pre-wrap',
              }}>{r.body}</pre>
              <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 10, lineHeight: 1.5 }}>
                {r.note}
              </div>
            </Card>
          ))}
        </div>
      </Block>

      <Block title="Source" note="Same content as the file above.">
        <pre style={{
          margin: 0, padding: 20,
          background: 'var(--bg-secondary)',
          border: '1px solid var(--border-tertiary)',
          borderRadius: 12,
          fontFamily: 'var(--font-mono)', fontSize: 12,
          lineHeight: 1.65,
          color: 'var(--text-primary)',
          maxHeight: 520,
          overflow: 'auto',
          whiteSpace: 'pre-wrap',
        }}>{tokensText || 'Loading…'}</pre>
      </Block>
    </Section>
  );
}

window.S_Tokens = S_Tokens;
