/* For-agents page — text-only brand reference designed for LLMs and
   coding agents. Mirrors the canonical /llms.txt at the site root, with
   in-page Copy / Download / View raw actions. */

/* The single source of truth for the agent page. We fetch /llms.txt at
   runtime so the rendered page never drifts from the file LLMs hit. If
   the fetch fails (e.g. local dev with caching headaches), we fall back
   to a slim built-in summary so the page still renders something useful. */
const LLMS_FALLBACK = `# Nexus ReGen — Brand & Design System

> Loading the live llms.txt failed; this is a fallback summary.

- Tagline: Materially smarter construction.
- One-liner: One platform to plan, source, move and prove every material on every project.
- Penn Blue #121541 · Aureolin #F7EC33 · Paper #FFFFFF

See the live file at /llms.txt for full content.
`;

/* Stable asset URLs — derived from window.HOSTED_ASSETS (single source
   of truth, defined in s-hosted-assets.jsx) so the agent page and the
   Brand page can never drift apart. */
function llmsAssetGroups() {
  if (!window.HOSTED_ASSETS) return [];
  const base = window.HOSTED_ASSET_BASE;
  return window.HOSTED_ASSETS.map(g => ({
    group: g.group,
    note: g.note,
    items: g.items.flatMap(it =>
      it.formats.map(f => ({
        label: `${it.name} · ${f.toUpperCase()}`,
        url: `${base}/${it.path}.${f}`,
      }))
    ),
  }));
}

/* Click-to-copy chip with hover-reveal copy button */
function LlmsAssetRow({ label, url }) {
  const [copied, setCopied] = useState(false);
  const onCopy = (e) => {
    e.preventDefault();
    copy(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 1100);
  };
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1fr auto auto',
      alignItems: 'center', gap: 10,
      padding: '8px 12px',
      borderRadius: 8,
      background: 'var(--bg-secondary)',
      border: '1px solid var(--border-tertiary)',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)' }}>{label}</div>
        <code style={{
          display: 'block', fontFamily: 'var(--font-mono)', fontSize: 11,
          color: 'var(--text-quaternary)', marginTop: 2,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{url}</code>
      </div>
      <a href={url} target="_blank" rel="noopener" style={{
        fontSize: 11, fontFamily: 'var(--font-mono)', fontWeight: 600,
        color: 'var(--text-secondary)', textDecoration: 'none',
        border: '1px solid var(--border-secondary)',
        background: 'var(--bg-primary)',
        padding: '4px 10px', borderRadius: 6,
      }}>Open ↗</a>
      <button onClick={onCopy} style={{
        border: '1px solid var(--border-secondary)',
        background: copied ? 'var(--brand-600)' : 'var(--bg-primary)',
        color: copied ? '#fff' : 'var(--text-secondary)',
        fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 6,
        cursor: 'pointer', fontFamily: 'inherit', minWidth: 56,
      }}>{copied ? '✓' : 'Copy'}</button>
    </div>
  );
}

function S_LlmsOverview() {
  const [llmsTxt, setLlmsTxt] = useState(null);
  const [copied, setCopied] = useState(false);
  const [loadError, setLoadError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch('/llms.txt', { cache: 'no-store' })
      .then(r => r.ok ? r.text() : Promise.reject(new Error('not ok')))
      .then(t => { if (!cancelled) setLlmsTxt(t); })
      .catch(() => { if (!cancelled) { setLoadError(true); setLlmsTxt(LLMS_FALLBACK); } });
    return () => { cancelled = true; };
  }, []);

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

  return (
    <Section
      id="llms-overview"
      eyebrow="00 · For agents"
      title="A text-only brand brief, machine-readable."
      intro="This page mirrors the canonical /llms.txt — a single Markdown document with the brand identity, voice rules, colour tokens and stable asset URLs. Hand it to an LLM, paste it into a system prompt, or fetch it directly from a tool. Following the llmstxt.org convention."
    >
      <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
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', marginTop: 4 }}>
              brand.nexusregen.com<span style={{ opacity: .65 }}>/llms.txt</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.'
                : (llmsTxt ? `${llmsTxt.split('\n').length} lines · ${llmsTxt.length.toLocaleString()} chars` : 'Loading…')}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
            <button
              onClick={onCopy}
              disabled={!llmsTxt}
              style={{
                background: copied ? 'var(--accent-400)' : '#fff',
                color: copied ? 'var(--brand-700)' : 'var(--brand-700)',
                border: 'none',
                padding: '10px 16px', borderRadius: 8,
                fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700,
                cursor: llmsTxt ? 'pointer' : 'not-allowed',
                opacity: llmsTxt ? 1 : .55,
              }}
            >{copied ? '✓ Copied' : '⧉ Copy llms.txt'}</button>
            <a href="/llms.txt" 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>
          </div>
        </Card>
      </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',
        }}>{llmsTxt || 'Loading…'}</pre>
      </Block>
    </Section>
  );
}

