/* Shared building blocks for the 7NOW docs site. */
const docsKit = {};

function useTokens() {
  const [t, setT] = React.useState(window.__7nowTokens || null);
  React.useEffect(() => {
    if (t) return;
    fetch('../tokens/tokens.json').then(r => r.json()).then(j => { window.__7nowTokens = j; setT(j); }).catch(() => setT({ primitive: {}, basic: {}, interface: {} }));
  }, []);
  return t;
}
const resolveVar = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();

const _cv = document.createElement('canvas'); _cv.width = _cv.height = 1;
const _cx = _cv.getContext('2d', { willReadFrequently: true });
function toRgb(css) {
  _cx.clearRect(0, 0, 1, 1); _cx.fillStyle = '#fff'; _cx.fillRect(0, 0, 1, 1);
  _cx.fillStyle = css; _cx.fillRect(0, 0, 1, 1);
  const d = _cx.getImageData(0, 0, 1, 1).data; return [d[0], d[1], d[2]];
}
function contrast(a, b) {
  const L = (c) => { const [r, g, bl] = toRgb(c).map(v => { v /= 255; return v <= .03928 ? v / 12.92 : Math.pow((v + .055) / 1.055, 2.4); }); return .2126 * r + .7152 * g + .0722 * bl; };
  const x = L(a), y = L(b); return (Math.max(x, y) + .05) / (Math.min(x, y) + .05);
}

function Page({ eyebrow, title, lead, children }) {
  return (
    <article className="doc-page">
      {eyebrow && <p className="doc-eyebrow">{eyebrow}</p>}
      <h1 className="doc-h1">{title}</h1>
      {lead && <p className="doc-lead">{lead}</p>}
      {children}
    </article>
  );
}
const H2 = ({ id, children }) => <h2 className="doc-h2" id={id}>{children}</h2>;
const H3 = ({ children }) => <h3 className="doc-h3">{children}</h3>;
const P = ({ children }) => <p className="doc-p">{children}</p>;
const Rules = ({ items }) => <ul className="doc-rules">{items.map((r, i) => <li key={i}>{r}</li>)}</ul>;
const Code = ({ children }) => <pre className="doc-code"><code>{children}</code></pre>;
const Tok = ({ children }) => <code className="doc-tok">{children}</code>;

function Callout({ kind = 'info', title, children }) {
  return <div className={'doc-callout doc-callout--' + kind}>{title && <strong>{title}</strong>}<div>{children}</div></div>;
}

function Example({ title, code, children, surface = 'plain', pad = 32 }) {
  const [open, setOpen] = React.useState(false);
  return (
    <figure className="doc-example">
      {title && <figcaption className="doc-example__title">{title}</figcaption>}
      <div className={'doc-example__stage doc-example__stage--' + surface} style={{ padding: pad }}>{children}</div>
      {code && <>
        <button className="doc-example__toggle" onClick={() => setOpen(!open)}>{open ? 'Hide code' : 'Show code'}</button>
        {open && <Code>{code}</Code>}
      </>}
    </figure>
  );
}

function DoDont({ doEl, dontEl, doText, dontText }) {
  return (
    <div className="doc-dodont">
      <div className="doc-dodont__col doc-dodont__col--do"><div className="doc-dodont__stage">{doEl}</div><p><strong>Do</strong> {doText}</p></div>
      <div className="doc-dodont__col doc-dodont__col--dont"><div className="doc-dodont__stage">{dontEl}</div><p><strong>Don't</strong> {dontText}</p></div>
    </div>
  );
}

function PropsTable({ rows }) {
  return (
    <div className="doc-table-wrap"><table className="doc-table">
      <thead><tr><th>Prop</th><th>Type</th><th>Default</th><th>Description</th></tr></thead>
      <tbody>{rows.map(([n, t, d, desc]) => <tr key={n}><td><Tok>{n}</Tok></td><td className="doc-mono">{t}</td><td className="doc-mono">{d || '—'}</td><td>{desc}</td></tr>)}</tbody>
    </table></div>
  );
}

