// Subway-map page approach
// The map: three horizontal "lines" (one per AI mode) running across
// the four phases. Stations are tools, colored by mode.

const { useState } = React;

function SubwayMap() {
  const phases = window.UXW_PHASES;
  const rows = window.UXW_ROWS;
  const modes = window.UXW_MODES;
  const summaries = window.UXW_PROMPT_SUMMARIES;

  // ─── MAP LAYOUT ────────────────────────────────────────────────────
  const W = 1100;
  const H = 540;
  const padL = 150;
  const padR = 40;
  const phaseY = 80;
  const modeYs = { automate: 180, augment: 320, alone: 460 };
  const phaseWidth = (W - padL - padR) / phases.length;

  // Split a tool name onto up to 2 lines at the most balanced word break.
  function splitName(name) {
    if (name.length <= 12) return [name];
    const words = name.split(' ');
    if (words.length === 1) return [name];
    // Find the split that minimizes the longer line's length
    let best = 1, bestMax = Infinity;
    for (let i = 1; i < words.length; i++) {
      const a = words.slice(0, i).join(' ').length;
      const b = words.slice(i).join(' ').length;
      const mx = Math.max(a, b);
      if (mx < bestMax) { bestMax = mx; best = i; }
    }
    return [words.slice(0, best).join(' '), words.slice(best).join(' ')];
  }

  // Layout: within each phase, distribute ALL tools evenly along x,
  // and within that phase, alternate labels above/below the mode line.
  const stations = [];
  phases.forEach((p, pi) => {
    const phaseRows = rows.filter(r => r.phase === p.id);
    const slot = phaseWidth / phaseRows.length;
    phaseRows.forEach((r, ri) => {
      stations.push({
        ...r,
        x: padL + pi * phaseWidth + slot * (ri + 0.5),
        y: modeYs[r.mode],
        labelAbove: ri % 2 === 1,
        lines: splitName(r.tool),
      });
    });
  });

  // Helpers
  const modeVars = (md) => ({
    '--mode-bg':   md.bg,
    '--mode-mark': md.color,
    '--mode-fg':   md.fg,
    '--mode-line': md.dot,
  });

  return (
    <article className="sm-root">
      {/* HERO */}
      <header className="sm-hero">
        <div className="sm-hero-meta">
          <span className="sm-hero-eyebrow">The UX writing process in the age of AI</span>
          <span className="v-chip">
            <span style={{ width:6, height:6, borderRadius:'50%', background:'var(--ut-blue-500)' }} />
            Sixteen tools, three modes
          </span>
        </div>
        <h1 className="sm-hero-title">
          The <em>UX writing process</em><br />
          in the age of AI.
        </h1>
        <p className="sm-hero-dek">
          Sixteen tools across four phases of the work. Each one carries a mode:
          AI runs it, AI helps and we decide, or AI stays out. Below, the whole map at a glance,
          then phase by phase.
        </p>

        <div className="sm-hero-modes">
          {Object.values(modes).map(md => {
            const c = rows.filter(r => r.mode === md.id).length;
            return (
              <div key={md.id} className="sm-mode-card" style={modeVars(md)}>
                <div>
                  <div className="label">
                    <span className="swatch" aria-hidden="true" />
                    {md.label}
                  </div>
                  <div className="short">{md.short}</div>
                  <div className="blurb">{md.blurb}</div>
                </div>
                <div className="num">{String(c).padStart(2,'0')}</div>
              </div>
            );
          })}
        </div>
      </header>

      {/* THE MAP */}
      <div className="sm-map-wrap">
        <div className="sm-map-frame">
          <svg className="sm-map-svg-container" viewBox={`0 0 ${W} ${H}`} width="100%" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Subway-map view of the UX writing process showing where AI runs the task, assists, or sits out across the four phases.">

            {/* Phase columns · soft background */}
            {phases.map((p, pi) => (
              <rect
                key={`bg-${p.id}`}
                x={padL + pi * phaseWidth}
                y={phaseY - 24}
                width={phaseWidth}
                height={H - phaseY + 8}
                fill={pi % 2 === 0 ? 'transparent' : 'var(--ut-neutral-25)'}
                opacity="0.6"
              />
            ))}

            {/* Phase column dividers */}
            {phases.map((p, pi) => (
              <line
                key={`div-${p.id}`}
                x1={padL + pi * phaseWidth}
                y1={phaseY}
                x2={padL + pi * phaseWidth}
                y2={H - 20}
                stroke="var(--ut-neutral-50)"
                strokeWidth="1"
                strokeDasharray="2 4"
              />
            ))}
            <line
              x1={W - padR}
              y1={phaseY}
              x2={W - padR}
              y2={H - 20}
              stroke="var(--ut-neutral-50)"
              strokeWidth="1"
              strokeDasharray="2 4"
            />

            {/* Phase headers */}
            {phases.map((p, pi) => {
              const cx = padL + pi * phaseWidth + phaseWidth / 2;
              return (
                <g key={`head-${p.id}`}>
                  <text x={cx} y={phaseY - 38} textAnchor="middle" className="sm-svg-phase-label">
                    Phase {String(pi+1).padStart(2,'0')}
                  </text>
                  <text x={cx} y={phaseY - 18} textAnchor="middle" className="sm-svg-phase-num" style={{ fontSize: 18, letterSpacing: '-0.01em' }}>
                    {p.label}
                  </text>
                </g>
              );
            })}

            {/* Mode lines (3 horizontal lanes) */}
            {Object.values(modes).map(md => {
              const y = modeYs[md.id];
              return (
                <g key={`line-${md.id}`}>
                  {/* Line background segment under stations */}
                  <line
                    x1={padL - 18}
                    y1={y}
                    x2={W - padR + 18}
                    y2={y}
                    stroke={md.bg}
                    strokeWidth="14"
                    strokeLinecap="round"
                  />
                  {/* Inner line */}
                  <line
                    x1={padL - 18}
                    y1={y}
                    x2={W - padR + 18}
                    y2={y}
                    stroke={md.color}
                    strokeWidth="4"
                    strokeLinecap="round"
                  />
                  {/* Mode label (left of line) */}
                  <g transform={`translate(${padL - 28}, ${y})`}>
                    <text x={0} y={-6} textAnchor="end" className="sm-svg-mode-name" fill={md.fg}>
                      {md.label}
                    </text>
                    <text x={0} y={10} textAnchor="end" className="sm-svg-mode-short" fill={md.fg} opacity="0.7">
                      {md.short.toUpperCase()}
                    </text>
                  </g>
                  {/* Line cap circle (left and right) */}
                  <circle cx={padL - 18} cy={y} r="6" fill={md.color} />
                  <circle cx={W - padR + 18} cy={y} r="6" fill={md.color} />
                </g>
              );
            })}

            {/* Stations */}
            {stations.map(s => {
              const md = modes[s.mode];
              const lineHeight = 13;
              // Labels go above (negative y from station) or below
              const baseOffset = 28;
              const yStart = s.labelAbove
                ? s.y - baseOffset - (s.lines.length - 1) * lineHeight
                : s.y + baseOffset;
              return (
                <g key={s.id}>
                  {/* Tick line from station to label */}
                  <line
                    x1={s.x}
                    y1={s.y}
                    x2={s.x}
                    y2={s.labelAbove ? s.y - 16 : s.y + 16}
                    stroke={md.color}
                    strokeWidth="1.5"
                    opacity="0.55"
                  />
                  {/* Station outer white ring */}
                  <circle cx={s.x} cy={s.y} r="13" fill="var(--surface-base)" />
                  {/* Station inner colored dot */}
                  <circle cx={s.x} cy={s.y} r="10" fill={md.color} />
                  {/* Symbol on the dot */}
                  <text x={s.x} y={s.y + 3} textAnchor="middle" className="sm-svg-tool-sym">
                    {s.symbol.toUpperCase()}
                  </text>
                  {/* Tool name, possibly multi-line */}
                  {s.lines.map((ln, li) => (
                    <text
                      key={li}
                      x={s.x}
                      y={yStart + li * lineHeight}
                      textAnchor="middle"
                      className="sm-svg-tool-name"
                    >
                      {ln}
                    </text>
                  ))}
                </g>
              );
            })}
          </svg>
        </div>
        <p className="sm-map-caption">
          <strong>How to read the map.</strong> Each lane is an AI mode; each station is a tool;
          x-position shows which phase of the work it belongs to. The denser the lane, the more often
          that mode shows up in our process.
        </p>
      </div>

      {/* PHASE SECTIONS */}
      {phases.map((p, pi) => {
        const phaseRows = rows.filter(r => r.phase === p.id);
        return (
          <section className="sm-phase" key={p.id}>
            <div className="sm-phase-head">
              <div>
                <div className="sm-phase-num">Phase {String(pi+1).padStart(2,'0')}</div>
                <h2 className="sm-phase-name">{p.label}.</h2>
              </div>
              <p className="sm-phase-blurb">{p.blurb}</p>
            </div>
            <div className="sm-tools">
              {phaseRows.map(r => <ToolCard key={r.id} r={r} m={modes[r.mode]} summary={summaries[r.id]} modeVars={modeVars} />)}
            </div>
          </section>
        );
      })}

      <footer className="sm-foot">
        <div className="sm-foot-meta">
          <strong>UXW × AI process map</strong> · Living document, last updated this quarter.
        </div>
        <div className="sm-foot-formats">
          <span className="sm-foot-formats-label">Other formats</span>
          <a href="index.html">Overview</a>
          <a href="Process explorer.html">Explorer</a>
          <a href="#" className="is-current" aria-current="page">Subway map</a>
          <a href="Process deck.html">Slide deck</a>
        </div>
      </footer>
    </article>
  );
}

