/* global React, ReactDOM */
const { useState: useS, useEffect: useE, useMemo: useM, useRef: useR } = React;

const INITIAL = () => ({
  step: "hero",          // hero | q | email | celebration
  stepIdx: 0,
  motivation: null,
  branch: null,
  answers: {},
  email: "", name: "", mobile: "", consent: false,
  sessionId: window.uid(),
});

function flowSteps(state) {
  // Returns ordered keys for the current branch (after Q01)
  if (!state.branch) return [];
  const b = window.BCO_BRANCHES[state.branch];
  const arr = [...b.flow];
  if (b.altitude) arr.push(b.altitude);
  return arr;
}

function totalQuestions(state) {
  // hero (0) + Q01 + flowSteps + email = used for progress
  if (!state.branch) return 8;
  return 1 + flowSteps(state).length + 1;
}

function App() {
  const [state, setState] = useS(INITIAL);
  const [overlayOpen, setOverlayOpen] = useS(false);
  const [tweaksOpen, setTweaksOpen] = useS(false);

  // edit-mode protocol
  useE(() => {
    const onMsg = (e) => {
      const d = e.data;
      if (!d || typeof d !== "object") return;
      if (d.type === "__activate_edit_mode") setTweaksOpen(true);
      if (d.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent?.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const update = (patch) => setState(s => ({ ...s, ...patch }));
  const setAnswer = (key, val) => setState(s => ({ ...s, answers: { ...s.answers, [key]: val } }));

  // Q01 — motivation pseudo-question
  const Q1 = useM(() => ({
    id: "motivation",
    eyebrow: "QUESTION 01 / WHY ARE YOU HERE TODAY",
    title: "What brings you to today's event?",
    sub: "Whichever feels truest — pick one.",
    kind: "cards",
    options: window.BCO_MOTIVATION.map(m => ({
      id: m.id, label: m.label, hint: m.routes, glyph: m.glyph,
    })),
  }), []);

  const goNext = () => {
    setState(s => {
      if (s.step === "hero") return { ...s, step: "q01", stepIdx: 1 };
      if (s.step === "q01") {
        const m = window.BCO_MOTIVATION.find(x => x.id === s.motivation);
        return { ...s, step: "branch", branch: m.branch, stepIdx: 2 };
      }
      if (s.step === "branch") {
        const steps = flowSteps(s);
        const cur = s.stepIdx - 2; // 0-indexed within branch
        if (cur + 1 < steps.length) return { ...s, stepIdx: s.stepIdx + 1 };
        return { ...s, step: "email", stepIdx: s.stepIdx + 1 };
      }
      if (s.step === "email") return { ...s, step: "celebration" };
      return s;
    });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const goBack = () => {
    setState(s => {
      if (s.step === "q01") return { ...s, step: "hero", stepIdx: 0 };
      if (s.step === "branch") {
        if (s.stepIdx <= 2) return { ...s, step: "q01", stepIdx: 1, branch: null };
        return { ...s, stepIdx: s.stepIdx - 1 };
      }
      if (s.step === "email") {
        const steps = flowSteps(s);
        return { ...s, step: "branch", stepIdx: 1 + steps.length };
      }
      return s;
    });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const reset = () => setState(INITIAL());

  const usePersona = (p) => {
    setState({
      step: "celebration",
      stepIdx: 99,
      motivation: p.motivation,
      branch: p.branch,
      answers: p.answers,
      email: p.email,
      name: p.name,
      mobile: "",
      consent: true,
      sessionId: window.uid(),
    });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const jumpToBranch = (branchId) => {
    const motiv = window.BCO_MOTIVATION.find(m => m.branch === branchId);
    setState(s => ({
      ...INITIAL(),
      step: "branch",
      stepIdx: 2,
      motivation: motiv.id,
      branch: branchId,
    }));
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // ─── Render current step ──────────────────────────────────────────────────
  let body = null;
  const total = totalQuestions(state);
  const progress = state.step === "hero" ? 0
    : state.step === "celebration" ? 100
    : Math.min(98, Math.round(((state.stepIdx) / total) * 100));

  if (state.step === "hero") {
    body = <HeroScreen onStart={goNext} />;
  } else if (state.step === "q01") {
    body = (
      <QuestionScreen
        q={Q1}
        value={state.motivation}
        onChange={(v) => update({ motivation: v })}
        onNext={() => { if (state.motivation) goNext(); }}
        onBack={goBack}
      />
    );
  } else if (state.step === "branch") {
    const steps = flowSteps(state);
    const cur = state.stepIdx - 2;
    const q = steps[cur];
    if (!q) { body = null; }
    else {
      body = (
        <QuestionScreen
          key={`${state.branch}-${q.id}`}
          q={q}
          value={state.answers[q.id]}
          onChange={(v) => setAnswer(q.id, v)}
          onNext={goNext}
          onBack={goBack}
          isMulti={q.kind === "multi"}
        />
      );
    }
  } else if (state.step === "email") {
    body = (
      <EmailScreen
        value={{ email: state.email, name: state.name, mobile: state.mobile, consent: state.consent }}
        onChange={(v) => update(v)}
        onSubmit={goNext}
        onBack={goBack}
      />
    );
  } else if (state.step === "celebration") {
    body = <CelebrationScreen state={state} onShare={() => {}} onReset={reset} />;
  }

  return (
    <div className="app">
      <main className="journey-pane" data-screen-label="01 Journey">
        <TopBar sessionId={state.sessionId} />
        <div className="progress-rail">
          <div className="progress-fill" style={{ width: `${progress}%` }} />
        </div>
        {body}
        <div className="j-foot">
          <span className="pill">Concept demo</span>
          <span>Supporting breastcancer.org · not a substitute for medical advice</span>
          <span style={{ marginLeft: "auto" }}>No third-party data sharing · delete your record anytime</span>
        </div>
      </main>

      <BuyerOverlay
        state={state}
        open={overlayOpen}
        onClose={() => setOverlayOpen(false)}
        totalSteps={total}
      />

      <button className="overlay-toggle" onClick={() => setOverlayOpen(true)}>
        <span className="pulse-dot" />
        Live record
      </button>

      {tweaksOpen && (
        <DemoTweaks
          onClose={() => { setTweaksOpen(false); window.parent?.postMessage({ type: "__edit_mode_dismissed" }, "*"); }}
          onReset={reset}
          onJump={jumpToBranch}
          onPersona={usePersona}
        />
      )}
    </div>
  );
}

// ─── Demo controls (Tweaks panel) ─────────────────────────────────────────
function DemoTweaks({ onClose, onReset, onJump, onPersona }) {
  return (
    <div style={{
      position: "fixed", right: 20, bottom: 20, zIndex: 60, width: 320,
      background: "#fff", borderRadius: 16, boxShadow: "0 18px 50px -12px rgba(0,0,0,0.28)",
      border: "1px solid var(--line)", overflow: "hidden",
      fontFamily: "var(--font-sans)", fontSize: 13,
    }}>
      <div style={{
        padding: "14px 16px", borderBottom: "1px solid var(--line)",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--pink)" }} />
          <strong style={{ fontWeight: 600 }}>Tweaks</strong>
          <span style={{ color: "var(--ink-3)", fontSize: 11.5 }}>demo controls</span>
        </div>
        <button onClick={onClose} style={{ border: "none", background: "transparent", cursor: "pointer", color: "var(--ink-3)", fontSize: 16 }}>✕</button>
      </div>
      <div style={{ padding: "14px 16px", display: "flex", flexDirection: "column", gap: 14 }}>
        <div>
          <div style={{ fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 8 }}>JUMP TO BRANCH</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
            {[
              ["partnership", "Partnership"],
              ["coverage", "Coverage"],
              ["personal", "Personal"],
              ["combined", "Combined"],
              ["light", "Light-touch"],
            ].map(([id, label]) => (
              <button key={id} onClick={() => onJump(id)} style={chipBtn}>{label}</button>
            ))}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 10.5, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 8 }}>PRE-BAKED PERSONA → CELEBRATION</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {window.BCO_PERSONAS.map(p => (
              <button key={p.id} onClick={() => onPersona(p)} style={{ ...chipBtn, textAlign: "left", padding: "9px 12px" }}>
                {p.label}
              </button>
            ))}
          </div>
        </div>
        <div>
          <button onClick={onReset} style={{ ...chipBtn, width: "100%", background: "var(--ink)", color: "var(--cream)", borderColor: "var(--ink)" }}>
            Reset journey
          </button>
        </div>
        <p style={{ margin: 0, fontSize: 11.5, color: "var(--ink-3)", lineHeight: 1.5 }}>
          For the Carl walkthrough: start clean from the hero, or use a persona to land directly on the celebration with a populated Buyer Overlay.
        </p>
      </div>
    </div>
  );
}
const chipBtn = {
  padding: "8px 12px", borderRadius: 10, border: "1px solid var(--line)",
  background: "#fff", color: "var(--ink)", cursor: "pointer",
  font: "inherit", fontSize: 12.5, textAlign: "center",
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
