// panels.jsx — Phase drawer, Method detail (modal), Method library page, and Legend.

const { useState: useState_p, useMemo: useMemo_p } = React;

// ---------- Legend ----------------------------------------------------------

function Legend({ selectedPhase, onSelectPhase, hoveredRing, onHoverRing }) {
  const phases = window.PHASES;
  const layers = window.CONTEXT_LAYERS;
  return (
    <aside className="legend">
      <div className="legend-section">
        <div className="legend-title">
          Phases <span className="legend-hint">Click for details & methods</span>
          </div>
        <ul>
          {phases.map(p => (
            <li key={p.id}
                className={"legend-row" + (selectedPhase === p.id ? " is-active" : "")}
                onClick={() => onSelectPhase(p.id)}>
              <span className="legend-dot" style={{ background: p.color }} />
              <span>{p.label}</span>
            </li>
          ))}
        </ul>
      </div>
      <div className="legend-section">
        <div className="legend-title">
          Context <span className="legend-hint">hover for more info</span>
        </div>
        <ul className="context-list">
          {layers.map(l => (
            <li key={l.id}
                className={"context-row" + (hoveredRing === l.id ? " is-hovered" : "")}
                onMouseEnter={() => onHoverRing && onHoverRing(l.id)}
                onMouseLeave={() => onHoverRing && onHoverRing(null)}>
              {l.id === "policy_lab"
                ? <span className="dash-swatch" />
                : <span className={"ring-swatch " + (l.id === "society" ? "outer" : l.id === "involved" ? "mid" : "inner")} />}
              <span>{l.label}</span>
            </li>
          ))}
        </ul>
      </div>
    </aside>
  );
}

// ---------- Context ring tooltip card --------------------------------------

function ContextTooltip({ layerId }) {
  if (!layerId) return null;
  const layer = window.CONTEXT_LAYERS.find(l => l.id === layerId);
  if (!layer) return null;
  return (
    <div className="context-tooltip" role="tooltip">
      <div className="ct-eyebrow">Context layer</div>
      <div className="ct-title">{layer.label}</div>
      <p className="ct-short">{layer.short}</p>
      {layer.members?.length > 0 && <>
        <div className="ct-section">Actors in this layer</div>
        <ul className="ct-members">
          {layer.members.map((m, i) => <li key={i}>{m}</li>)}
        </ul>
      </>}
    </div>
  );
}

// ---------- Phase drawer (right side, slides in) ----------------------------

