/* For-agents page — Tailwind preset & CSS vars.
   Drop-in artefacts so any product project can adopt the Nexus ReGen
   palette/typography/radius/shadow without re-keying tokens by hand.

   Two artefacts ship from the brand microsite:
     • /tailwind.preset.js  — Tailwind v3+ preset (CommonJS)
     • /nexus-brand.css     — :root CSS custom properties

   Both are fetched at runtime so the in-page Copy buttons hand the
   visitor the exact bytes the file serves — no chance of drift. */

/* ------------------------------------------------------------------
   Hero card — navy band with primary "Copy" + secondary "View raw".
   Modelled on S_LlmsOverview's "The file" card so the For-agents page
   has a consistent visual rhythm across artefacts.
   ------------------------------------------------------------------ */
function ArtifactHero({ eyebrow, path, description, content, loadError, copyLabel }) {
  const [copied, setCopied] = useState(false);
  const onCopy = () => {
    if (!content) return;
    copy(content);
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
  };
  const meta = loadError
    ? "Couldn't load the live file."
    : (content ? `${content.split('\n').length} lines · ${content.length.toLocaleString()} chars` : 'Loading…');
  return (
    <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 }}>
          {eyebrow}
        </div>
        <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', marginTop: 4 }}>
          brand.nexusregen.com<span style={{ opacity: .65 }}>{path}</span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--brand-100)', marginTop: 6, lineHeight: 1.5 }}>
          {description} · {meta}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
        <button
          onClick={onCopy}
          disabled={!content}
          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: content ? 'pointer' : 'not-allowed',
            opacity: content ? 1 : .55,
          }}
        >{copied ? '✓ Copied' : `⧉ ${copyLabel}`}</button>
        <a href={path} 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>
  );
}

function S_Tailwind() {
  /* Fetch both artefacts on mount. We hand the bytes to ArtifactHero so
     "Copy" pastes exactly what /tailwind.preset.js and /nexus-brand.css
     serve — no risk of the in-page copy drifting from the file. */
  const [preset, setPreset] = useState(null);
  const [presetError, setPresetError] = useState(false);
  const [css, setCss] = useState(null);
  const [cssError, setCssError] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch('/tailwind.preset.js', { cache: 'no-store' })
      .then(r => r.ok ? r.text() : Promise.reject(new Error('not ok')))
      .then(t => { if (!cancelled) setPreset(t); })
      .catch(() => { if (!cancelled) setPresetError(true); });
    fetch('/nexus-brand.css', { cache: 'no-store' })
      .then(r => r.ok ? r.text() : Promise.reject(new Error('not ok')))
      .then(t => { if (!cancelled) setCss(t); })
      .catch(() => { if (!cancelled) setCssError(true); });
    return () => { cancelled = true; };
  }, []);

  /* Install snippets — three numbered steps. Use Code block so each one
     is click-to-copy. Wrapping a Code in a numbered row keeps the
     existing primitive contract (just children). */
  const installSteps = [
    {
      label: 'Save the preset into your project',
      body: `# from your repo root
curl -o tailwind.preset.js https://brand.nexusregen.com/tailwind.preset.js`,
    },
    {
      label: 'Wire it into tailwind.config.js',
      body: `// tailwind.config.js
module.exports = {
  presets: [require('./tailwind.preset.js')],
  content: ['./src/**/*.{ts,tsx,js,jsx,html}'],
};`,
    },
    {
      label: 'Use the brand classes',
      body: `<button class="bg-brand-600 text-white shadow-md rounded-xl px-4 py-2 font-sans">
  Materially smarter.
</button>
<span class="text-accent-400">Aureolin highlight</span>`,
    },
  ];

  /* "What's in it" — the categories of tokens shipped by the preset.
     Counts come from the canonical :root block in index.html. */
  const inventory = [
    {
      heading: 'Colours',
      lines: [
        '3 ramps — brand (12), accent (11), neutral (12)',
        '4 supporting tones — dodger, signal, pine, humus',
        '3 semantic tones — success, warning, error',
      ],
    },
    {
      heading: 'Typography',
      lines: [
        'font-sans → Inter (UI, body)',
        'font-mono → JetBrains Mono (code, captions)',
        'font-display → Fraunces (Refine variant, opt-in)',
      ],
    },
    {
      heading: 'Radii',
      lines: [
        '7 steps — xs (2px) → 3xl (24px)',
        'rounded-full → 9999px (Tailwind default, untouched)',
      ],
    },
    {
      heading: 'Shadows',
      lines: [
        '7 steps — xs → 3xl, neutral-tinted Untitled-UI elevation',
        'shadow-2xl for hero cards, shadow-xs for inputs',
      ],
    },
  ];

  return (
    <Section
      id="tailwind"
      eyebrow="04 · For agents"
      title="Tailwind preset & CSS vars"
      intro="Two drop-in artefacts so any Nexus product picks up the brand correctly without re-keying tokens. Pick the Tailwind preset for utility-class projects, or the raw :root CSS file for everything else."
    >
      {/* ---- Tailwind preset hero ---- */}
      <Block title="The Tailwind preset"
        note="Spread into tailwind.config.js — no further setup needed.">
        <ArtifactHero
          eyebrow="TAILWIND v3+"
          path="/tailwind.preset.js"
          description="Colours · fonts · radii · shadows"
          content={preset}
          loadError={presetError}
          copyLabel="Copy preset"
        />
      </Block>

      {/* ---- nexus-brand.css hero ---- */}
      <Block title="The CSS variables file"
        note="For projects that want tokens without Tailwind.">
        <ArtifactHero
          eyebrow="CSS CUSTOM PROPERTIES"
          path="/nexus-brand.css"
          description="--brand-* · --accent-* · --neutral-* · --r-* · --s-* · --shadow-*"
          content={css}
          loadError={cssError}
          copyLabel="Copy CSS vars"
        />
      </Block>

      {/* ---- Install ---- */}
      <Block title="Install" note="Three steps to brand-correct utility classes.">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {installSteps.map((s, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '32px 1fr', gap: 12,
              alignItems: 'start',
            }}>
              <div style={{
                width: 28, height: 28, borderRadius: 999,
                background: 'var(--brand-600)', color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700,
                marginTop: 6,
              }}>{i + 1}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)' }}>
                  {s.label}
                </div>
                <Code block>{s.body}</Code>
              </div>
            </div>
          ))}
        </div>
      </Block>

      {/* ---- What's in it ---- */}
      <Block title="What's in it" note="Token categories shipped by the preset.">
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
          gap: 12,
        }}>
          {inventory.map(group => (
            <Card key={group.heading} variant="inset" pad={20}>
              <div style={{
                fontSize: 11, fontWeight: 700, letterSpacing: '.14em',
                color: 'var(--text-quaternary)', textTransform: 'uppercase',
              }}>{group.heading}</div>
              <ul style={{
                margin: '10px 0 0', padding: 0, listStyle: 'none',
                display: 'flex', flexDirection: 'column', gap: 6,
              }}>
                {group.lines.map((line, i) => (
                  <li key={i} style={{
                    fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5,
                    paddingLeft: 14, position: 'relative',
                  }}>
                    <span style={{
                      position: 'absolute', left: 0, top: 8,
                      width: 5, height: 5, borderRadius: 999,
                      background: 'var(--accent-400)',
                    }} />
                    {line}
                  </li>
                ))}
              </ul>
            </Card>
          ))}
        </div>
      </Block>
    </Section>
  );
}

window.S_Tailwind = S_Tailwind;
