/* For-agents page — shadcn/ui theme distribution.
   Lets any agent (or human) pull the Nexus ReGen brand theme into a
   shadcn-based project in seconds. The theme.css and registry.json
   live under /shadcn at the brand site root and are the single source
   of truth — this section fetches and surfaces them. */

/* Mapping table — drives the "Mappings" Block. Order matches the
   logical groups in theme.css so a human reading the table sees the
   same shape they'll see in the file.
   `why` is non-null when the choice is not obvious; the cell renders
   a small explainer beneath the value so an agent (or designer) can
   tell mapping-from-tokens apart from mapping-by-decision. */
const SHADCN_MAPPINGS = [
  { group: 'Surfaces', rows: [
    { v: '--background',  light: 'Paper #FFFFFF',           dark: 'brand-950 #03040E',
      why: null },
    { v: '--foreground',  light: 'neutral-900 #101828',     dark: 'brand-50 #F1F2F9',
      why: null },
    { v: '--card',        light: 'Paper #FFFFFF',           dark: 'brand-900 #06081C',
      why: 'Cards lift one step out of the canvas — paper on white, brand-900 on brand-950.' },
    { v: '--popover',     light: 'Paper #FFFFFF',           dark: 'brand-900 #06081C', why: null },
  ]},
  { group: 'Brand', rows: [
    { v: '--primary',     light: 'brand-600 #121541',       dark: 'brand-200 #B4B7D4',
      why: 'Penn Blue is the primary on light. On dark we step up to brand-200 so the button reads as a confident lighter shape.' },
    { v: '--primary-foreground', light: 'neutral-25 #FCFCFD', dark: 'brand-700 #0E1034',
      why: 'Inverts with --primary so contrast stays AA in both modes.' },
    { v: '--accent',      light: 'accent-50 #FEF8B8',       dark: 'accent-400 #F7EC33',
      why: 'Pure aureolin fails contrast on light surfaces, so the accent surface uses the soft accent-50 wash. Real aureolin returns on dark, where the navy canvas provides the contrast it needs.' },
    { v: '--accent-foreground', light: 'brand-700 #0E1034', dark: 'brand-900 #06081C', why: null },
    { v: '--ring',        light: 'accent-400 #F7EC33',      dark: 'accent-400 #F7EC33',
      why: 'Aureolin focus ring keeps accessibility high-visibility AND on-brand, distinct from the destructive red.' },
  ]},
  { group: 'Status', rows: [
    { v: '--destructive', light: 'signal-red #FF331F',      dark: 'signal-red #FF331F',
      why: 'Single value across modes — the brand\'s designated alert red.' },
  ]},
  { group: 'Low-emphasis', rows: [
    { v: '--secondary',   light: 'neutral-100 #F2F4F7',     dark: 'brand-800 #0A0C28', why: null },
    { v: '--muted',       light: 'neutral-100 #F2F4F7',     dark: 'brand-800 #0A0C28', why: null },
    { v: '--muted-foreground', light: 'neutral-600 #475467', dark: 'brand-200 #B4B7D4',
      why: 'Sits AA on the muted surface — verified manually, not just stepped.' },
  ]},
  { group: 'Borders / inputs', rows: [
    { v: '--border',      light: 'neutral-200 #EAECF0',     dark: 'brand-700 #0E1034', why: null },
    { v: '--input',       light: 'neutral-200 #EAECF0',     dark: 'brand-700 #0E1034', why: null },
  ]},
  { group: 'Charts', rows: [
    { v: '--chart-1',     light: 'brand-600 #121541',       dark: 'brand-200 #B4B7D4',
      why: 'Brand series is always the headline; lifted on dark.' },
    { v: '--chart-2',     light: 'accent-400 #F7EC33',      dark: 'accent-400 #F7EC33', why: null },
    { v: '--chart-3',     light: 'dodger-blue #1E96FC',     dark: 'dodger-blue #1E96FC', why: null },
    { v: '--chart-4',     light: 'success-500 #17B26A',     dark: 'success-500 #17B26A', why: null },
    { v: '--chart-5',     light: 'warning-500 #F79009',     dark: 'warning-500 #F79009', why: null },
  ]},
  { group: 'Sidebar (app shell)', rows: [
    { v: '--sidebar',     light: 'brand-600 #121541',       dark: 'brand-900 #06081C',
      why: 'Canonical Nexus chrome — navy chrome with paper text. Use as-is for product navigation.' },
    { v: '--sidebar-foreground', light: 'brand-100 #DDDFE9', dark: 'brand-100 #DDDFE9', why: null },
    { v: '--sidebar-primary', light: 'accent-400 #F7EC33',  dark: 'accent-400 #F7EC33',
      why: 'Active nav item glows aureolin — matches the marketing site.' },
  ]},
  { group: 'Radius', rows: [
    { v: '--radius',      light: '0.5rem (8px)',            dark: '0.5rem (8px)',
      why: 'Matches `--r-lg` — the default Card / Button / Input radius across the design system.' },
  ]},
];

