/* =========================================================================
   ISD MEL Toolkit — main App
   ========================================================================= */

const STORAGE_KEY = "isd-mel-toolkit-v1";


function loadState() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch (e) { return null; }
}
function saveState(s) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch (e) {}
}

/* ---------- Section intro view (full-panel, replaces chain when on an intro node) ---------- */
function SectionIntroView({ step, si, onContinue, onBack, currentIdx }) {
  return (
    <main className="main-panel si-view">
      <div className="si-view__scroll">
        <div className="si-view__inner" style={{ "--si-accent": step.colorHex }}>
          <p className="si-view__eyebrow-label">Introduction</p>
          <h1 className="si-view__title" style={{ color: step.colorHex }}>
            Step {step.number}: {step.title}
          </h1>

          <p className="si-view__lead">{si.question ? `${si.question} ` : ""}{si.body}</p>

          {(si.detailA || si.detailB || si.bulletsTitle || si.callout) && (
            <div className="si-view__details">
              {si.detailA && <p>{si.detailA}</p>}
              {si.detailB && (
                <p>
                  {si.detailB.map((seg, i) =>
                    seg.href
                      ? <a key={i} href={seg.href} target="_blank" rel="noopener noreferrer">{seg.text}</a>
                      : seg.text
                  )}
                </p>
              )}
              {si.bulletsTitle && (
                <div className="si-view__bullets">
                  <p className="si-view__bullets-label">{si.bulletsTitle}</p>
                  <ul>
                    {si.bullets.map((b, i) => (
                      <li key={i}><strong>{b.term}:</strong> {b.def}</li>
                    ))}
                  </ul>
                </div>
              )}
              {si.callout && (
                <div className="callout callout--tip">
                  <span className="callout__icon"><Icon name="info" size={14} /></span>
                  <div className="callout__body">
                    {si.calloutTitle && <div className="callout__title"><strong>{si.calloutTitle}</strong></div>}
                    <div className="callout__text">{si.callout}</div>
                  </div>
                </div>
              )}
            </div>
          )}

          <div className="si-view__nav">
            <Btn variant="ghost" icon="arrow-l" onClick={onBack} disabled={currentIdx === 0}>Previous</Btn>
            <Btn variant="primary" iconRight="arrow-r" onClick={onContinue}>Begin Step {step.number}</Btn>
          </div>
        </div>
      </div>
    </main>
  );
}

