// App — top-level orchestration: scenario state, per-scenario answers + iteration
// history, and the submit/refine flow. All state is per-browser (in-memory), so
// separate rooms on the same URL never share or overwrite each other's work.
const { useState, useMemo } = React;

const BLANK = { positioning: "", channels: "", challenges: "" };

function App() {
  const scenarios = window.SCENARIOS;
  const [activeId, setActiveId] = useState(scenarios[0].id);

  // Per-scenario answer state so switching doesn't wipe work.
  const [answersByScenario, setAnswersByScenario] = useState(() =>
    Object.fromEntries(scenarios.map((s) => [s.id, { ...BLANK }]))
  );

  // Per-scenario history of submitted iterations: [{ inputs, response }, ...].
  // Kept so a group can refine and read the new persona take beside the old one.
  const [historyByScenario, setHistoryByScenario] = useState(() =>
    Object.fromEntries(scenarios.map((s) => [s.id, []]))
  );

  const [stage, setStage] = useState("form"); // 'form' | 'loading' | 'response'
  const [submitError, setSubmitError] = useState(null);

  const active = useMemo(
    () => scenarios.find((s) => s.id === activeId),
    [activeId, scenarios]
  );
  const answers = answersByScenario[activeId];
  const history = historyByScenario[activeId];
  const setAnswers = (next) =>
    setAnswersByScenario((prev) => ({ ...prev, [activeId]: next }));

  function handleScenarioChange(id) {
    if (stage === "loading") return;
    setActiveId(id);
    setStage("form");
    setSubmitError(null);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  async function handleSubmit() {
    setStage("loading");
    setSubmitError(null);
    // Scroll the (in-progress) latest analysis into view as it loads.
    setTimeout(() => {
      const el = document.getElementById("response-anchor");
      if (el) window.scrollTo({ top: el.offsetTop - 40, behavior: "smooth" });
    }, 60);
    try {
      const submittedInputs = { ...answers };
      const res = await window.fetchPersonaResponse({
        scenarioId: activeId,
        ...submittedInputs
      });
      setHistoryByScenario((prev) => ({
        ...prev,
        [activeId]: [...prev[activeId], { inputs: submittedInputs, response: res }]
      }));
      setStage("response");
    } catch (err) {
      console.error(err);
      setSubmitError((err && err.message) || "Something went wrong reaching the persona. Try again.");
      setStage("form");
    }
  }

  function handleRefine() {
    // Back to the form to improve the inputs; prior analyses are kept so the
    // next submission can sit side by side with them.
    setStage("form");
    setTimeout(() => {
      const el = document.querySelector(".form");
      if (el) window.scrollTo({ top: el.offsetTop - 40, behavior: "smooth" });
    }, 40);
  }

  // The (at most two) columns to render: previous vs latest. While loading, the
  // newest completed analysis sits beside an in-progress skeleton column.
  const columns = useMemo(() => {
    if (stage === "loading") {
      const prior = history.slice(-1); // 0 or 1 completed
      const cols = prior.map((e, i) => ({
        iter: history.length - prior.length + 1 + i,
        inputs: e.inputs,
        response: e.response,
        loading: false,
        latest: false
      }));
      cols.push({ iter: history.length + 1, loading: true, latest: true });
      return cols;
    }
    const shown = history.slice(-2); // 1 or 2 completed
    const base = history.length - shown.length + 1;
    return shown.map((e, i) => ({
      iter: base + i,
      inputs: e.inputs,
      response: e.response,
      loading: false,
      latest: base + i === history.length
    }));
  }, [stage, history]);

  const showResponse = stage === "loading" || history.length > 0;

  return (
    <div className="page">
      <header className="site-header">
        <a className="site-header__logo" href="https://www.londonclimateactionweek.org" target="_blank" rel="noopener noreferrer" aria-label="London Climate Action Week">
          <img src="images/lcaw-logo-white.webp" alt="London Climate Action Week" />
        </a>
        <div className="site-header__cohost">
          <img className="site-header__cohost-logo site-header__cohost-logo--weber" src="images/weber-shandwick-white.webp" alt="Weber Shandwick" />
          <span className="dot" aria-hidden="true">×</span>
          <img className="site-header__cohost-logo site-header__cohost-logo--aimhi" src="images/aimhi-earth.svg" alt="AimHi Earth" />
        </div>
      </header>

      <main className="main">
        <section className="hero">
          <h1 className="hero__title">
            Test your sustainability comms against an AI persona.
          </h1>
          <p className="hero__sub">
            Pick a scenario. Draft your approach with your group. Submit it, and see how
            the target audience reacts — in their own words.
          </p>
        </section>

        <ScenarioToggle
          scenarios={scenarios}
          activeId={activeId}
          onChange={handleScenarioChange}
          disabled={stage === "loading"}
        />

        <ScenarioBrief scenario={active} />

        <SubmissionForm
          answers={answers}
          setAnswers={setAnswers}
          onSubmit={handleSubmit}
          submitting={stage === "loading"}
          disabled={false}
        />

        {submitError && (
          <div className="form__error" role="alert">
            <span className="form__error-label">Couldn't get a response</span>
            {submitError}
          </div>
        )}

        <div id="response-anchor" />
        {showResponse && (
          <ResponsePanel
            personaName={active.persona.name}
            loading={stage === "loading"}
            columns={columns}
            canRefine={stage === "response"}
            onRefine={handleRefine}
          />
        )}
      </main>

      <footer className="site-footer">
        <div>LCAW 2026 · Workshop portal</div>
        <div className="site-footer__right">
          Weber Shandwick &nbsp;×&nbsp; AimHi Earth
        </div>
      </footer>
    </div>
  );
}

window.App = App;