/* Single mapping row with three copy targets: the variable name, the
   light value and the dark value. Hover-reveal the copy buttons so the
   table reads cleanly when scanning. */
function ShadcnMappingRow({ v, light, dark, why }) {
  const [copied, setCopied] = useState(null);
  const onCopy = (text, key) => {
    copy(text);
    setCopied(key);
    setTimeout(() => setCopied(null), 1100);
  };
  const cell = (label, key, mono = false) => (
    <button
      onClick={() => onCopy(label, key)}
      title="Click to copy"
      style={{
        textAlign: 'left', minWidth: 0,
        background: copied === key ? 'var(--brand-600)' : 'transparent',
        color: copied === key ? '#fff' : 'var(--text-secondary)',
        border: 'none', padding: '6px 8px', borderRadius: 6,
        cursor: 'pointer', fontFamily: mono ? 'var(--font-mono)' : 'inherit',
        fontSize: mono ? 12 : 13, fontWeight: mono ? 500 : 600,
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
      }}
    >{copied === key ? '✓ copied' : label}</button>
  );
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1.1fr 1fr 1fr', gap: 8,
      alignItems: 'start',
      padding: '6px 4px',
      borderTop: '1px solid var(--border-tertiary)',
    }}>
      <div>
        {cell(v, `${v}:name`, true)}
        {why && (
          <div style={{
            fontSize: 11, color: 'var(--text-quaternary)',
            padding: '0 8px 4px 8px', lineHeight: 1.45,
            gridColumn: '1 / -1',
          }}>{why}</div>
        )}
      </div>
      {cell(light, `${v}:light`)}
      {cell(dark, `${v}:dark`)}
    </div>
  );
}

