/* ============================================================
   Lumino Design Site — Reusable content building blocks
   (<Section>, <CodeTabs>, <SwatchGrid>, etc.) available globally.
   ============================================================ */

const LDSUI = (function () {
  const { useState, useEffect, useRef } = React;

  // Section — anchor + heading
  function Section({ id, eyebrow, title, lead, children }) {
    return (
      <section id={id} style={{ scrollMarginTop: 70 }}>
        {eyebrow && <div className="lds-eyebrow">{eyebrow}</div>}
        {title && <h2 className="lds-h2" style={{ marginTop: 0 }}>{title}</h2>}
        {lead && <p className="lds-lead" style={{ fontSize: 15 }}>{lead}</p>}
        {children}
      </section>
    );
  }

  // Code block with copy
  function CodeBlock({ code, lang = "css", style }) {
    return (
      <div className="lds-code" style={style}>
        <button className="copy" data-copy={code}>Copy</button>
        <pre><code className={`lang-${lang}`}>{code}</code></pre>
      </div>
    );
  }

  // Tabbed code
  function CodeTabs({ tabs }) {
    const [i, setI] = useState(0);
    return (
      <div>
        <div className="lds-code-tabs">
          {tabs.map((t, k) => (
            <button key={k} className={"lds-code-tab " + (i === k ? "active" : "")} onClick={() => setI(k)}>{t.label}</button>
          ))}
        </div>
        <CodeBlock code={tabs[i].code} lang={tabs[i].lang} style={{ borderTopLeftRadius: 0, borderTopRightRadius: 0, marginTop: 0 }} />
      </div>
    );
  }

  // Swatch row
  function Swatch({ name, value, notes }) {
    // Render swatch via live CSS variable so it reflects the active theme/mode.
    // Also read the computed value for display so the hex stays truthful.
    const swatchRef = React.useRef(null);
    const [liveHex, setLiveHex] = React.useState(value);
    React.useEffect(() => {
      if (!swatchRef.current) return;
      const update = () => {
        try {
          const v = getComputedStyle(swatchRef.current).getPropertyValue(name).trim();
          if (v) setLiveHex(v);
        } catch (_) {}
      };
      update();
      const mo = new MutationObserver(update);
      mo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-mode", "data-theme", "data-density"] });
      return () => mo.disconnect();
    }, [name]);
    return (
      <div className="lds-swatch-row" data-copy={`var(${name})`} style={{ cursor: "pointer" }}>
        <div ref={swatchRef} className="lds-swatch" style={{ background: `var(${name}, ${value})` }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--color-text-primary)" }}>{name}</div>
          <div style={{ fontSize: 11, color: "var(--color-text-tertiary)", marginTop: 2 }}>
            {liveHex} {notes && <span style={{ marginLeft: 8 }}>· {notes}</span>}
          </div>
        </div>
        <button className="copy" style={{ position: "static", opacity: 1 }} data-copy={`var(${name})`}>Copy</button>
      </div>
    );
  }

  // Example frame — shows a live rendered UI block with a code panel
  function Example({ title, children, code, codeLang = "html", style }) {
    return (
      <div style={{ margin: "20px 0 28px" }}>
        {title && <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 8, color: "var(--color-text-primary)" }}>{title}</div>}
        <div style={{
          border: "1px solid var(--color-border-hairline)",
          borderRadius: "var(--radius-lg) var(--radius-lg) 0 0",
          background: "var(--color-surface-panel)",
          padding: 28,
          display: "flex", alignItems: "center", justifyContent: "center",
          minHeight: 100,
          ...style,
        }}>
          {children}
        </div>
        {code && (
          <div className="lds-code" style={{ marginTop: 0, borderTopLeftRadius: 0, borderTopRightRadius: 0, borderTop: "none" }}>
            <button className="copy" data-copy={code}>Copy</button>
            <pre><code>{code}</code></pre>
          </div>
        )}
      </div>
    );
  }

  // Property table for component docs
  function PropsTable({ rows }) {
    return (
      <table className="lds-table">
        <thead><tr><th>Prop</th><th>Type</th><th>Default</th><th>Notes</th></tr></thead>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i}>
              <td className="mono">{r.name}</td>
              <td className="mono" style={{ color: "var(--color-info)" }}>{r.type}</td>
              <td className="mono" style={{ color: "var(--color-text-tertiary)" }}>{r.default || "—"}</td>
              <td>{r.notes}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }

  // Anchor table of contents
  function TOC({ items }) {
    return (
      <nav style={{
        position: "sticky", top: 76, alignSelf: "flex-start",
        padding: "10px 14px", fontSize: 12,
        borderLeft: "1px solid var(--color-border-hairline)",
      }}>
        <div className="lds-side-label" style={{ padding: 0, marginBottom: 8 }}>On this page</div>
        {items.map((it) => (
          <a key={it.id} href={"#" + it.id} style={{
            display: "block", padding: "3px 0", color: "var(--color-text-tertiary)",
            fontSize: 12, transition: "color 140ms",
          }}>{it.label}</a>
        ))}
      </nav>
    );
  }

  return { Section, CodeBlock, CodeTabs, Swatch, Example, PropsTable, TOC };
})();

window.LDSUI = LDSUI;