function ToolCard({ r, m, summary, modeVars }) {
  const [showFull, setShowFull] = useState(false);
  return (
    <div className="sm-tool" style={modeVars(m)}>
      <div className="sm-tool-head">
        <div className="sm-tool-sym">{r.symbol}</div>
        <div>
          <h3 className="sm-tool-title">{r.tool}</h3>
          <div className="sm-tool-mode">
            <span className="dot" />
            {m.label}
          </div>
        </div>
      </div>
      <div className="sm-tool-body">
        <p className="sm-tool-def">{r.definition}</p>
        <div className="sm-tool-banner">
          <strong>{m.label}.</strong> {r.modeNote}
        </div>
        <div className="sm-tool-metaline">
          <div>
            <div className="sm-tool-meta-label">Output</div>
            <div className="sm-tool-meta-value">{r.output || '—'}</div>
          </div>
          <div>
            <div className="sm-tool-meta-label">For</div>
            <div className="sm-tool-meta-value">{r.application || '—'}</div>
          </div>
        </div>
        {r.whenToUse && (
          <div className="sm-tool-when">
            <strong>Reach for it.</strong> {r.whenToUse}
          </div>
        )}
      </div>

      <div className="sm-tool-prompt">
        {summary === null ? (
          <>
            <div className="sm-tool-prompt-head">
              <span className="sm-tool-prompt-kind is-none">Human only</span>
              <span className="sm-tool-prompt-name">No AI here</span>
            </div>
            <p className="sm-tool-prompt-body">{r.modeNote}</p>
          </>
        ) : summary?.placeholder ? (
          <>
            <div className="sm-tool-prompt-head">
              <span className="sm-tool-prompt-kind is-tbd">Skill in progress</span>
              <span className="sm-tool-prompt-name">Spec being drafted</span>
            </div>
            <p className="sm-tool-prompt-body">A skill is planned for this step. The spec hasn't been written up yet.</p>
          </>
        ) : (
          <>
            <div className="sm-tool-prompt-head">
              <span className="sm-tool-prompt-kind">{summary.kind}</span>
              <span className="sm-tool-prompt-name">What the AI does</span>
            </div>
            <p className="sm-tool-prompt-body">{summary.summary}</p>
            <button className="sm-tool-prompt-toggle" onClick={() => setShowFull(v => !v)} aria-expanded={showFull}>
              {showFull ? 'Hide full prompt' : 'View full prompt'}
            </button>
            {showFull && <pre className="sm-tool-prompt-full">{r.prompt}</pre>}
          </>
        )}
      </div>
    </div>
  );
}

window.SubwayMap = SubwayMap;