/* ---------- Title screen ---------- */
function TitleScreen({ onStart, hasProgress, savedName }) {
  const [name, setName] = useState(savedName || "");
  const trimmed = (name || "").trim();
  const handleStart = () => onStart(trimmed || "Untitled MEL plan");

  return (
    <div className="title-screen">
      <div className="title-screen__left">
        <img className="title-screen__logo" src="assets/isd-logo.png" alt="Institute for Strategic Dialogue" />
        <div>
          <h1 className="title-screen__title">
            Evaluating projects to counter <span className="accent">online antisemitism.</span>
          </h1>
          <div className="title-screen__hook">
            <p className="title-screen__hook-lead">This interactive toolkit:</p>
            <ul className="title-screen__hook-list">
              <li>Walks you through ISD&rsquo;s four-step MEL framework</li>
              <li>Captures your responses for your own project</li>
              <li>Compiles a draft MEL report you can take into delivery</li>
            </ul>
          </div>

          <div className="title-screen__form">
            <label className="title-screen__field-label" htmlFor="ts-name">Name your project</label>
            <input
              id="ts-name"
              type="text"
              className="title-screen__field"
              value={name}
              onChange={e => setName(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") handleStart(); }}
              placeholder="e.g. Counter-antisemitism youth program"
              autoFocus
            />
            <div className="title-screen__cta-row">
              <Btn variant="primary" iconRight="arrow-r" onClick={handleStart}>
                {hasProgress && savedName ? "Resume toolkit" : "Next"}
              </Btn>
              <span className="title-screen__footnote">You can rename it at any time.</span>
            </div>
          </div>

          <a className="title-screen__source" href="assets/TTA Eval D1.2.pdf" target="_blank" rel="noopener noreferrer">
            <Icon name="doc" size={16} />
            <div className="title-screen__source-body">
              <span className="title-screen__source-label">Read the framework guide</span>
              <span className="title-screen__source-sub"><em>Evaluating Projects to Counter Online Antisemitism</em> — ISD, 2025</span>
            </div>
            <span className="title-screen__source-arrow">↗</span>
          </a>
        </div>
      </div>
      <div className="title-screen__right">
        <p className="title-screen__caption">
          A well-designed evaluation enables a practitioner to build an evidence base around effective approaches, identify problems in delivery, demonstrate accountability, and make a credible case for continued support.
        </p>
      </div>
    </div>
  );
}


/* ---------- Main toolkit view ---------- */
function ToolkitApp() {
  const steps = window.MEL_STEPS;

  // Flatten lessons (+ section intro stubs) with step ref for easy navigation
  const flat = useMemo(() => {
    const out = [];
    steps.forEach(s => {
      if (s.sectionIntro) {
        out.push({
          id: `si-${s.id}`, type: "section-intro",
          stepId: s.id, stepNumber: s.number, stepTitle: s.title, colorHex: s.colorHex,
          sectionIntro: s.sectionIntro,
          eyebrow: `Step ${s.number}`, title: "Introduction",
          prompts: [], allowsNotApplicable: false
        });
      }
      s.lessons.forEach(l => {
        out.push({ ...l, stepId: s.id, stepNumber: s.number, stepTitle: s.title, colorHex: s.colorHex });
      });
    });
    return out;
  }, [steps]);

  // ---------- State ----------
  const initial = loadState();
  const [screen, setScreen] = useState(initial?.screen || "title"); // title | toolkit | report
  const [currentIdx, setCurrentIdx] = useState(initial?.currentIdx ?? 0);
  const [answers, setAnswers] = useState(initial?.answers || {});
  const [projectName, setProjectName] = useState(initial?.projectName || "");
  const [naState, setNaState] = useState(initial?.naState || {});

  // Persist
  useEffect(() => {
    saveState({ screen, currentIdx, answers, projectName, naState });
  }, [screen, currentIdx, answers, projectName, naState]);

  // Project name dialog on first toolkit entry
  const askForName = useCallback(() => {
    if (projectName) return;
    const n = window.prompt(
      "Give your MEL project a name (you can change this later):",
      "Counter-antisemitism project"
    );
    if (n) setProjectName(n.trim());
  }, [projectName]);

  // ---------- Refs for scrolling the chain ----------
  const canvasRef = useRef(null);
  const activeCardRef = useRef(null);

  // Auto-scroll: keep the active lesson card centered in the canvas
  useEffect(() => {
    if (screen !== "toolkit") return;
    const c = canvasRef.current;
    const card = activeCardRef.current;
    if (!c || !card) return;
    // wait for layout
    requestAnimationFrame(() => {
      const cardCenter = card.offsetLeft + card.offsetWidth / 2;
      // Nudge 30px right of true centre so exactly one preceding card stays visible
      const target = cardCenter - c.clientWidth / 2 - 30;
      const prevWasIntro = flat[currentIdx - 1]?.type === "section-intro";
      if (prevWasIntro) {
        // Pre-position just behind the card so the short smooth nudge still plays
        c.scrollTo({ left: Math.max(0, target - 120), behavior: "instant" });
      }
      c.scrollTo({ left: Math.max(0, target), behavior: "smooth" });
    });
  }, [currentIdx, screen]);

  // ---------- TOC gate ----------
  const tocData = answers.toc || {};
  const isTocComplete = (
    (tocData.outputs || []).some(x => (x || "").trim()) &&
    (
      (tocData.outcomes_im || []).some(x => (x || "").trim()) ||
      (tocData.outcomes_it || []).some(x => (x || "").trim()) ||
      (tocData.outcomes_lt || []).some(x => (x || "").trim())
    ) &&
    (tocData.impact || []).some(x => (x || "").trim())
  );
  const [tocGateMsg, setTocGateMsg] = useState(null);
  useEffect(() => { if (isTocComplete) setTocGateMsg(null); }, [isTocComplete]);

  // (No auto-N/A needed for new method selection sections 3.3–3.5)

  // ---------- Handlers ----------
  const updateAnswer = (id, val) => setAnswers(a => ({ ...a, [id]: val }));
  const toggleNa = (lessonId, isNa) => setNaState(s => ({ ...s, [lessonId]: !!isNa }));
  const handleReset = () => {
    setAnswers({});
    setCurrentIdx(0);
    setNaState({});
    setProjectName("");
    setScreen("title");
    setTocGateMsg(null);
  };
  const toc12Idx = useMemo(() => flat.findIndex(f => f.id === "1.2"), [flat]);
  const jumpTo = (i) => {
    const target = Math.max(0, Math.min(flat.length - 1, i));
    if (target > toc12Idx && !isTocComplete) {
      setTocGateMsg("Before continuing, your Theory of Change needs at least one Output, one Outcome, and one Impact.");
      setCurrentIdx(toc12Idx);
      return;
    }
    setTocGateMsg(null);
    setCurrentIdx(target);
  };
  const next = () => jumpTo(currentIdx + 1);
  const prev = () => jumpTo(currentIdx - 1);

  // Keyboard navigation — skip when focus is inside a text input or textarea
  useEffect(() => {
    if (screen !== "toolkit") return;
    const onKey = (e) => {
      const tag = document.activeElement?.tagName;
      const isTyping = tag === "INPUT" || tag === "TEXTAREA" || document.activeElement?.isContentEditable;
      if (isTyping) return;
      if (e.key === "ArrowRight" || e.key === "Enter") { e.preventDefault(); next(); }
      if (e.key === "ArrowLeft")                        { e.preventDefault(); jumpTo(currentIdx - 1); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [screen, currentIdx, isTocComplete]);

  // ---------- Derived ----------
  const current = flat[currentIdx];
  const currentStep = steps.find(s => s.id === current.stepId);

  // Short answer preview for completed nodes
  const previewForLesson = useCallback((lesson) => {
    if (naState[lesson.id]) return "— Marked not applicable —";
    for (const p of lesson.prompts) {
      const preview = promptPreview(p, answers[p.id]);
      if (preview) return preview.length > 110 ? preview.slice(0, 110) + "…" : preview;
    }
    return null;
  }, [answers, naState]);

  const layout = "inline";
  const chrome = "full";

  // ---------- Render ----------
  if (screen === "title") {
    const hasProgress = currentIdx > 0 || Object.keys(answers).length > 0;
    return (
      <TitleScreen
        hasProgress={hasProgress}
        savedName={projectName}
        onStart={(name) => {
          if (name) setProjectName(name);
          setScreen(hasProgress ? "toolkit" : "intro");
        }}
      />
    );
  }

  if (screen === "intro") {
    return (
      <div className="app-root">
        <header className="app-header">
          <img className="app-header__logo" src="assets/isd-logo.png" alt="ISD"
            onClick={() => setScreen("title")} style={{ cursor: "pointer" }} title="Back to home" />
          <span className="app-header__divider" />
          <div><div className="app-header__title">Counter-Antisemitism MEL Toolkit</div></div>
          <div className="app-header__spacer" />
        </header>
        <div className="intro-wrap">
          <div className="lesson-card intro-card">
            <div className="intro-card__spine" aria-hidden="true">
              {steps.map((s) => (
                <span key={s.id} style={{ background: s.colorHex }} />
              ))}
            </div>
            <div className="lesson-card__inner">
              <h2 className="intro-card__heading intro-anim" style={{ animationDelay: "0ms" }}>
                Evaluating Projects to Counter Online Antisemitism
              </h2>
              <p className="intro-card__subheading intro-anim" style={{ animationDelay: "80ms" }}>
                An MEL Tool for Civil Society Organizations and Practitioners
              </p>
              <div className="intro-card__body intro-anim" style={{ animationDelay: "160ms" }}>
                <p>Monitoring, Evaluation &amp; Learning (MEL) is a crucial part of combatting antisemitism. A well-designed evaluation enables a practitioner to build an evidence base around effective approaches, identify problems in program design or delivery, demonstrate accountability to funders and partners, and make a credible case for continued or expanded support. In an area of work with high stakes and finite funding, it is crucial to understand what works and for whom, so good practices can be replicated and harmful practices rooted out.</p>
                <p>ISD developed this MEL tool to assist civil society practitioners in evaluating online and offline initiatives to counter antisemitism. It is designed to support a myriad of approaches and provide a practical evaluation framework for those with limited experience or technical knowledge of MEL.</p>
                <p>The MEL Tool is divided into four sections and will walk you through a series of steps to produce an evaluation plan for your project. Your progress will be saved automatically, and you can easily navigate back and forth between sections using the menu on the side or by scrolling sideways on your screen. The Tool was designed to be used alongside the Framework Guide, which will offer detailed explanations and examples for everything covered in the Tool.</p>
              </div>

              <div className="intro-rail intro-anim" style={{ animationDelay: "300ms" }}>
                <div className="intro-rail__label">This toolkit will guide you through four steps:</div>
                <div className="intro-rail__track">
                  {steps.map((s) => {
                    const target = flat.findIndex(f => f.stepId === s.id);
                    return (
                      <button
                        key={s.id}
                        className="intro-rail__step"
                        style={{ "--step-color": s.colorHex }}
                        onClick={() => { setCurrentIdx(target < 0 ? 0 : target); setScreen("toolkit"); }}
                        title={`Start at Step ${s.number}: ${s.title}`}
                      >
                        <span className="intro-rail__disc">{s.number}</span>
                        <span className="intro-rail__name">{s.title}</span>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="intro-card__cta intro-anim" style={{ animationDelay: "400ms" }}>
                <Btn variant="primary" iconRight="arrow-r" onClick={() => { setCurrentIdx(0); setScreen("toolkit"); }}>Begin toolkit</Btn>
                <span className="intro-card__cta-note">20 short sections &middot; your answers save as you go</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (screen === "report") {
    return (
      <ReportView
        steps={steps}
        answers={answers}
        naState={naState}
        projectName={projectName}
        onBack={() => setScreen("toolkit")}
      />
    );
  }

  // toolkit screen
  const showSidebar = chrome === "full" || chrome === "sectioned" || chrome === "rail";
  const sidebarMode = showSidebar ? chrome : null;

  return (
    <div className={`app-root app-root--chrome-${chrome}`} data-screen-label="MEL Toolkit">
      <header className="app-header">
        <img className="app-header__logo" src="assets/isd-logo.png" alt="ISD" onClick={() => setScreen("title")} style={{ cursor: "pointer" }} title="Back to home" />
        <span className="app-header__divider" />
        <div>
          <div className="app-header__title">Counter-Antisemitism MEL Toolkit</div>
        </div>
        {chrome === "tabs" && (
          <NavTabs steps={steps} flat={flat} currentIdx={currentIdx} onJump={jumpTo} tocLocked={!isTocComplete} />
        )}
        <div className="app-header__spacer" />
        {chrome !== "tabs" && (
          <div className="app-header__actions">
            <span className="app-header__autosave">Progress saves automatically</span>
            <Btn variant="ghost" icon="arrow-l" onClick={prev} disabled={currentIdx === 0}>Previous</Btn>
            {current.type === "section-intro"
              ? <Btn variant="primary" iconRight="arrow-r" onClick={next}>Begin Step {current.stepNumber}</Btn>
              : currentIdx < flat.length - 1
                ? <Btn variant="primary" iconRight="arrow-r" onClick={next}>Next section</Btn>
                : <Btn variant="primary" iconRight="doc" onClick={() => setScreen("report")}>Finish &amp; view report</Btn>
            }
          </div>
        )}
        {chrome === "tabs" && (
          <div className="app-header__project-pill" onClick={() => {
            const n = window.prompt("Project name:", projectName || "");
            if (n !== null) setProjectName(n.trim());
          }} title="Click to rename">
            <span className="app-header__project-name">{projectName || "Untitled MEL plan"}</span>
            <Icon name="pencil" size={12} />
          </div>
        )}
      </header>

      <div className="app-body">
        {showSidebar && (
          <Sidebar
            steps={steps}
            flat={flat}
            currentIdx={currentIdx}
            onJump={jumpTo}
            onOpenReport={() => setScreen("report")}
            projectName={projectName}
            mode={sidebarMode}
            onRename={(n) => { if (n) setProjectName(n); }}
            onReset={handleReset}
          />
        )}

        {current.type === "section-intro" ? (
          <SectionIntroView
            step={steps.find(s => s.id === current.stepId)}
            si={current.sectionIntro}
            onContinue={next}
            onBack={prev}
            currentIdx={currentIdx}
          />
        ) : layout === "inline" ? (
          <InlineCanvas
            steps={steps}
            flat={flat}
            currentIdx={currentIdx}
            answers={answers}
            updateAnswer={updateAnswer}
            naState={naState}
            onToggleNa={toggleNa}
            jumpTo={jumpTo}
            previewForLesson={previewForLesson}
            currentStep={currentStep}
            current={current}
            canvasRef={canvasRef}
            activeCardRef={activeCardRef}
            next={next}
            prev={prev}
            onOpenReport={() => setScreen("report")}
            showReportBtnInFooter={chrome === "tabs"}
            tocGateMsg={tocGateMsg}
          />
        ) : (
          <DockedCanvas
            steps={steps}
            flat={flat}
            currentIdx={currentIdx}
            answers={answers}
            updateAnswer={updateAnswer}
            naState={naState}
            onToggleNa={toggleNa}
            jumpTo={jumpTo}
            currentStep={currentStep}
            current={current}
            next={next}
            prev={prev}
            onOpenReport={() => setScreen("report")}
            showReportBtnInFooter={chrome === "tabs"}
            hideStrip={showSidebar}
          />
        )}
      </div>

    </div>
  );
}

/* ---------- Mount ---------- */
const rootEl = document.getElementById("root");
ReactDOM.createRoot(rootEl).render(<ToolkitApp />);
