/* global React */
const { useState: useTState } = React;

// ============================================================
// PAGE HEADER (breadcrumbs, title, last-updated)
// ============================================================
function PageHeader({ crumbs = [], title, lastUpdated, summary }) {
  return (
    <header className="page-header">
      <nav className="breadcrumbs" aria-label="Breadcrumb">
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            <a href="#">{c}</a>
            {i < crumbs.length - 1 && <span className="breadcrumb-sep">/</span>}
          </React.Fragment>
        ))}
      </nav>
      <h1 className="page-title">{title}</h1>
      {summary && <p className="page-summary">{summary}</p>}
      {lastUpdated && (
        <div className="page-meta">
          <span className="page-meta-dot" />
          Updated {lastUpdated}
        </div>
      )}
    </header>
  );
}

// ============================================================
// PROSE — typography sample block
// ============================================================
function Prose({ children }) {
  return <div className="prose">{children}</div>;
}

// ============================================================
// CODE BLOCK (Mission Control aesthetic)
// ============================================================
function CodeBlock({ filename, lang = "php", children, lineNumbers = false }) {
  const [copied, setCopied] = useTState(false);
  const onCopy = () => {
    setCopied(true);
    setTimeout(() => setCopied(false), 1400);
  };

  // children is array of {type, text} tokens, or a string
  const rendered = Array.isArray(children) ? children : [{ text: children }];

  return (
    <div className="codeblock">
      <div className="codeblock-header">
        <div className="codeblock-dots">
          <span /><span /><span />
        </div>
        {filename && <div className="codeblock-filename">{filename}</div>}
        <div className="codeblock-lang">{lang}</div>
        <button className="codeblock-copy" onClick={onCopy} aria-label="Copy">
          {copied ? (
            <><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg> Copied</>
          ) : (
            <><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg> Copy</>
          )}
        </button>
      </div>
      <pre className="codeblock-pre">
        <code>
          {rendered.map((line, i) => (
            <div key={i} className="codeblock-line">
              {lineNumbers && <span className="codeblock-ln">{i + 1}</span>}
              <span dangerouslySetInnerHTML={{ __html: line.text }} />
            </div>
          ))}
        </code>
      </pre>
    </div>
  );
}

// Token helper — wraps text in a syntax-color span
function tk(cls, text) {
  return `<span class="tk-${cls}">${text}</span>`;
}

// Pre-tokenized PHP sample (saves us writing a real lexer)
const phpSample = [
  { text: `${tk("kw", "namespace")} ${tk("ns", "App\\\\Controllers")};` },
  { text: `` },
  { text: `${tk("kw", "use")} ${tk("ns", "Nibiru\\\\Controller")};` },
  { text: `${tk("kw", "use")} ${tk("ns", "Nibiru\\\\Form")};` },
  { text: `` },
  { text: `${tk("kw", "class")} ${tk("cn", "BookingController")} ${tk("kw", "extends")} ${tk("cn", "Controller")} {` },
  { text: `    ${tk("kw", "public")} ${tk("kw", "function")} ${tk("fn", "create")}(${tk("var", "$req")}) {` },
  { text: `        ${tk("var", "$form")} = ${tk("kw", "new")} ${tk("cn", "Form")}();` },
  { text: `        ${tk("var", "$form")}->${tk("fn", "addInputType")}(${tk("str", "'email'")}, ${tk("str", "'address'")});` },
  { text: `        ${tk("kw", "return")} ${tk("var", "$this")}->${tk("fn", "view")}(${tk("str", "'booking/create'")}, [` },
  { text: `            ${tk("str", "'form'")} => ${tk("var", "$form")},` },
  { text: `        ]);` },
  { text: `    }` },
  { text: `}` },
];

const sqlSample = [
  { text: `${tk("kw", "SELECT")} ${tk("var", "id")}, ${tk("var", "title")}, ${tk("var", "created_at")}` },
  { text: `${tk("kw", "FROM")} ${tk("cn", "bookings")}` },
  { text: `${tk("kw", "WHERE")} ${tk("var", "user_id")} = ${tk("num", "42")}` },
  { text: `  ${tk("kw", "AND")} ${tk("var", "status")} = ${tk("str", "'confirmed'")}` },
  { text: `${tk("kw", "ORDER BY")} ${tk("var", "created_at")} ${tk("kw", "DESC")}` },
  { text: `${tk("kw", "LIMIT")} ${tk("num", "20")};` },
];

const yamlSample = [
  { text: `${tk("kw", "app")}:` },
  { text: `  ${tk("kw", "name")}: ${tk("str", "Nibiru")}` },
  { text: `  ${tk("kw", "version")}: ${tk("str", "2.0.0")}` },
  { text: `  ${tk("kw", "modules")}:` },
  { text: `    - ${tk("str", "auth")}` },
  { text: `    - ${tk("str", "blog")}` },
  { text: `    - ${tk("str", "api")}` },
];

// ============================================================
// CALLOUTS (cosmic-coded)
// ============================================================
function Callout({ kind = "note", title, children }) {
  const icons = {
    note:    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="3" fill="currentColor"/><circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>,
    tip:     <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2 14 8l6 1-4.5 4 1 6-4.5-3-4.5 3 1-6L4 9l6-1z"/></svg>,
    warning: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M12 7v6M12 16h.01"/></svg>,
    danger:  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m12 2 10 18H2L12 2zM12 9v4M12 17h.01"/></svg>,
  };
  const labels = { note: "Note", tip: "Tip", warning: "Warning", danger: "Danger" };
  return (
    <div className={"callout callout-" + kind}>
      <div className="callout-glyph">{icons[kind]}</div>
      <div className="callout-body">
        <div className="callout-title">{title || labels[kind]}</div>
        <div className="callout-content">{children}</div>
      </div>
    </div>
  );
}

// ============================================================
// TABLE
// ============================================================
function DocTable({ headers, rows }) {
  return (
    <div className="doc-table-wrap">
      <table className="doc-table">
        <thead>
          <tr>{headers.map((h, i) => <th key={i}>{h}</th>)}</tr>
        </thead>
        <tbody>
          {rows.map((row, i) => (
            <tr key={i}>
              {row.map((cell, j) => <td key={j}>{cell}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { PageHeader, Prose, CodeBlock, Callout, DocTable, phpSample, sqlSample, yamlSample, tk });
