// app.jsx — App shell: tab routing, layout, async content bootstrap.

const { useState: useState_a, useEffect: useEffect_a } = React;

function App() {
  const [tab, setTab] = useState_a("concept");
  const [phaseId, setPhaseId] = useState_a(null);
  const [methodId, setMethodId] = useState_a(null);

  useEffect_a(() => {
    function onKey(e) {
      if (e.key === "Escape") {
        if (methodId) setMethodId(null);
        else if (phaseId && tab === "concept") setPhaseId(null);
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [methodId, phaseId, tab]);

  const method = methodId ? window.methodById(methodId) : null;

  function openMethod(id) {
    setMethodId((prev) => prev === id ? null : id);
  }

  return (
    <div className="app">
      <TopBar tab={tab} setTab={setTab} />

      {tab === "concept" ?
        <ConceptPage
          phaseId={phaseId}
          setPhaseId={setPhaseId}
          openMethod={openMethod} /> :
        <window.MethodLibrary
          onOpenMethod={openMethod}
          expandedId={methodId} />
      }

      {method &&
        <window.MethodDetail method={method} onClose={() => setMethodId(null)} />
      }

      <PageFooter />
    </div>
  );
}

function TopBar({ tab, setTab }) {
  const site = window.SITE;
  return (
    <header className="top-bar">
      <div className="brand">
        <div className="brand-mark">
          <img className="brand-logo" src="logo.png" alt="" />
        </div>
        <div className="brand-text">
          <div className="brand-eyebrow">{site.eyebrow}</div>
          <div className="brand-title">{site.title}</div>
        </div>
      </div>

      <nav className="tabs">
        <button className={"tab" + (tab === "concept" ? " is-active" : "")} onClick={() => setTab("concept")}>
          Concept diagram
        </button>
        <button className={"tab" + (tab === "library" ? " is-active" : "")} onClick={() => setTab("library")}>
          Method library
        </button>
      </nav>

      <div className="top-right">
        <span className="top-meta">{site.tagline}</span>
        {site.authors && (
          <div className="top-authorship">
            {site.authors.map((a, i) => {
              const entry = typeof a === "string" ? { name: a } : a;
              return (
                <React.Fragment key={i}>
                  {i > 0 && ", "}
                  {entry.url
                    ? <a href={entry.url} target="_blank" rel="noopener noreferrer">{entry.name}</a>
                    : entry.name}
                </React.Fragment>
              );
            })}
          </div>
        )}
      </div>
    </header>
  );
}

function ConceptPage({ phaseId, setPhaseId, openMethod }) {
  const [hoveredRing, setHoveredRing] = useState_a(null);
  const phase = phaseId ? window.phaseById(phaseId) : null;

  return (
    <main className={"concept-page layout-drawer" + (phaseId ? " drawer-open" : "")}>
      <div className="concept-stage">
        <window.Legend
          selectedPhase={phaseId}
          onSelectPhase={setPhaseId}
          hoveredRing={hoveredRing}
          onHoverRing={setHoveredRing} />
        <div className="diagram-wrap">
          <div className="diagram-headline">
            <h1>The context of Policy Labs</h1>
            <p>Click a phase to see its objectives and methods. Hover a context ring to see who's involved.</p>
          </div>
          <div className="diagram-stage">
            <window.ConceptDiagram
              selectedPhase={phaseId}
              onSelectPhase={setPhaseId}
              hoveredRing={hoveredRing}
              onHoverRing={setHoveredRing}
              dimMethods={!!phaseId} />
            <window.ContextTooltip layerId={hoveredRing} />
          </div>
        </div>
      </div>

      {phase &&
        <window.PhaseDrawer
          phaseId={phaseId}
          onClose={() => setPhaseId(null)}
          onOpenMethod={openMethod}
          position="right" />
      }
    </main>
  );
}

function PageFooter() {
  return (
    <div className="page-footer">
      <span className="page-footer-label">Created with support from:</span>
      <a href="https://iat-dml.github.io/" target="_blank" rel="noopener noreferrer" className="page-footer-link">
        <img className="page-footer-logo" src="dml-strata-lockup-deep.svg" alt="DML — Data and Modelling Infrastructure for Living Labs" />
      </a>
    </div>
  );
}

function ContentError({ message }) {
  return (
    <div className="content-error">
      <div className="content-error-box">
        <div className="ce-icon">⚠</div>
        <h2>Content failed to load</h2>
        <p className="ce-message">{message}</p>
        <p className="ce-hint">Check the <code>app/content/</code> YAML files for errors and reload the page.</p>
      </div>
    </div>
  );
}

async function bootstrap() {
  const root = ReactDOM.createRoot(document.getElementById("root"));
  try {
    await window.loadContent();
    root.render(<App />);
  } catch (e) {
    root.render(<ContentError message={e.message} />);
  }
}

bootstrap();