function PhaseDrawer({ phaseId, onClose, onOpenMethod, position = "right" }) {
  const phase = phaseId ? window.phaseById(phaseId) : null;
  if (!phase) return null;
  const methods = phase.methods.map(window.methodById);
  return (
    <div className={"phase-drawer drawer-" + position} role="dialog" aria-label={phase.label}>
      <header className="drawer-head" style={{ borderTopColor: phase.color }}>
        <div className="drawer-eyebrow">
          <span className="phase-pip" style={{ background: phase.color }} />
          <span>Phase</span>
        </div>
        <h2 className="drawer-title">{phase.label}</h2>
        <p className="drawer-short">{phase.short}</p>
        <button className="drawer-close" onClick={onClose} aria-label="Close">×</button>
      </header>

      <div className="drawer-body">
        <p className="drawer-desc">{phase.description}</p>

        <div className="drawer-section-head">Objectives</div>
        <ul className="drawer-objectives">
          {phase.objectives.map((o, i) => <li key={i}>{o}</li>)}
        </ul>

        <div className="drawer-section-head">
          Recommended methods <span className="count">{methods.length}</span>
        </div>
        <ul className="method-list">
          {methods.map(m => (
            <li key={m.id} className={"method-item" + (m.draft ? " is-draft" : "")} onClick={() => onOpenMethod(m.id)}>
              <div className="method-item-main">
                <div className="method-item-name">{m.name}</div>
                <div className="method-item-blurb">{m.blurb}</div>
              </div>
              <div className="method-item-meta">
                {m.draft && <span className="draft-badge">Draft</span>}
                <span className={"chip chip-effort effort-" + m.effort}>{window.EFFORT_LABEL[m.effort]}</span>
                <span className="chip chip-skill">{window.SKILL_LABEL[m.skill]}</span>
              </div>
              <span className="method-chevron">›</span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

// ---------- Method detail ---------------------------------------------------

function MethodDetailBody({ method, onClose }) {
  if (!method) return null;
  const phaseChips = method.phases.map(window.phaseById);
  const actors = method.actors.map(window.actorById);
  return (
    <div className="method-detail variant-modal">
      <header className="md-head">
        <div className="md-eyebrow">Method</div>
        <h3 className="md-title">{method.name}</h3>
        <button className="md-close" onClick={onClose} aria-label="Close">×</button>
      </header>

      <div className="md-body">
        <p className="md-blurb">{method.blurb}</p>

        <div className="md-stats">
          <div className="md-stat">
            <div className="md-stat-label">Effort</div>
            <div className={"md-stat-val effort-" + method.effort}>{window.EFFORT_LABEL[method.effort]}</div>
          </div>
          <div className="md-stat">
            <div className="md-stat-label">Skill level</div>
            <div className="md-stat-val">{window.SKILL_LABEL[method.skill]}</div>
          </div>
          <div className="md-stat">
            <div className="md-stat-label">Duration</div>
            <div className="md-stat-val">{method.duration}</div>
          </div>
          <div className="md-stat">
            <div className="md-stat-label">Group size</div>
            <div className="md-stat-val">{method.group}</div>
          </div>
        </div>

        <div className="md-section-head">When to use it</div>
        <p className="md-when">{method.when}</p>

        <div className="md-section-head">Used in phases</div>
        <div className="chip-row">
          {phaseChips.map(p => (
            <span key={p.id} className="phase-chip" style={{ borderColor: p.color, color: p.color }}>
              <span className="phase-pip" style={{ background: p.color }} />
              {p.label}
            </span>
          ))}
        </div>

        <div className="md-section-head">Relevant actors</div>
        <div className="chip-row">
          {actors.map(a => <span key={a.id} className="actor-chip">{a.label}</span>)}
        </div>

        {method.refs?.length > 0 && (() => {
          const refs = method.refs.map(window.refByKey).filter(Boolean);
          if (!refs.length) return null;
          return (
            <>
              <div className="md-section-head">Further reading</div>
              <ul className="md-refs">
                {refs.map((r, i) => {
                  const { text, href } = window.formatReference(r);
                  return (
                    <li key={i}>
                      {href
                        ? <a href={href} target="_blank" rel="noopener noreferrer">{text}</a>
                        : text}
                    </li>
                  );
                })}
              </ul>
            </>
          );
        })()}
      </div>
    </div>
  );
}

function MethodDetail({ method, onClose }) {
  if (!method) return null;
  return (
    <div className="md-overlay" onClick={onClose}>
      <div className="md-modal" onClick={(e) => e.stopPropagation()}>
        <MethodDetailBody method={method} onClose={onClose} />
      </div>
    </div>
  );
}

// ---------- Method grid (used in library) -----------------------------------

function MethodGrid({ methods, onOpen, expandedId, highlightPhase }) {
  return (
    <div className="method-grid">
      {methods.map(m => {
        const dim = highlightPhase && !m.phases.includes(highlightPhase);
        const phaseChips = m.phases.map(window.phaseById);
        return (
          <article
            key={m.id}
            className={"method-card" + (expandedId === m.id ? " is-expanded" : "") + (dim ? " is-dim" : "") + (m.draft ? " is-draft" : "")}
            onClick={() => onOpen(m.id)}>
            <div className="card-top">
              <div className="card-name">{m.name}</div>
              <span className="card-chevron">›</span>
            </div>
            <p className="card-blurb">{m.blurb}</p>
            <div className="card-foot">
              {m.draft && <span className="draft-badge">Draft</span>}
              <span className={"chip chip-effort effort-" + m.effort}>{window.EFFORT_LABEL[m.effort]}</span>
              <span className="chip chip-skill">{window.SKILL_LABEL[m.skill]}</span>
              <div className="card-phase-dots">
                {phaseChips.map(p => (
                  <span key={p.id} className="phase-pip lg" title={p.label} style={{ background: p.color }} />
                ))}
              </div>
            </div>
          </article>
        );
      })}
    </div>
  );
}

// ---------- Method library / Search page -----------------------------------

function MethodLibrary({ onOpenMethod, expandedId }) {
  const phases = window.PHASES;
  const actors = window.ACTORS;
  const all = window.METHODS;

  const [phaseFilter,  setPhase ] = useState_p(null);
  const [actorFilter,  setActor ] = useState_p(null);
  const [effortFilter, setEffort] = useState_p(null);
  const [skillFilter,  setSkill ] = useState_p(null);
  const [q, setQ] = useState_p("");

  const filtered = useMemo_p(() => {
    return all.filter(m => {
      if (phaseFilter  && !m.phases.includes(phaseFilter)) return false;
      if (actorFilter  && !m.actors.includes(actorFilter)) return false;
      if (effortFilter && m.effort !== effortFilter)       return false;
      if (skillFilter  && m.skill  !== skillFilter)        return false;
      if (q.trim()) {
        const needle = q.trim().toLowerCase();
        if (!m.name.toLowerCase().includes(needle) &&
            !m.blurb.toLowerCase().includes(needle)) return false;
      }
      return true;
    });
  }, [phaseFilter, actorFilter, effortFilter, skillFilter, q]);

  const activeCount = [phaseFilter, actorFilter, effortFilter, skillFilter].filter(Boolean).length + (q ? 1 : 0);

  return (
    <div className="library">
      <aside className="library-filters">
        <div className="filters-head">
          <h2>Filter methods</h2>
          {activeCount > 0 && (
            <button className="clear-all" onClick={() => {
              setPhase(null); setActor(null); setEffort(null); setSkill(null); setQ("");
            }}>Clear all ({activeCount})</button>
          )}
        </div>

        <div className="filter-group">
          <label className="filter-label" htmlFor="lib-q">Search</label>
          <input id="lib-q" type="text" className="filter-input"
                 placeholder="Search by name or description…"
                 value={q} onChange={(e) => setQ(e.target.value)} />
        </div>

        <FilterBlock label="Phase">
          {phases.map(p => (
            <FilterChip key={p.id}
              active={phaseFilter === p.id}
              onClick={() => setPhase(phaseFilter === p.id ? null : p.id)}>
              <span className="phase-pip" style={{ background: p.color }} />
              {p.label}
            </FilterChip>
          ))}
        </FilterBlock>

        <FilterBlock label="Actor">
          {actors.map(a => (
            <FilterChip key={a.id}
              active={actorFilter === a.id}
              onClick={() => setActor(actorFilter === a.id ? null : a.id)}>
              {a.label}
            </FilterChip>
          ))}
        </FilterBlock>

        <FilterBlock label="Effort / time">
          {window.EFFORT_ORDER.map(e => (
            <FilterChip key={e}
              active={effortFilter === e}
              onClick={() => setEffort(effortFilter === e ? null : e)}>
              {window.EFFORT_LABEL[e]}
            </FilterChip>
          ))}
        </FilterBlock>

        <FilterBlock label="Skill level required">
          {window.SKILL_ORDER.map(s => (
            <FilterChip key={s}
              active={skillFilter === s}
              onClick={() => setSkill(skillFilter === s ? null : s)}>
              {window.SKILL_LABEL[s]}
            </FilterChip>
          ))}
        </FilterBlock>
      </aside>

      <section className="library-results">
        <div className="results-head">
          <h1>Method library</h1>
          <div className="results-count">{filtered.length} {filtered.length === 1 ? "method" : "methods"}</div>
        </div>
        {filtered.length === 0 ? (
          <div className="empty-state">
            <p>No methods match the current filters.</p>
          </div>
        ) : (
          <MethodGrid
            methods={filtered}
            onOpen={onOpenMethod}
            expandedId={expandedId}
            highlightPhase={null} />
        )}
      </section>
    </div>
  );
}

function FilterBlock({ label, children }) {
  return (
    <div className="filter-group">
      <div className="filter-label">{label}</div>
      <div className="filter-chips">{children}</div>
    </div>
  );
}

function FilterChip({ active, onClick, children }) {
  return (
    <button className={"filter-chip" + (active ? " is-active" : "")} onClick={onClick}>
      {children}
    </button>
  );
}

Object.assign(window, {
  Legend, ContextTooltip, PhaseDrawer,
  MethodDetailBody, MethodDetail, MethodGrid, MethodLibrary,
});