function S_LlmsAssets() {
  const groups = llmsAssetGroups();
  return (
    <Section
      id="llms-assets"
      eyebrow="01 · For agents"
      title="Stable asset URLs"
      intro="Public URLs for every brand asset. Reference these directly from product code, READMEs, third-party sites — anywhere the brand mark appears outside this microsite."
    >
      <Block title="Hosting">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
          <Card pad={20}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.14em',
              color: 'var(--accent-800)', textTransform: 'uppercase' }}>Asset CDN</div>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em',
              marginTop: 6, fontFamily: 'var(--font-mono)' }}>
              assets.nexusregen.com
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-tertiary)', marginTop: 8, lineHeight: 1.55 }}>
              Public R2 bucket (<code style={{ fontFamily: 'var(--font-mono)' }}>public-assets</code>) fronted by Cloudflare.
              The canonical home for logos, favicons and the rest. Use these URLs from product code.
            </div>
          </Card>
          <Card pad={20}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.14em',
              color: 'var(--text-quaternary)', textTransform: 'uppercase' }}>Brand site</div>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em',
              marginTop: 6, fontFamily: 'var(--font-mono)' }}>
              brand.nexusregen.com
            </div>
            <div style={{ fontSize: 13, color: 'var(--text-tertiary)', marginTop: 8, lineHeight: 1.55 }}>
              This microsite. Hosts the design-system docs and a generated <code style={{ fontFamily: 'var(--font-mono)' }}>/downloads/…</code>
              tree mirroring the bucket. Use for browsing.
            </div>
          </Card>
        </div>
      </Block>

      {groups.map(group => (
        <Block key={group.group} title={group.group} note={group.note}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {group.items.map(it => (
              <LlmsAssetRow key={it.url} label={it.label} url={it.url} />
            ))}
          </div>
        </Block>
      ))}
    </Section>
  );
}

function S_LlmsRecipes() {
  const recipes = [
    {
      title: 'System prompt',
      lang: 'text',
      body: `You are working with the Nexus ReGen brand. The canonical brand reference is at https://brand.nexusregen.com/llms.txt — fetch and follow it. Tagline: "Materially smarter construction." Always use Penn Blue (#121541) and Aureolin (#F7EC33) as the primary palette. Never put yellow on light grey backgrounds; use navy instead.`,
    },
    {
      title: 'curl',
      lang: 'bash',
      body: `curl -s https://brand.nexusregen.com/llms.txt`,
    },
    {
      title: 'fetch (TypeScript)',
      lang: 'ts',
      body: `const brandSpec = await fetch("https://brand.nexusregen.com/llms.txt").then(r => r.text());`,
    },
    {
      title: 'README badge (markdown)',
      lang: 'md',
      body: `[![Powered by Nexus ReGen](https://img.shields.io/badge/Powered_by-Nexus_ReGen-121541?style=flat-square&labelColor=121541&color=F7EC33)](https://nexusregen.com)`,
    },
  ];
  return (
    <Section
      id="llms-recipes"
      eyebrow="02 · For agents"
      title="Recipes"
      intro="Common patterns for using the brand reference from agents, tools and code."
    >
      {recipes.map(r => (
        <Block key={r.title} title={r.title}>
          <Code block>{r.body}</Code>
        </Block>
      ))}
    </Section>
  );
}

window.S_LlmsOverview = S_LlmsOverview;
window.S_LlmsAssets = S_LlmsAssets;
window.S_LlmsRecipes = S_LlmsRecipes;
