// Explorer · primary deliverable
// Layout: top bar, mode hero strip, [phase rail | tool list | detail]

const { useState, useEffect, useMemo } = React;

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

  const [query, setQuery] = useState('');
  const [phaseFilter, setPhaseFilter] = useState(new Set(phases.map(p => p.id)));
  const [modeFilter, setModeFilter] = useState(new Set(Object.keys(modes)));
  const [selectedId, setSelectedId] = useState('messaging-wireframes');
  const [showFullPrompt, setShowFullPrompt] = useState(false);

  const toggle = (set, setter) => (id) => {
    const next = new Set(set);
    if (next.has(id)) next.delete(id); else next.add(id);
    if (next.size === 0) return; // never let user select zero. Keep at least one
    setter(next);
  };

  const counts = useMemo(() => ({
    automate: rows.filter(r => r.mode === 'automate').length,
    augment:  rows.filter(r => r.mode === 'augment').length,
    alone:    rows.filter(r => r.mode === 'alone').length,
  }), []);

  const filtered = rows.filter(r => {
    if (!phaseFilter.has(r.phase)) return false;
    if (!modeFilter.has(r.mode)) return false;
    if (!query) return true;
    const q = query.toLowerCase();
    return r.tool.toLowerCase().includes(q)
        || r.definition.toLowerCase().includes(q)
        || (r.application || '').toLowerCase().includes(q)
        || (r.whenToUse || '').toLowerCase().includes(q)
        || r.modeNote.toLowerCase().includes(q);
  });

  // Keep selection inside the filtered list
  useEffect(() => {
    if (!filtered.find(r => r.id === selectedId) && filtered[0]) {
      setSelectedId(filtered[0].id);
    }
  }, [filtered.length, filtered[0]?.id]);

  // Reset prompt view when switching tools
  useEffect(() => { setShowFullPrompt(false); }, [selectedId]);

  const selected = rows.find(r => r.id === selectedId) || filtered[0] || rows[0];
  const m = modes[selected.mode];
  const summary = summaries[selected.id];

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

  return (
    <div className="ex-shell">
      {/* TOP BAR */}
      <header className="ex-topbar">
        <div className="ex-brand">
          <div className="ex-logo" aria-hidden="true">U×</div>
          <div>
          <div className="ex-brand-title">The UX writing process in the age of AI</div>
            <div className="ex-brand-sub">An explorer of tools, modes, and where AI fits.</div>
          </div>
        </div>
        <div className="ex-topbar-spacer" />
        <label className="ex-search">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>
          </svg>
          <input
            type="text"
            placeholder="Search tools, definitions, when to use…"
            value={query}
            onChange={e => setQuery(e.target.value)}
            aria-label="Search tools"
          />
          {query && <button className="ex-search-clear" onClick={() => setQuery('')}>Clear</button>}
        </label>
        <div className="ex-count">
          <strong>{filtered.length}</strong> of {rows.length}
        </div>
      </header>

      {/* MODE HERO */}
      <div className="ex-modebar">
        <div className="ex-modebar-lede">
          <div className="ex-modebar-eyebrow">Three ways AI shows up</div>
          <h2 className="ex-modebar-headline">Filter the process by how much AI does the work.</h2>
        </div>
        {Object.values(modes).map(md => {
          const active = modeFilter.has(md.id);
          return (
            <button
              key={md.id}
              className={`ex-mode-chip ${active ? 'is-on' : 'is-off'}`}
              onClick={() => toggle(modeFilter, setModeFilter)(md.id)}
              style={modeVars(md)}
              aria-pressed={active}
            >
              <span className="ex-mode-count">{String(counts[md.id]).padStart(2,'0')}</span>
              <span className="ex-mode-meta">
                <span className="ex-mode-label">
                  <span className="ex-mode-dot" aria-hidden="true" />
                  {md.label}
                </span>
                <span className="ex-mode-short">{md.blurb}</span>
              </span>
              <span className="ex-mode-check" aria-hidden="true">
                {active && (
                  <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="3,8.5 6.5,12 13,4.5" />
                  </svg>
                )}
              </span>
            </button>
          );
        })}
      </div>

      <div className="ex-body">
        {/* SIDEBAR */}
        <aside className="ex-sidebar">
          <section className="ex-side-section">
            <div className="ex-side-title">Phases of the work</div>
            {phases.map((p, i) => {
              const active = phaseFilter.has(p.id);
              const c = rows.filter(r => r.phase === p.id).length;
              return (
                <label key={p.id} className={`ex-phase-row ${active ? 'is-on' : ''}`}>
                  <input
                    type="checkbox"
                    checked={active}
                    onChange={() => toggle(phaseFilter, setPhaseFilter)(p.id)}
                  />
                  <span style={{ display:'flex', flexDirection:'column', gap:2, minWidth: 0 }}>
                    <span className="ex-phase-num">PHASE {String(i+1).padStart(2,'0')}</span>
                    <span>{p.label}</span>
                  </span>
                  <span className="ex-phase-count">{c}</span>
                </label>
              );
            })}
          </section>

        </aside>

        {/* TOOL LIST */}
        <main className="ex-list">
          {phases.map((p, pi) => {
            const phaseRows = filtered.filter(r => r.phase === p.id);
            if (phaseRows.length === 0) return null;
            return (
              <section className="ex-list-group" key={p.id}>
                <div className="ex-list-grouphead">
                  <span className="ex-list-groupname">Phase {String(pi+1).padStart(2,'0')} · {p.label}</span>
                  <span className="ex-list-groupblurb">{p.blurb}</span>
                  <span className="ex-list-groupcount">{phaseRows.length} {phaseRows.length === 1 ? 'tool' : 'tools'}</span>
                </div>
                {phaseRows.map(r => {
                  const md = modes[r.mode];
                  const isSel = r.id === selected.id;
                  return (
                    <button
                      key={r.id}
                      className={`ex-card ${isSel ? 'is-selected' : ''}`}
                      onClick={() => setSelectedId(r.id)}
                      style={modeVars(md)}
                      aria-pressed={isSel}
                    >
                      <span className="ex-card-rail" />
                      <span className="ex-card-body">
                        <span className="ex-card-toprow">
                          <span className="ex-card-symbol">{r.symbol}</span>
                          <span className="ex-card-tool">{r.tool}</span>
                          <span className={`mode-pill is-${md.id}`}>
                            <span className="dot" />
                            {md.label}
                          </span>
                        </span>
                        <span className="ex-card-def">{r.definition}</span>
                        <span className="ex-card-meta">
                          <span><span className="ex-card-meta-label">Output</span> {r.output || '—'}</span>
                          <span className="ex-card-meta-sep">·</span>
                          <span><span className="ex-card-meta-label">For</span> {r.application || '—'}</span>
                        </span>
                      </span>
                      <span className="ex-card-chev" aria-hidden="true">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <polyline points="9 6 15 12 9 18" />
                        </svg>
                      </span>
                    </button>
                  );
                })}
              </section>
            );
          })}
          {filtered.length === 0 && (
            <div className="ex-empty">
              <div className="ex-empty-title">No tools match these filters</div>
              <div className="ex-empty-blurb">Try clearing the search or turning a mode back on.</div>
            </div>
          )}
        </main>

        {/* DETAIL */}
        <aside className="ex-detail" style={modeVars(m)}>
          <div className="ex-detail-crumbs">
            <span>Phase {String(phases.findIndex(p => p.id === selected.phase)+1).padStart(2,'0')}</span>
            <span className="ex-detail-crumbs-sep">›</span>
            <span>{phases.find(p => p.id === selected.phase).label}</span>
            <span className="ex-detail-crumbs-sep">›</span>
            <span className="ex-detail-crumbs-current">{selected.tool}</span>
          </div>

          <div className="ex-detail-titleblock">
            <div className="ex-detail-sym" aria-hidden="true">{selected.symbol}</div>
            <div>
              <h2 className="ex-detail-title">{selected.tool}</h2>
              <span className={`mode-pill is-${m.id}`}>
                <span className="dot" />
                {m.label} <span style={{ opacity:0.7, marginLeft:6, fontWeight:400 }}>· {m.short}</span>
              </span>
              <p className="ex-detail-def" style={{ marginTop: 12 }}>{selected.definition}</p>
            </div>
          </div>

          <div className="ex-detail-banner">
            <div className="ex-detail-banner-label">
              <span className="dot" />
              How AI shows up here
            </div>
            <div className="ex-detail-banner-body">{selected.modeNote}</div>
          </div>

          <div className="ex-detail-meta">
            <div className="ex-meta-cell">
              <div className="ex-meta-label">Output</div>
              <div className="ex-meta-value">{selected.output || <span className="ex-muted">Not specified</span>}</div>
            </div>
            <div className="ex-meta-cell">
              <div className="ex-meta-label">Use for</div>
              <div className="ex-meta-value">{selected.application || <span className="ex-muted">Not specified</span>}</div>
            </div>
            <div className="ex-meta-cell ex-meta-cell-wide">
              <div className="ex-meta-label">Reach for it</div>
              <div className="ex-meta-value">{selected.whenToUse || <span className="ex-muted">When to use this tool isn't documented yet.</span>}</div>
            </div>
          </div>

          {summary === null ? (
            <div className="ex-detail-prompt">
              <div className="ex-detail-prompt-head">
                <span className="ex-detail-prompt-kind is-none">Human only</span>
                <span className="ex-detail-prompt-name">No AI instructions for this tool</span>
              </div>
              <div className="ex-detail-prompt-empty">
                {selected.modeNote}
              </div>
            </div>
          ) : summary?.placeholder ? (
            <div className="ex-detail-prompt">
              <div className="ex-detail-prompt-head">
                <span className="ex-detail-prompt-kind is-tbd">Skill in progress</span>
                <span className="ex-detail-prompt-name">Spec still being drafted</span>
              </div>
              <div className="ex-detail-prompt-empty">
                A skill is planned for this step. The spec hasn't been written up yet.
                <div className="ex-detail-prompt-tbd-note">Coming from the team. Placeholder until then.</div>
              </div>
            </div>
          ) : (
            <div className="ex-detail-prompt">
              <div className="ex-detail-prompt-head">
                <span className="ex-detail-prompt-kind">{summary.kind}</span>
                <span className="ex-detail-prompt-name">What the AI is asked to do</span>
              </div>
              <div className="ex-detail-prompt-body-section">
                <p className="ex-detail-prompt-summary">{summary.summary}</p>
                <button
                  className={`ex-detail-prompt-toggle ${showFullPrompt ? 'is-open' : ''}`}
                  onClick={() => setShowFullPrompt(v => !v)}
                  aria-expanded={showFullPrompt}
                >
                  <span className="caret" aria-hidden="true">
                    <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="9 6 15 12 9 18" />
                    </svg>
                  </span>
                  {showFullPrompt ? 'Hide full prompt' : 'View full prompt'}
                </button>
                {showFullPrompt && (
                  <pre className="ex-detail-prompt-full">{selected.prompt}</pre>
                )}
              </div>
            </div>
          )}
        </aside>
      </div>

      {/* Format switcher */}
      <footer className="ex-formats">
        <span className="ex-formats-label">Other formats</span>
        <a href="index.html">Overview</a>
        <a href="#" className="is-current" aria-current="page">Explorer</a>
        <a href="process-map.html">Subway map</a>
        <a href="process-deck.html">Slide deck</a>
      </footer>
    </div>
  );
}

window.Explorer = Explorer;
