/* Concept page — derivative
   Source text adapted from OpenStax Calculus Volume 1, §3.1
   CC-BY 4.0 */

const ConceptPageDerivative = () => {
  const [hValue, setHValue] = React.useState(0.5);
  const [funcKey, setFuncKey] = React.useState("xsq");
  const [pointX, setPointX] = React.useState(1.0);

  // ── Functions for explorers ─────────────────────────────
  const FUNCS = {
    xsq: { label: "f(x) = x²", tex: "x^2", f: (x) => x*x, df: (x) => 2*x, dlabel: "f'(x) = 2x" },
    sin: { label: "f(x) = sin(x)", tex: "\\sin(x)", f: Math.sin, df: Math.cos, dlabel: "f'(x) = cos(x)" },
    exp: { label: "f(x) = eˣ", tex: "e^{x}", f: Math.exp, df: Math.exp, dlabel: "f'(x) = eˣ" },
  };
  const fn = FUNCS[funcKey];

  // ── KaTeX render helper ─────────────────────────────────
  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} />;
  };

  return (
    <div className="cp">
      {/* ── Top chrome — masthead/breadcrumb ─────────────── */}
      <header className="cp__top">
        <div className="cp__top-l">
          <span className="t-mono" style={{color:"var(--ink-4)"}}>§ 03.01</span>
          <span className="cp__bc-sep">/</span>
          <a className="cp__bc-link" href="#">Mathematics</a>
          <span className="cp__bc-sep">/</span>
          <a className="cp__bc-link" href="#">Calculus</a>
          <span className="cp__bc-sep">/</span>
          <a className="cp__bc-link" href="#">Differentiation</a>
          <span className="cp__bc-sep">/</span>
          <span className="cp__bc-cur">Derivative</span>
        </div>
        <div className="cp__top-r">
          <span className="t-meta">Mastery</span>
          <span className="mastery-dot mastery-dot--frontier" />
          <span className="t-mono cp__mastery-num">62%</span>
          <span className="cp__top-divider" />
          <button className="btn btn--ghost cp__top-btn">View graph →</button>
          <button className="btn cp__top-btn">Author</button>
        </div>
      </header>

      <hr className="rule" />

      {/* ── Title block ───────────────────────────────────── */}
      <section className="cp__title">
        <div className="cp__title-grid">
          <div className="cp__title-meta">
            <span className="type-chip" data-kind="definition">Definition</span>
            <div className="cp__id-block">
              <div className="t-meta">Identifier</div>
              <div className="t-mono cp__id">def.calc.derivative</div>
            </div>
            <div className="cp__id-block">
              <div className="t-meta">Edges</div>
              <div className="t-mono cp__id">14 in · 28 out</div>
            </div>
            <div className="cp__id-block">
              <div className="t-meta">Difficulty</div>
              <div className="cp__diff">
                <span className="cp__diff-on" /><span className="cp__diff-on" /><span /><span /><span />
              </div>
            </div>
          </div>
          <div className="cp__title-main">
            <h1 className="t-display cp__title-h">Derivative</h1>
            <p className="cp__title-sub t-lead">
              The instantaneous rate of change of a function at a point. <em className="cp__title-em">Foundational object of differential calculus; equivalent to the slope of the tangent line to the graph of <Tex tex="f" /> at <Tex tex="x" />.</em>
            </p>
          </div>
          <aside className="cp__title-aside">
            <div className="t-meta cp__aside-h">Aliases</div>
            <ul className="cp__aliases">
              <li>differential</li>
              <li>instantaneous rate of change</li>
              <li>slope of tangent</li>
            </ul>
            <div className="t-meta cp__aside-h" style={{marginTop:"24px"}}>Notation</div>
            <ul className="cp__notation">
              <li><Tex tex="f'(x)" /><span className="cp__notation-by">Lagrange</span></li>
              <li><Tex tex="\frac{df}{dx}" /><span className="cp__notation-by">Leibniz</span></li>
              <li><Tex tex="\dot{f}" /><span className="cp__notation-by">Newton</span></li>
              <li><Tex tex="Df" /><span className="cp__notation-by">Euler</span></li>
            </ul>
          </aside>
        </div>
      </section>

      <hr className="rule-thick" />

      {/* ── §1 Definition + prerequisites two-up ──────────── */}
      <section className="cp__section">
        <div className="cp__section-head">
          <span className="t-mono cp__section-num">01</span>
          <span className="t-meta">Formal definition</span>
        </div>
        <hr className="rule-2" />
        <div className="cp__defn-grid">
          <div className="cp__defn-body">
            <p className="t-body">
              Let <Tex tex="f" /> be a function defined on an open interval containing the point <Tex tex="a" />. The <strong>derivative</strong> of <Tex tex="f" /> at <Tex tex="a" />, denoted <Tex tex="f'(a)" />, is defined by
            </p>
            <div className="cp__display-math">
              <span className="fig-number cp__eq-num">(3.1.1)</span>
              <Tex tex="f'(a) \;=\; \lim_{h \to 0}\, \frac{f(a + h) - f(a)}{h}" display />
            </div>
            <p className="t-body">
              provided this limit exists. If the limit fails to exist, <Tex tex="f" /> is said to be <em>not differentiable</em> at <Tex tex="a" />. When the derivative exists at every point of an interval <Tex tex="I" />, the resulting function <Tex tex="f': I \to \mathbb{R}" /> is itself called <em>the derivative of <Tex tex="f" /></em>.
            </p>
            <p className="t-body">
              Geometrically, <Tex tex="f'(a)" /> is the slope of the tangent line to the graph of <Tex tex="f" /> at the point <Tex tex="\bigl(a, f(a)\bigr)" />. The defining quotient <Tex tex="\bigl[f(a+h) - f(a)\bigr]/h" /> is the slope of the secant line through <Tex tex="\bigl(a, f(a)\bigr)" /> and <Tex tex="\bigl(a+h, f(a+h)\bigr)" />; the derivative is the limit of these secant slopes as the second point approaches the first.
            </p>
          </div>
          <aside className="cp__prereq">
            <div className="cp__prereq-head">
              <span className="t-meta">Prerequisites</span>
              <span className="t-mono cp__prereq-count">06</span>
            </div>
            <hr className="rule-3" />
            <ul className="cp__prereq-list">
              <li className="cp__prereq-item">
                <span className="mastery-dot mastery-dot--mastered" />
                <a className="cp__prereq-link" href="#">Function</a>
                <span className="t-mono cp__prereq-pct">98%</span>
              </li>
              <li className="cp__prereq-item">
                <span className="mastery-dot mastery-dot--mastered" />
                <a className="cp__prereq-link" href="#">Real numbers</a>
                <span className="t-mono cp__prereq-pct">94%</span>
              </li>
              <li className="cp__prereq-item">
                <span className="mastery-dot mastery-dot--mastered" />
                <a className="cp__prereq-link" href="#">Limit of a function</a>
                <span className="t-mono cp__prereq-pct">88%</span>
              </li>
              <li className="cp__prereq-item">
                <span className="mastery-dot mastery-dot--learning" />
                <a className="cp__prereq-link" href="#">Continuity</a>
                <span className="t-mono cp__prereq-pct">71%</span>
              </li>
              <li className="cp__prereq-item">
                <span className="mastery-dot mastery-dot--learning" />
                <a className="cp__prereq-link" href="#">Slope of a line</a>
                <span className="t-mono cp__prereq-pct">82%</span>
              </li>
              <li className="cp__prereq-item">
                <span className="mastery-dot mastery-dot--frontier" />
                <a className="cp__prereq-link" href="#">Secant line</a>
                <span className="t-mono cp__prereq-pct">—</span>
              </li>
            </ul>
            <hr className="rule-3" />
            <a className="cp__prereq-foot t-ui" href="#">Open prerequisite graph →</a>
          </aside>
        </div>
      </section>

      {/* ── §2 Explorable — tangent slider ───────────────── */}
      <section className="cp__section cp__section--accent">
        <div className="cp__section-head">
          <span className="t-mono cp__section-num">02</span>
          <span className="t-meta">Explorable · tangent as the limit of secants</span>
          <span className="cp__section-tag">Figure 3.1.A</span>
        </div>
        <hr className="rule-2" />
        <div className="cp__explore-grid">
          <div className="cp__explore-plot">
            <TangentPlot func={fn} h={hValue} a={pointX} Tex={Tex} />
          </div>
          <div className="cp__explore-controls">
            <div className="cp__ctrl-block">
              <div className="t-meta">Function</div>
              <div className="cp__seg">
                {Object.entries(FUNCS).map(([k, v]) => (
                  <button key={k}
                    className={"cp__seg-btn " + (funcKey===k ? "is-on": "")}
                    onClick={() => setFuncKey(k)}>
                    <Tex tex={v.tex} />
                  </button>
                ))}
              </div>
            </div>
            <div className="cp__ctrl-block">
              <div className="cp__ctrl-row">
                <div className="t-meta">Point a</div>
                <div className="t-mono cp__ctrl-val">{pointX.toFixed(3)}</div>
              </div>
              <input type="range" className="swiss"
                min="-2" max="2" step="0.05" value={pointX}
                onChange={(e) => setPointX(parseFloat(e.target.value))} />
              <div className="cp__ctrl-axis">
                <span className="t-mono">−2</span><span className="t-mono">0</span><span className="t-mono">+2</span>
              </div>
            </div>
            <div className="cp__ctrl-block">
              <div className="cp__ctrl-row">
                <div className="t-meta">Step h</div>
                <div className="t-mono cp__ctrl-val">{hValue.toFixed(4)}</div>
              </div>
              <input type="range" className="swiss"
                min="0.001" max="1.5" step="0.001" value={hValue}
                onChange={(e) => setHValue(parseFloat(e.target.value))} />
              <div className="cp__ctrl-axis">
                <span className="t-mono">0.001</span><span className="t-mono">0.5</span><span className="t-mono">1.5</span>
              </div>
            </div>
            <hr className="rule-3" />
            <div className="cp__readout">
              <div className="cp__readout-row">
                <span className="t-meta">Secant slope</span>
                <span className="t-mono cp__readout-val">
                  {(((fn.f(pointX + hValue) - fn.f(pointX)) / hValue)).toFixed(4)}
                </span>
              </div>
              <div className="cp__readout-row cp__readout-row--accent">
                <span className="t-meta">f'(a) — exact</span>
                <span className="t-mono cp__readout-val">{fn.df(pointX).toFixed(4)}</span>
              </div>
              <div className="cp__readout-row">
                <span className="t-meta">Error |secant − f'|</span>
                <span className="t-mono cp__readout-val">
                  {Math.abs(((fn.f(pointX + hValue) - fn.f(pointX)) / hValue) - fn.df(pointX)).toFixed(5)}
                </span>
              </div>
            </div>
            <p className="cp__explore-caption t-body">
              Drag <em>h</em> toward zero. The secant rotates into the tangent. The numeric error collapses to the precision of the underlying limit.
            </p>
          </div>
        </div>
      </section>

      {/* ── §3 Limit table ──────────────────────────────── */}
      <section className="cp__section">
        <div className="cp__section-head">
          <span className="t-mono cp__section-num">03</span>
          <span className="t-meta">Numerical limit · the difference quotient as h → 0</span>
          <span className="cp__section-tag">Table 3.1.A</span>
        </div>
        <hr className="rule-2" />
        <div className="cp__table-wrap">
          <p className="cp__table-lead t-body">
            Evaluating the difference quotient for {fn.label} at <Tex tex={`a = ${pointX.toFixed(2)}`} /> over a sequence of decreasing <Tex tex="h" />:
          </p>
          <LimitTable func={fn} a={pointX} Tex={Tex} />
        </div>
      </section>

      {/* ── §4 Theorems involving derivative ────────────── */}
      <section className="cp__section">
        <div className="cp__section-head">
          <span className="t-mono cp__section-num">04</span>
          <span className="t-meta">Theorems involving derivative</span>
          <span className="cp__section-tag">14 results</span>
        </div>
        <hr className="rule-2" />
        <div className="cp__thm-grid">
          {[
            {n:"3.2.1", k:"theorem", title:"Differentiability implies continuity", body:<>If <Tex tex="f"/> is differentiable at <Tex tex="a"/>, then <Tex tex="f"/> is continuous at <Tex tex="a"/>. The converse is false: <Tex tex="|x|"/> at <Tex tex="0"/>.</>, refs:["limit_of_difference_quotient","continuity"], mastery:"mastered"},
            {n:"3.3.1", k:"theorem", title:"Sum rule", body:<><Tex tex="(f+g)'(x) = f'(x) + g'(x)"/>, whenever both derivatives exist. Linearity in the function argument.</>, refs:["limit_sum_rule","derivative"], mastery:"mastered"},
            {n:"3.3.2", k:"theorem", title:"Product rule", body:<><Tex tex="(fg)'(x) = f'(x)\,g(x) + f(x)\,g'(x)"/>. Proven by adding and subtracting <Tex tex="f(x+h)g(x)"/> in the numerator.</>, refs:["limit_product_rule","derivative"], mastery:"learning"},
            {n:"3.3.3", k:"theorem", title:"Chain rule", body:<><Tex tex="(f \circ g)'(x) = f'(g(x))\,g'(x)"/>. The cornerstone of differentiating composite functions.</>, refs:["limit_of_composition","derivative"], mastery:"frontier"},
            {n:"3.4.1", k:"theorem", title:"Mean value theorem", body:<>If <Tex tex="f"/> is continuous on <Tex tex="[a,b]"/> and differentiable on <Tex tex="(a,b)"/>, there exists <Tex tex="c \in (a,b)"/> with <Tex tex="f'(c) = \tfrac{f(b)-f(a)}{b-a}"/>.</>, refs:["rolles_theorem","derivative"], mastery:"locked"},
            {n:"3.5.1", k:"lemma", title:"Carathéodory's characterization", body:<><Tex tex="f"/> is differentiable at <Tex tex="a"/> iff there exists a function <Tex tex="\phi"/> continuous at <Tex tex="a"/> with <Tex tex="f(x) - f(a) = \phi(x)(x - a)"/>.</>, refs:["continuity","derivative"], mastery:"locked"},
          ].map((t) => (
            <article key={t.n} className="cp__thm">
              <header className="cp__thm-head">
                <span className="fig-number">{t.n}</span>
                <span className="type-chip" data-kind={t.k}>{t.k}</span>
                <span className={"mastery-dot mastery-dot--" + t.mastery} />
              </header>
              <h3 className="t-h4 cp__thm-title">{t.title}</h3>
              <p className="t-body cp__thm-body">{t.body}</p>
              <footer className="cp__thm-foot">
                <span className="t-meta">Uses</span>
                {t.refs.map((r,i) => <a key={i} className="cp__thm-ref t-mono" href="#">{r}</a>)}
              </footer>
            </article>
          ))}
        </div>
      </section>

      {/* ── §5 Procedures ────────────────────────────────── */}
      <section className="cp__section">
        <div className="cp__section-head">
          <span className="t-mono cp__section-num">05</span>
          <span className="t-meta">Procedures · computational techniques</span>
          <span className="cp__section-tag">04 procedures</span>
        </div>
        <hr className="rule-2" />
        <div className="cp__proc-list">
          {[
            ["Differentiate from first principles","Apply the limit definition directly. 4 steps.","mastered"],
            ["Power rule","Differentiate xⁿ as nxⁿ⁻¹. 2 steps.","mastered"],
            ["Product / quotient rule","Differentiate fg or f/g. 5 steps.","learning"],
            ["Chain rule for composite functions","Decompose, differentiate, recombine. 6 steps.","frontier"],
          ].map(([t, sub, m], i) => (
            <a key={i} className="cp__proc" href="#">
              <span className="t-mono cp__proc-n">P.{(i+1).toString().padStart(2,"0")}</span>
              <span className={"mastery-dot mastery-dot--" + m} />
              <span className="cp__proc-title t-h4">{t}</span>
              <span className="cp__proc-sub t-ui">{sub}</span>
              <span className="cp__proc-arrow">→</span>
            </a>
          ))}
        </div>
      </section>

      {/* ── §6 Embedding neighborhood ────────────────────── */}
      <section className="cp__section">
        <div className="cp__section-head">
          <span className="t-mono cp__section-num">06</span>
          <span className="t-meta">Embedding neighborhood · concepts near in semantic space</span>
          <span className="cp__section-tag">qwen3 · 1024-dim</span>
        </div>
        <hr className="rule-2" />
        <EmbeddingNeighborhood />
      </section>

      {/* ── footer ───────────────────────────────────────── */}
      <footer className="cp__foot">
        <div className="cp__foot-l">
          <span className="t-meta">Source</span>
          <span className="t-ui">OpenStax Calculus Volume 1, §3.1 — adapted under CC-BY 4.0</span>
        </div>
        <div className="cp__foot-r">
          <span className="t-meta">Last review · 2026-04-29 · FSRS stability 14.2d</span>
        </div>
      </footer>
    </div>
  );
};

window.ConceptPageDerivative = ConceptPageDerivative;
