/* MapMdReveal.jsx — the "staff engineer would write this" document reveal */

const TOC = [
  { id: 'orientation', label: 'Orientation', icon: '◇' },
  { id: 'entrypoints', label: 'Entry points', icon: '→' },
  { id: 'invariants',  label: 'Invariants & contracts', icon: '≡' },
  { id: 'critical',    label: 'Critical paths', icon: '★' },
  { id: 'dragons',     label: 'Here be dragons', icon: '☠' },
  { id: 'conventions', label: 'Naming conventions', icon: 'Aa' },
  { id: 'dead',        label: 'Dead zones', icon: '✕' },
  { id: 'deps',        label: 'External deps', icon: '↗' },
];

const MapMdReveal = () => {
  const [active, setActive] = React.useState('orientation');
  const scrollRef = React.useRef(null);

  const onNavClick = (id) => {
    setActive(id);
    const el = document.getElementById('mapmd-' + id);
    const container = scrollRef.current;
    if (el && container) {
      container.scrollTo({ top: el.offsetTop - 16, behavior: 'smooth' });
    }
  };

  return (
    <section id="map" className="section">
      <div className="container-wide">
        <div className="section-head" style={{maxWidth: 780}}>
          <span className="eyebrow">The Artifact · <code style={{background:'var(--paper-2)', padding:'1px 6px', borderRadius:3, border:'1px solid var(--border-hair)', fontSize:11}}>.claude/map.md</code></span>
          <h2>A brief a senior engineer would write<br/><em>after a week in the codebase.</em></h2>
          <p>Not autogenerated slop. Opinionated, prioritized, human-tone. Claude Code reads it at session start and suddenly knows which three files matter — and which seventy don't.</p>
        </div>

        <div className="mapmd">
          <aside className="mapmd-toc">
            <div className="mapmd-toc-head">
              <div className="mapmd-toc-title">map.md</div>
              <div className="mapmd-toc-meta">14,204 words · built 2m ago</div>
            </div>
            {TOC.map(t => (
              <button
                key={t.id}
                className={`mapmd-toc-item ${active===t.id?'active':''}`}
                onClick={() => onNavClick(t.id)}
              >
                <span className="mapmd-toc-icon">{t.icon}</span>
                <span>{t.label}</span>
              </button>
            ))}
            <div className="mapmd-toc-foot">
              <div className="mapmd-toc-meta">Regenerated on every push via <code style={{fontSize:11}}>pre-push</code> hook</div>
            </div>
          </aside>

          <div className="mapmd-doc" ref={scrollRef}>
            <div className="mapmd-header">
              <div className="mapmd-meta">auto-generated · ~/repos/acme-monorepo · main @ a1b2c3d</div>
              <h1 className="mapmd-h1">acme-monorepo</h1>
              <p className="mapmd-tldr">
                A multi-tenant events platform. Four services (<code>api</code>, <code>billing</code>,
                <code>workers</code>, <code>admin</code>) share one Postgres and a Redis bus. Python
                handles background jobs; TypeScript handles everything customer-facing. The auth module
                is load-bearing — touch it carefully.
              </p>
            </div>

            <MapSection id="orientation" title="Orientation" n="01">
              <p>If you have five minutes, read three files:</p>
              <ul className="mapmd-ul">
                <li><code>src/app.ts</code> — the HTTP entrypoint; middleware order is <em>not</em> alphabetical.</li>
                <li><code>src/auth/session.ts</code> — the only module every request crosses.</li>
                <li><code>packages/api-core/headers.ts</code> — where response envelopes are shaped.</li>
              </ul>
              <div className="mapmd-note mapmd-note-clay">
                <div className="mapmd-note-k">Tone</div>
                This codebase is conservative. Patterns are repeated intentionally; the team prefers duplication over shared abstractions younger than a quarter old.
              </div>
            </MapSection>

            <MapSection id="entrypoints" title="Entry points" n="02">
              <p>Three production processes and two cron workers:</p>
              <table className="mapmd-table">
                <tbody>
                  <tr><td><code>src/app.ts</code></td><td>HTTP · api.acme.com</td><td>port 4000</td></tr>
                  <tr><td><code>src/admin.ts</code></td><td>HTTP · admin.acme.com</td><td>port 4001 · internal</td></tr>
                  <tr><td><code>workers/billing.py</code></td><td>Celery · billing queue</td><td>stripe webhooks</td></tr>
                  <tr><td><code>workers/dispatch.py</code></td><td>Celery · events queue</td><td>segment fan-out</td></tr>
                  <tr><td><code>cron/rollup.ts</code></td><td>nightly · 02:00 UTC</td><td>rollups table</td></tr>
                </tbody>
              </table>
            </MapSection>

            <MapSection id="invariants" title="Invariants & contracts" n="03">
              <p>Things that must remain true. If a change would break one of these, stop and ask.</p>
              <ol className="mapmd-ol">
                <li><strong>Every public route mounts <code>authMiddleware</code> before <code>rateLimitMiddleware</code>.</strong> Reversing the order leaks rate-limit headers to unauthenticated callers.</li>
                <li><strong>Writes to <code>billing.*</code> tables go through <code>lib/billing/ledger.ts</code>.</strong> Direct SQL writes break the audit log.</li>
                <li><strong><code>X-Request-Id</code> propagates through every fetch.</strong> The tracer asserts its presence and will throw in dev.</li>
              </ol>
            </MapSection>

            <MapSection id="critical" title="Critical paths" n="04">
              <p>The three flows worth knowing cold:</p>
              <div className="mapmd-path">
                <div className="mapmd-path-k">Sign-in</div>
                <code className="mapmd-path-v">web/portal → auth/session.verify → lib/crypto.rotatingKey → db/redis.get</code>
              </div>
              <div className="mapmd-path">
                <div className="mapmd-path-k">Charge</div>
                <code className="mapmd-path-v">api/billing.charge → ext/stripe.createCharge → ledger.record → events.emit</code>
              </div>
              <div className="mapmd-path">
                <div className="mapmd-path-k">Event dispatch</div>
                <code className="mapmd-path-v">workers/dispatch → segment.track → metrics.count → alert.maybe</code>
              </div>
            </MapSection>

            <MapSection id="dragons" title="Here be dragons" n="05" warn>
              <div className="mapmd-note mapmd-note-red">
                <div className="mapmd-note-k">Don't refactor src/utils/old_payment.py</div>
                It predates the ledger. Two enterprise customers still trigger it via legacy webhooks.
                No tests. The person who wrote it left in 2022. If you must touch it, add a test first.
              </div>
              <div className="mapmd-note mapmd-note-red">
                <div className="mapmd-note-k">lib/features has two flag systems</div>
                The original string-based system and a newer typed one. Don't unify them without three weeks
                to burn — every surface reads from both.
              </div>
            </MapSection>

            <MapSection id="conventions" title="Naming conventions" n="06">
              <ul className="mapmd-ul">
                <li>Files: <code>snake_case.ts</code> for modules; <code>PascalCase.tsx</code> for React components.</li>
                <li>Public route handlers live in <code>src/routes/public/*</code>; internal in <code>src/routes/admin/*</code>.</li>
                <li>Domain types live next to their service: <code>services/billing/types.ts</code>, never a global <code>types.ts</code>.</li>
                <li>Tests mirror source: <code>src/x/y.ts</code> ↔ <code>tests/unit/x/y.spec.ts</code>.</li>
              </ul>
            </MapSection>

            <MapSection id="dead" title="Dead zones" n="07">
              <p>Detected by absence from the call graph and zero recent edits. Safe to delete in a dedicated PR:</p>
              <ul className="mapmd-ul mapmd-ul-dim">
                <li><code>src/experimental/ml_pricing/</code> — never imported, last touched 412 days ago.</li>
                <li><code>packages/legacy-metrics/</code> — superseded by <code>lib/tracing</code>.</li>
                <li><code>scripts/migrate_v0_to_v1.py</code> — single-shot migration, completed Q3 2024.</li>
              </ul>
            </MapSection>

            <MapSection id="deps" title="External dependencies" n="08">
              <div className="mapmd-path">
                <div className="mapmd-path-k">Stripe</div>
                <div className="mapmd-path-v mapmd-path-plain">webhook signature verified in <code>api/billing/webhook.ts:32</code>. Retries are idempotent via <code>idempotency_key</code>.</div>
              </div>
              <div className="mapmd-path">
                <div className="mapmd-path-k">Segment</div>
                <div className="mapmd-path-v mapmd-path-plain">fire-and-forget; failures log but never throw. Called from <code>lib/analytics.track</code>.</div>
              </div>
              <div className="mapmd-path">
                <div className="mapmd-path-k">Postgres</div>
                <div className="mapmd-path-v mapmd-path-plain">single writer. Long queries go through <code>db/read_replica.ts</code>. No ORM — query builder only.</div>
              </div>
            </MapSection>

            <div className="mapmd-foot">
              <div className="mapmd-foot-k">— generated by cartographer v0.3.1 · 38m exploration · Opus 4.7</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

const MapSection = ({ id, title, n, warn, children }) => (
  <section id={`mapmd-${id}`} className={`mapmd-section ${warn?'mapmd-section-warn':''}`}>
    <div className="mapmd-section-head">
      <span className="mapmd-section-n">{n}</span>
      <h2 className="mapmd-h2">{title}</h2>
    </div>
    {children}
  </section>
);

window.MapMdReveal = MapMdReveal;