function Preview({ kind, name }) {
  const v = `var(${name})`;
  if (kind === 'color') return <span className="doc-swatch" style={{ background: v }}></span>;
  if (kind === 'space') return <span style={{ display: 'inline-block', height: 10, width: v, maxWidth: 160, background: 'var(--green)', borderRadius: 2 }}></span>;
  if (kind === 'radius') return <span style={{ display: 'inline-block', width: 40, height: 28, border: '1.5px solid var(--green)', background: 'var(--green-pale)', borderRadius: v }}></span>;
  if (kind === 'shadow') return <span style={{ display: 'inline-block', width: 48, height: 28, background: '#fff', borderRadius: 6, boxShadow: v }}></span>;
  if (kind === 'size') return <span style={{ display: 'inline-block', width: v, maxWidth: 140, height: 10, background: 'var(--ink)', borderRadius: 2 }}></span>;
  if (kind === 'font') return <span style={{ fontSize: v, lineHeight: 1, fontWeight: 700 }}>Aa</span>;
  if (kind === 'family') return <span style={{ fontFamily: v, fontSize: 20, fontWeight: 700 }}>Aa</span>;
  return null;
}
function kindOf(name, value) {
  const v = (value || '').trim();
  if (/^(#|oklch\(|rgba?\(|hsla?\(|transparent)/i.test(v)) return 'color';
  if (/shadow/.test(name)) return 'shadow';
  if (/radius/.test(name)) return 'radius';
  if (/font-(body|display|heading|wordmark|basis|right)/.test(name)) return 'family';
  if (/(font-size|line-height|font-weight|letter-spacing)/.test(name)
      && !/(height|icon-size|category|stat-|logo-size|social-size|card-width|card-media)/.test(name)) return 'font';
  if (/(^|-)space|padding|gap|gutter|inset|offset/.test(name)) return 'space';
  if (/(height|width|container|icon-size)/.test(name)) return 'size';
  return null;
}

function TokenTable({ tier, match, preview, limit }) {
  const t = useTokens();
  const [copied, setCopied] = React.useState('');
  if (!t) return <p className="doc-p">Loading tokens…</p>;
  const tiers = tier ? [tier] : ['interface', 'basic', 'primitive'];
  let rows = [];
  tiers.forEach(tr => Object.entries(t[tr] || {}).forEach(([n, v]) => { if (!match || match.test(n)) rows.push([tr, n, v]); }));
  if (limit) rows = rows.slice(0, limit);
  const copy = (n) => { navigator.clipboard && navigator.clipboard.writeText(`var(${n})`); setCopied(n); setTimeout(() => setCopied(''), 1200); };
  return (
    <div className="doc-table-wrap"><table className="doc-table doc-table--tokens">
      <thead><tr><th style={{ width: 70 }}></th><th>Token</th>{!tier && <th>Tier</th>}<th>References</th><th>Value</th></tr></thead>
      <tbody>{rows.map(([tr, n, v]) => {
        const resolved = resolveVar(n);
        return <tr key={n}>
          <td><Preview kind={preview || kindOf(n, resolved)} name={n} /></td>
          <td><button className="doc-copy" onClick={() => copy(n)} title="Copy var()">{copied === n ? 'Copied' : n}</button></td>
          {!tier && <td><span className={'doc-tier doc-tier--' + tr}>{tr}</span></td>}
          <td className="doc-mono doc-muted">{v.replace(/\/\*.*?\*\//g, '').trim().startsWith('var(') ? v.replace(/\/\*.*?\*\//g, '').trim() : '—'}</td>
          <td className="doc-mono">{resolved}</td>
        </tr>;
      })}</tbody>
    </table></div>
  );
}

function ContrastRow({ fg, bg, label }) {
  const [r, setR] = React.useState(null);
  React.useEffect(() => { setR(contrast(resolveVar(fg), resolveVar(bg))); }, []);
  const pass = r >= 4.5 ? 'AA' : r >= 3 ? 'AA Large' : 'Fail';
  return (
    <tr>
      <td><span className="doc-contrast" style={{ background: `var(${bg})`, color: `var(${fg})` }}>{label}</span></td>
      <td className="doc-mono">{fg}</td><td className="doc-mono">{bg}</td>
      <td className="doc-mono">{r ? r.toFixed(2) + ':1' : ''}</td>
      <td><span className={'doc-pass doc-pass--' + (pass === 'Fail' ? 'fail' : pass === 'AA' ? 'ok' : 'warn')}>{pass}</span></td>
    </tr>
  );
}

function TokenList({ names }) {
  return <div className="doc-toklist">{names.map(n => <Tok key={n}>{n}</Tok>)}</div>;
}

Object.assign(window, { DocsKit: { useTokens, resolveVar, Page, H2, H3, P, Rules, Code, Tok, Callout, Example, DoDont, PropsTable, TokenTable, ContrastRow, TokenList, Preview } });