function S_Shadcn() {
  const [themeCss, setThemeCss] = useState(null);
  const [loadError, setLoadError] = useState(false);
  const [copied, setCopied] = useState(false);

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

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

  const stats = useMemo(() => {
    if (!themeCss) return null;
    return `${themeCss.split('\n').length} lines · ${themeCss.length.toLocaleString()} chars`;
  }, [themeCss]);

  /* Stable canonical URL agents will paste into install commands.
     Hardcoded to the production host so copy-paste from the page
     always points at brand.nexusregen.com regardless of env. */
  const REGISTRY_URL = 'https://brand.nexusregen.com/shadcn/registry.json';

  const manualInstall =
`/* app/globals.css — replace your :root and .dark blocks
   with the ones from https://brand.nexusregen.com/shadcn/theme.css.
   Or, simpler, paste the whole file in. */
@import "tailwindcss";
@import "tw-animate-css";

@import url("https://brand.nexusregen.com/shadcn/theme.css");

/* …rest of your @theme inline { … } block stays as shadcn shipped it. */`;

  const registryInstall =
`# One command — adds Nexus ReGen brand variables to your shadcn project
npx shadcn@latest add ${REGISTRY_URL}

# That's it. Light + dark CSS variables are written into
# app/globals.css; toggle .dark on <html> to switch.`;

  return (
    <Section
      id="shadcn"
      eyebrow="05 · For agents"
      title="shadcn/ui theme"
      intro="Apply the Nexus ReGen palette to any shadcn-based project in one command. Light + dark CSS variables, mapped intentionally to the brand tokens — Penn Blue primary, Aureolin accent, neutrals from the Untitled UI ramp."
    >
      <Block title="Research summary" note="How shadcn theming works in 2026.">
        <Card pad={20} variant="inset">
          <div style={{ fontSize: 14, lineHeight: 1.7, color: 'var(--text-secondary)' }}>
            <p style={{ margin: 0 }}>
              shadcn/ui ships components by copy-paste, not by package; the theme is just CSS variables on
              <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12, padding: '1px 6px',
                background: 'var(--bg-tertiary)', borderRadius: 4, margin: '0 4px' }}>:root</code>
              and
              <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12, padding: '1px 6px',
                background: 'var(--bg-tertiary)', borderRadius: 4, margin: '0 4px' }}>.dark</code>
              in your <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>app/globals.css</code>.
              Components consume them through Tailwind via an <code style={{ fontFamily: 'var(--font-mono)',
              fontSize: 12 }}>@theme inline</code> block (e.g.
              <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}> --color-primary: var(--primary)</code>),
              which means swapping a theme is a single CSS change — no rebuild of components.
            </p>
            <p style={{ marginTop: 12, marginBottom: 0 }}>
              In mid-2025 shadcn switched colour values from raw HSL triples to
              <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12, padding: '1px 6px',
                background: 'var(--bg-tertiary)', borderRadius: 4, margin: '0 4px' }}>oklch()</code>
              for perceptually-uniform light/dark interpolation. The full surface area is
              ~30 variables: background, foreground, card, popover, primary, secondary, muted, accent,
              destructive, border, input, ring, chart-1…5, sidebar (8 tokens) and radius. Themes can now
              be distributed as registry items —
              <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12, padding: '1px 6px',
                background: 'var(--bg-tertiary)', borderRadius: 4, margin: '0 4px' }}>type: "registry:theme"</code>
              with a <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>cssVars</code>
              { ' ' }block — and installed via <code style={{ fontFamily: 'var(--font-mono)',
              fontSize: 12 }}>npx shadcn add &lt;url&gt;</code>. That's the path we ship below.
            </p>
          </div>
        </Card>
      </Block>

      <Block title="The theme">
        <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 · REGISTRY:THEME
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', marginTop: 4 }}>
              brand.nexusregen.com<span style={{ opacity: .65 }}>/shadcn/theme.css</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--brand-100)', marginTop: 6, lineHeight: 1.5 }}>
              {loadError
                ? 'Couldn\'t load the live file. Try the View raw link.'
                : (stats || 'Loading…')}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
            <button
              onClick={onCopyTheme}
              disabled={!themeCss}
              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: themeCss ? 'pointer' : 'not-allowed',
                opacity: themeCss ? 1 : .55,
              }}
            >{copied ? '✓ Copied' : '⧉ Copy theme.css'}</button>
            <a href="/shadcn/theme.css" 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="/shadcn/theme.css" download="theme.css" 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="Install" note="Two paths — pick the one that matches your stack.">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 16 }}>
          <Card pad={20}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <span style={{
                fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700,
                letterSpacing: '.14em', color: 'var(--accent-800)',
                background: 'var(--accent-50)', padding: '3px 8px', borderRadius: 4,
              }}>RECOMMENDED</span>
              <h4 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: 'var(--text-primary)' }}>
                Registry — one command
              </h4>
            </div>
            <p style={{ margin: '0 0 12px', fontSize: 13, color: 'var(--text-tertiary)', lineHeight: 1.6 }}>
              The shadcn CLI pulls our <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>registry.json</code>,
              merges the CSS variables into your existing <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>globals.css</code>,
              and you're done. Works on any shadcn project (Next.js, Remix, Vite, Astro).
            </p>
            <Code block>{registryInstall}</Code>
          </Card>

          <Card pad={20}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <span style={{
                fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700,
                letterSpacing: '.14em', color: 'var(--text-tertiary)',
                background: 'var(--bg-tertiary)', padding: '3px 8px', borderRadius: 4,
              }}>FALLBACK</span>
              <h4 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: 'var(--text-primary)' }}>
                Manual — paste theme.css
              </h4>
            </div>
            <p style={{ margin: '0 0 12px', fontSize: 13, color: 'var(--text-tertiary)', lineHeight: 1.6 }}>
              For projects that don't use the shadcn CLI, or when you want to vendor the theme. Paste the file
              into your <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>app/globals.css</code> —
              or import it remotely as below.
            </p>
            <Code block>{manualInstall}</Code>
          </Card>
        </div>
      </Block>

      <Block title="Mappings" note="How shadcn variables map to Nexus brand tokens. Click any cell to copy.">
        <Card pad={0} variant="inset" style={{ overflow: 'hidden' }}>
          {/* Header row */}
          <div style={{
            display: 'grid', gridTemplateColumns: '1.1fr 1fr 1fr', gap: 8,
            padding: '10px 12px',
            background: 'var(--bg-primary)',
            borderBottom: '1px solid var(--border-secondary)',
            fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700,
            letterSpacing: '.08em', color: 'var(--text-quaternary)',
            textTransform: 'uppercase',
          }}>
            <div>Variable</div>
            <div>Light</div>
            <div>Dark</div>
          </div>
          {SHADCN_MAPPINGS.map(group => (
            <div key={group.group}>
              <div style={{
                padding: '10px 12px',
                background: 'var(--bg-primary)',
                fontSize: 12, fontWeight: 700, color: 'var(--text-secondary)',
                letterSpacing: '.02em',
                borderTop: '1px solid var(--border-secondary)',
                borderBottom: '1px solid var(--border-tertiary)',
              }}>{group.group}</div>
              <div style={{ padding: '4px 8px' }}>
                {group.rows.map(row => (
                  <ShadcnMappingRow key={row.v} {...row} />
                ))}
              </div>
            </div>
          ))}
        </Card>
      </Block>

      <Block title="Source" note="Same content as theme.css — scrollable.">
        <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',
        }}>{themeCss || 'Loading…'}</pre>
      </Block>
    </Section>
  );
}

window.S_Shadcn = S_Shadcn;
