/* Authoring surface — DSL editor + live preview + parsed-entity sidebar + autocomplete */

const AuthoringSurface = () => {
  // We render a "frozen mid-keystroke" state — caret position fixed, autocomplete open.

  const codeLines = [
    { n: 1,  t: 'definition "derivative" {', tokens: [["k","definition"],[" ",""],["s",'"derivative"'],[" ",""],["p","{"]] },
    { n: 2,  t: '  """', tokens: [["w","  "],["s",'"""']] },
    { n: 3,  t: '  The instantaneous rate of change of a function at a point.', tokens: [["w","  "],["d","The instantaneous rate of change of a function at a point."]] },
    { n: 4,  t: '  """', tokens: [["w","  "],["s",'"""']] },
    { n: 5,  t: '', tokens: [] },
    { n: 6,  t: '  context: real_analysis, calculus', tokens: [["w","  "],["k","context"],["p",":"],[" "," "],["i","real_analysis"],["p",","],[" "," "],["i","calculus"]] },
    { n: 7,  t: '  given:   function f: R -> R,  point x in domain(f)', tokens: [["w","  "],["k","given"],["p",":"],["w","   "],["i","function"],[" "," "],["v","f"],["p",":"],[" "," "],["t","R"],[" "," "],["o","->"],[" "," "],["t","R"],["p",","],["w","  "],["i","point"],[" "," "],["v","x"],[" "," "],["k","in"],[" "," "],["i","domain"],["p","("],["v","f"],["p",")"]] },
    { n: 8,  t: '  notation: $f\'(x)$', tokens: [["w","  "],["k","notation"],["p",":"],[" "," "],["m","$f'(x)$"]] },
    { n: 9,  t: '  means:    $\\lim_{h \\to 0} \\frac{f(x+h) - f(x)}{h}$', tokens: [["w","  "],["k","means"],["p",":"],["w","    "],["m","$\\lim_{h \\to 0} \\frac{f(x+h) - f(x)}{h}$"]] },
    { n: 10, t: '  provided: this limit exists', tokens: [["w","  "],["k","provided"],["p",":"],[" "," "],["d","this limit exists"]] },
    { n: 11, t: '', tokens: [] },
    { n: 12, t: '  @aliases:   "differential", "instantaneous rate of change"', tokens: [["w","  "],["a","@aliases"],["p",":"],["w","   "],["s",'"differential"'],["p",","],[" "," "],["s",'"instantaneous rate of change"']] },
    { n: 13, t: '  @difficulty: 2', tokens: [["w","  "],["a","@difficulty"],["p",":"],[" "," "],["n","2"]] },
    { n: 14, t: '}', tokens: [["p","}"]] },
    { n: 15, t: '', tokens: [] },
    { n: 16, t: 'theorem "chain_rule" {', tokens: [["k","theorem"],[" "," "],["s",'"chain_rule"'],[" "," "],["p","{"]] },
    { n: 17, t: '  statement: $(f \\circ g)\'(x) = f\'(g(x)) \\cdot g\'(x)$', tokens: [["w","  "],["k","statement"],["p",":"],[" "," "],["m","$(f \\circ g)'(x) = f'(g(x)) \\cdot g'(x)$"]] },
    { n: 18, t: '  context:   real_analysis', tokens: [["w","  "],["k","context"],["p",":"],["w","   "],["i","real_analysis"]] },
    { n: 19, t: '  given:     differentiable f: R -> R,', tokens: [["w","  "],["k","given"],["p",":"],["w","     "],["i","differentiable"],[" "," "],["v","f"],["p",":"],[" "," "],["t","R"],[" "," "],["o","->"],[" "," "],["t","R"],["p",","]] },
    { n: 20, t: '             differentiable g: R -> R', tokens: [["w","             "],["i","differentiable"],[" "," "],["v","g"],[" "," "],["p",":"],[" "," "],["t","R"],[" "," "],["o","->"],[" "," "],["t","R"]] },
    { n: 21, t: '', tokens: [] },
    { n: 22, t: '  proof: by "limit_of_compo█', isCaret: true, autocomplete: true,
      tokens: [["w","  "],["k","proof"],["p",":"],[" "," "],["k","by"],[" "," "],["s",'"'],["i","limit_of_compo"],["caret",""]] },
    { n: 23, t: '}', tokens: [["p","}"]] },
  ];

  const tokenClass = {
    k: "tk-key", s: "tk-str", p: "tk-punc", d: "tk-doc", w: "tk-ws",
    i: "tk-ident", v: "tk-var", t: "tk-type", o: "tk-op", m: "tk-math",
    a: "tk-anno", n: "tk-num"
  };

  const Tex = ({ tex, display }) => {
    const ref = React.useRef(null);
    React.useEffect(() => {
      if (window.katex && ref.current) {
        try { window.katex.render(tex, ref.current, { displayMode: !!display, throwOnError: false }); } catch(e){}
      }
    }, [tex, display]);
    return <span ref={ref} />;
  };

  const autocompleteItems = [
    { k:"limit_of_composition", kind:"lemma", desc:"If lim g exists at a and lim f exists at g(a), then lim (f∘g) = f(lim g).", match:true },
    { k:"limit_of_composite_continuous", kind:"lemma", desc:"Special case under continuity.", match:false },
    { k:"limit_of_compose_uniform", kind:"lemma", desc:"Composition under uniform convergence.", match:false },
    { k:"limit_compose_metric", kind:"lemma", desc:"Generalization to metric spaces.", match:false },
  ];

  return (
    <div className="au">
      {/* top chrome */}
      <header className="au__top">
        <div className="au__top-l">
          <span className="t-meta">Project</span>
          <span className="cp__bc-cur t-ui">calculus.kgraph</span>
          <span className="cp__bc-sep">/</span>
          <span className="cp__bc-link t-ui">definitions</span>
          <span className="cp__bc-sep">/</span>
          <span className="cp__bc-cur t-ui">derivative.kg</span>
          <span className="au__dot-changed" title="Unsaved" />
        </div>
        <div className="au__top-r">
          <span className="t-meta">Validate</span>
          <span className="t-mono au__validate">✓ 0 errors · 1 warning</span>
          <span className="cp__top-divider" />
          <button className="btn btn--ghost cp__top-btn">Diff</button>
          <button className="btn btn--ghost cp__top-btn">Format</button>
          <button className="btn cp__top-btn">Commit ⌘↵</button>
        </div>
      </header>
      <hr className="rule" />

      <div className="au__layout">
        {/* left rail — file tree / entity outline */}
        <aside className="au__rail">
          <div className="au__rail-head">
            <span className="t-meta">Entities · this file</span>
            <span className="t-mono au__rail-count">02</span>
          </div>
          <hr className="rule-3" />
          <ul className="au__tree">
            <li className="au__tree-item is-active">
              <span className="type-chip" data-kind="definition">DEF</span>
              <span className="t-ui au__tree-label">derivative</span>
              <span className="t-mono au__tree-line">L 01</span>
            </li>
            <li className="au__tree-item">
              <span className="type-chip" data-kind="theorem">THM</span>
              <span className="t-ui au__tree-label">chain_rule</span>
              <span className="t-mono au__tree-line">L 16</span>
            </li>
          </ul>

          <div className="au__rail-head" style={{marginTop:"24px"}}>
            <span className="t-meta">Project tree</span>
          </div>
          <hr className="rule-3" />
          <ul className="au__filetree">
            <li className="au__file is-folder">▾ calculus</li>
            <li className="au__file au__file--child is-folder">▾ definitions</li>
            <li className="au__file au__file--gchild is-active">derivative.kg</li>
            <li className="au__file au__file--gchild">limit.kg</li>
            <li className="au__file au__file--gchild">continuity.kg</li>
            <li className="au__file au__file--gchild au__file--muted">function.kg</li>
            <li className="au__file au__file--child is-folder">▸ theorems</li>
            <li className="au__file au__file--child is-folder">▸ procedures</li>
            <li className="au__file au__file--child is-folder">▸ examples</li>
          </ul>

          <div className="au__rail-head" style={{marginTop:"24px"}}>
            <span className="t-meta">Lint</span>
          </div>
          <hr className="rule-3" />
          <ul className="au__lint">
            <li className="au__lint-item">
              <span className="t-mono au__lint-pos">L 22</span>
              <span className="au__lint-mark au__lint-mark--warn">!</span>
              <span className="t-ui">Unresolved cross-reference</span>
            </li>
          </ul>
        </aside>

        {/* editor */}
        <div className="au__editor">
          <div className="au__editor-head">
            <span className="t-meta">DSL · derivative.kg</span>
            <span className="au__tab-stops">
              <span className="t-mono">UTF-8</span>
              <span className="t-mono">LF</span>
              <span className="t-mono">SP·2</span>
            </span>
          </div>
          <div className="au__code">
            {codeLines.map((line) => (
              <div key={line.n} className={"au__line " + (line.isCaret ? "is-active" : "")}>
                <span className="au__gutter t-mono">{line.n.toString().padStart(2,"0")}</span>
                <span className="au__lineN">
                  {line.tokens.length === 0 ? <>&nbsp;</> :
                    line.tokens.map((tok, i) => {
                      if (tok[0] === "caret") return <span key={i} className="au__caret" />;
                      if (tok[0] === "m") return (
                        <span key={i} className="tk-math au__math-inline" title="$math$">
                          <span className="au__math-delim">$</span>
                          <Tex tex={tok[1].slice(1, -1)} />
                          <span className="au__math-delim">$</span>
                        </span>
                      );
                      return <span key={i} className={tokenClass[tok[0]] || ""}>{tok[1]}</span>;
                    })
                  }
                  {line.autocomplete && (
                    <div className="au__ac">
                      <div className="au__ac-head">
                        <span className="t-meta">Cross-reference · lemma | theorem</span>
                        <span className="t-mono au__ac-meta">4 matches</span>
                      </div>
                      <ul className="au__ac-list">
                        {autocompleteItems.map((it, i) => (
                          <li key={i} className={"au__ac-item " + (it.match ? "is-on" : "")}>
                            <span className="type-chip" data-kind={it.kind}>{it.kind.slice(0,3).toUpperCase()}</span>
                            <span className="t-mono au__ac-key">
                              {it.match ? <><span className="au__ac-hl">limit_of_compo</span>sition</> : it.k}
                            </span>
                            <span className="t-ui au__ac-desc">{it.desc}</span>
                          </li>
                        ))}
                      </ul>
                      <div className="au__ac-foot">
                        <span className="t-meta">↑↓ navigate</span>
                        <span className="t-meta">⏎ insert</span>
                        <span className="t-meta">⌘. open ref</span>
                      </div>
                    </div>
                  )}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* live preview */}
        <div className="au__preview">
          <div className="au__editor-head">
            <span className="t-meta">Rendered preview</span>
            <span className="au__tab-stops">
              <span className="t-mono">KaTeX</span>
              <span className="t-mono">live</span>
            </span>
          </div>
          <div className="au__pv">
            <div className="au__pv-card">
              <div className="au__pv-head">
                <span className="type-chip" data-kind="definition">Definition</span>
                <span className="t-mono au__pv-id">def.calc.derivative</span>
              </div>
              <h2 className="t-h2 au__pv-title">Derivative</h2>
              <p className="t-body au__pv-doc">
                The instantaneous rate of change of a function at a point.
              </p>
              <hr className="rule-3" />
              <dl className="au__pv-dl">
                <dt className="t-meta">Context</dt>
                <dd className="t-ui">real_analysis · calculus</dd>
                <dt className="t-meta">Given</dt>
                <dd className="t-body">function <Tex tex="f : \mathbb{R} \to \mathbb{R}" />, point <Tex tex="x \in \mathrm{domain}(f)" /></dd>
                <dt className="t-meta">Notation</dt>
                <dd className="au__pv-math"><Tex tex="f'(x)" display /></dd>
                <dt className="t-meta">Means</dt>
                <dd className="au__pv-math"><Tex tex="\lim_{h \to 0} \frac{f(x+h) - f(x)}{h}" display /></dd>
                <dt className="t-meta">Provided</dt>
                <dd className="t-body">this limit exists</dd>
              </dl>
              <hr className="rule-3" />
              <div className="au__pv-meta">
                <span className="t-meta">Aliases</span>
                <span className="t-ui">differential · instantaneous rate of change</span>
              </div>
              <div className="au__pv-meta">
                <span className="t-meta">Difficulty</span>
                <span className="cp__diff">
                  <span className="cp__diff-on" /><span className="cp__diff-on" /><span /><span /><span />
                </span>
              </div>
            </div>

            <div className="au__pv-card au__pv-card--theorem">
              <div className="au__pv-head">
                <span className="type-chip" data-kind="theorem">Theorem</span>
                <span className="t-mono au__pv-id">thm.calc.chain_rule</span>
                <span className="au__pv-warn t-mono">Unresolved ref</span>
              </div>
              <h2 className="t-h3 au__pv-title">Chain rule</h2>
              <div className="au__pv-math"><Tex tex="(f \circ g)'(x) = f'(g(x)) \cdot g'(x)" display /></div>
              <hr className="rule-3" />
              <div className="au__pv-meta">
                <span className="t-meta">Proof by</span>
                <span className="t-mono au__pv-incomplete">"limit_of_compo<span className="au__caret au__caret--small" />" <span className="au__pv-warn">▲ resolving</span></span>
              </div>
            </div>
          </div>
        </div>

        {/* right rail — parsed entity graph + status */}
        <aside className="au__entities">
          <div className="au__rail-head">
            <span className="t-meta">Parsed entities</span>
            <span className="t-mono au__rail-count">02 / 04</span>
          </div>
          <hr className="rule-3" />
          <svg viewBox="0 0 220 240" className="au__minigraph">
            {/* mini hierarchical view of what's being authored */}
            <line x1="40" y1="60" x2="40" y2="140" stroke="var(--rule-2)" strokeDasharray="2 2"/>
            <line x1="180" y1="60" x2="180" y2="140" stroke="var(--rule-2)" strokeDasharray="2 2"/>
            <line x1="40" y1="140" x2="110" y2="180" stroke="var(--accent)" strokeWidth="1.5"/>
            <line x1="180" y1="140" x2="110" y2="180" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="3 2"/>

            {/* upstream nodes (prereqs already declared elsewhere) */}
            <circle cx="40" cy="60" r="5" fill="var(--ink)"/>
            <text x="48" y="63" fontFamily="var(--font-ui)" fontSize="10" fill="var(--ink)">limit</text>
            <circle cx="180" cy="60" r="5" fill="var(--paper)" stroke="var(--ink)"/>
            <text x="138" y="63" fontFamily="var(--font-ui)" fontSize="10" fill="var(--ink)">limit_of_compo…</text>

            {/* this file's entities */}
            <circle cx="40" cy="140" r="6" fill="var(--accent)"/>
            <text x="48" y="143" fontFamily="var(--font-ui)" fontSize="10" fontWeight="600" fill="var(--ink)">derivative</text>

            <rect x="174" y="134" width="12" height="12" fill="var(--paper)" stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="2 2"/>
            <text x="138" y="143" fontFamily="var(--font-ui)" fontSize="10" fill="var(--ink-3)" fontStyle="italic">chain_rule (incomplete)</text>

            {/* downstream */}
            <circle cx="110" cy="180" r="4" fill="var(--paper)" stroke="var(--rule-2)"/>
            <text x="60" y="200" fontFamily="var(--font-ui)" fontSize="10" fill="var(--ink-4)">…30 dependents</text>
          </svg>

          <hr className="rule-3" />

          <div className="au__entity">
            <div className="au__entity-head">
              <span className="type-chip" data-kind="definition">DEF</span>
              <span className="t-mono au__entity-id">derivative</span>
              <span className="mastery-dot mastery-dot--mastered" />
            </div>
            <ul className="au__entity-meta">
              <li><span className="t-meta">Tokens</span><span className="t-mono">142</span></li>
              <li><span className="t-meta">In-deg</span><span className="t-mono">06</span></li>
              <li><span className="t-meta">Out-deg</span><span className="t-mono">28</span></li>
              <li><span className="t-meta">Has math</span><span className="t-mono">✓ 2 expr</span></li>
            </ul>
          </div>

          <div className="au__entity au__entity--warn">
            <div className="au__entity-head">
              <span className="type-chip" data-kind="theorem">THM</span>
              <span className="t-mono au__entity-id">chain_rule</span>
              <span className="mastery-dot mastery-dot--frontier" />
            </div>
            <ul className="au__entity-meta">
              <li><span className="t-meta">Tokens</span><span className="t-mono">71</span></li>
              <li><span className="t-meta">Proof refs</span><span className="t-mono">0 / 1</span></li>
              <li><span className="t-meta au__warn-em">Status</span><span className="t-mono au__warn-em">▲ pending</span></li>
            </ul>
          </div>

          <hr className="rule-3" />
          <div className="au__rail-head">
            <span className="t-meta">Compile</span>
            <span className="t-mono au__compile-time">14ms</span>
          </div>
          <ul className="au__compile">
            <li><span className="au__compile-mark">✓</span><span className="t-ui">Lex</span><span className="t-mono">213 tok</span></li>
            <li><span className="au__compile-mark">✓</span><span className="t-ui">Parse</span><span className="t-mono">2 ent</span></li>
            <li><span className="au__compile-mark">✓</span><span className="t-ui">Type-check</span><span className="t-mono">ok</span></li>
            <li><span className="au__compile-mark au__compile-mark--warn">!</span><span className="t-ui">Resolve refs</span><span className="t-mono">1 pending</span></li>
            <li><span className="au__compile-mark au__compile-mark--idle">○</span><span className="t-ui">KaTeX render</span><span className="t-mono">2/2</span></li>
            <li><span className="au__compile-mark au__compile-mark--idle">○</span><span className="t-ui">Embed (qwen3)</span><span className="t-mono">queued</span></li>
          </ul>
        </aside>
      </div>
    </div>
  );
};

window.AuthoringSurface = AuthoringSurface;
