/* eslint-disable */
/* Main app — orchestrates flow, shell, tweaks */

const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA, useRef: useRefA } = React;

const TWEAK_DEFAULS = /*EDITMODE-BEGIN*/{
  "viewMode": "auto",
  "ctaCopy": "Scan the can · Start",
  "headlineVariant": "primary",
  "jumpLevel": 0,
  "showBuyerOverlay": true,
  "autoPlay": false,
  "accent": "cobalt",
  "radius": "soft",
  "tone": "warm"
}/*EDITMODE-END*/;

/* ===== Demo intro overlay — first-load only ===== */
function DemoIntro({ onStart }) {
  return (
    <div className="demo-intro" role="dialog" aria-label="Demo introduction">
      <div className="demo-intro__card">
        <p className="demo-intro__eyebrow">Private concept demo · Q-S × Chase × Ape Beverages</p>
        <h2 className="demo-intro__title">Ape Water as a Chase in-branch acquisition surface.</h2>
        <p className="demo-intro__body">
          What you're about to see is one customer scanning a co-branded Ape Water can in a Chase branch lobby. In about 90 seconds they answer 4–10 questions tuned to their persona, and walk out with a matched Chase product + a verified declared record routed to your branch banker queue.
        </p>
        <ul className="demo-intro__list">
          <li>The phone is what the visitor sees on the floor.</li>
          <li>The right pane (desktop) is the live Buyer Overlay your branch team sees.</li>
          <li>Try the four jumps in the rail or scan straight through.</li>
        </ul>
        <button className="demo-intro__cta" onClick={onStart}>Start the demo →</button>
        <p className="demo-intro__foot">Illustrative · Not a live Chase offer · No live customer data captured</p>
      </div>
    </div>
  );
}

/* ===== Data-flow diagram — explains where the data goes ===== */
function FlowDiagram() {
  const steps = [
    "Scan can (QR / NFC)",
    "Collect declared answers",
    "Verify (email + SMS OTP)",
    "Segment (10-Q stack)",
    "Route to banker queue",
    "Sync to Salesforce / CDP",
  ];
  return (
    <div className="flow-diagram">
      <p className="flow-diagram__title">Data flow · concept</p>
      <div className="flow-diagram__steps">
        {steps.map((s, i) => (
          <React.Fragment key={s}>
            <div className="flow-diagram__step">
              <span className="flow-diagram__num">{i+1}</span>
              <span>{s}</span>
            </div>
            {i < steps.length - 1 && <div className="flow-diagram__arrow">↓</div>}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

/* ===== Behind-the-scenes capstone — slides in post-celebration ===== */
function BehindScenes({ flow, answers, onClose }) {
  const leadId = flow === "business" || flow === "both" ? "BIZ-04711"
                : flow === "personal" ? "P-19284" : "J-30201";
  const audience = flow === "business" || flow === "both" ? "BizSwitch_NonChase_Tier2"
                  : flow === "personal" ? "Sapphire_Travel_Affluent"
                  : "JustHere_Nurture_NonChase";
  const banker = flow === "business" || flow === "both" ? "Marisol Aguilar"
                : flow === "personal" ? "Devon Park" : "Jordan Reyes";
  return (
    <div className="btsx" role="dialog" aria-label="Behind the scenes — what Chase just received">
      <button className="btsx__close" onClick={onClose} aria-label="Close">×</button>
      <p className="btsx__eyebrow">Behind the scenes · Chase view</p>
      <h3 className="btsx__title">Record provisioned. Routed to your CRM in 47 seconds.</h3>
      <div className="btsx__rows">
        <div className="btsx__row"><span>Salesforce lead</span><b>{leadId}</b></div>
        <div className="btsx__row"><span>Chase CDP audience</span><b>{audience}</b></div>
        <div className="btsx__row"><span>Banker queue</span><b>{banker}</b></div>
        <div className="btsx__row"><span>Verified declared record</span><b>est. value $14</b></div>
        <div className="btsx__row"><span>Estimated CAC</span><b>~$4 / record</b></div>
        <div className="btsx__row"><span>Time-to-handoff</span><b>47 seconds</b></div>
      </div>
      <p className="btsx__foot">Illustrative figures · routing + integrations subject to Phase 0 scoping</p>
    </div>
  );
}

function useViewMode(viewMode) {
  const [mode, setMode] = useStateA(() => {
    if (viewMode === "mobile") return "mobile";
    if (viewMode === "desktop") return "desktop";
    return window.innerWidth < 980 ? "mobile" : "desktop";
  });
  useEffectA(() => {
    if (viewMode === "mobile") return setMode("mobile");
    if (viewMode === "desktop") return setMode("desktop");
    const onResize = () => setMode(window.innerWidth < 980 ? "mobile" : "desktop");
    onResize();
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, [viewMode]);
  return mode;
}

/* Build flow sequence given current state */
function buildSequence(flow, answers) {
  const { Q_GATE, BIZ, PERS, JUST, buildBizQ10 } = window.QUESTIONS;
  const filt = (arr) => arr.filter((q) => !q.onlyIf || q.onlyIf(answers));
  if (!flow) return [Q_GATE];
  if (flow === "business" || flow === "both") {
    // "Both" = already a Chase business customer — pre-fill biz_bank so Q07 + the
    // non-Chase Q08 are skipped via onlyIf, and the Chase-customer Q08 surfaces.
    const biz_bank = flow === "both" ? "us" : answers.biz_bank;
    const a2 = { ...answers, biz_bank };
    const filt2 = (arr) => arr.filter((q) => !q.onlyIf || q.onlyIf(a2));
    const skipBank = (q) => q.id !== "biz_bank";
    return [Q_GATE, ...filt2(BIZ).filter(flow === "both" ? skipBank : () => true), buildBizQ10(a2.biz_capital || [])];
  }
  if (flow === "personal") return [Q_GATE, ...filt(PERS)];
  if (flow === "just") return [Q_GATE, ...filt(JUST), { id: "j_email", isEmail: true }];
  return [Q_GATE];
}

function flowFromGate(v) {
  if (v === "personal") return "personal";
  if (v === "business") return "business";
  if (v === "both") return "both";
  if (v === "just") return "just";
  return null;
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULS);
  const mode = useViewMode(tweaks.viewMode);

  // Phase: 'hero' | 'questions' | 'capture' | 'celebration'
  const [phase, setPhase] = useStateA("hero");
  const [answers, setAnswers] = useStateA({});
  const [screenIndex, setScreenIndex] = useStateA(0);
  const [toast, setToast] = useStateA(null);

  // Demo intro — show on first load, dismiss to start
  const [introOpen, setIntroOpen] = useStateA(true);
  // Behind-the-scenes capstone — auto-show when celebration appears
  const [showBTSX, setShowBTSX] = useStateA(false);

  const flow = flowFromGate(answers.gate);
  const sequence = useMemoA(() => buildSequence(flow, answers), [flow, answers]);
  const total = sequence.length;
  const currentQ = sequence[screenIndex] || sequence[0];

  // Apply tweak: jumpLevel
  useEffectA(() => {
    if (typeof tweaks.jumpLevel === "number" && tweaks.jumpLevel >= 0) {
      // 0 = hero, 1..N = question N, last = celebration
      const lvl = tweaks.jumpLevel;
      if (lvl === 0) { setPhase("hero"); setScreenIndex(0); return; }
      // Use mock answers so the BO has something to show
      if (lvl >= 1 && !flow) {
        // pick personal as default jump target
        setAnswers((a) => Object.keys(a).length === 0
          ? { gate: "personal", p_intent: "new", p_bank: "big_boa", p_switch: ["travel","cash"], p_travel: "13", p_move: ["home","biz"], p_side: "free", p_stage: "work", firstName: "Sam" }
          : a);
        setPhase("questions");
        setScreenIndex(Math.min(lvl, 8));
      }
    }
  }, [tweaks.jumpLevel]);

  const setAnswer = (qid, value) => setAnswers((a) => ({ ...a, [qid]: value }));

  const advance = () => {
    // Recompute sequence from the LATEST answers — flow may have just been set
    // by the gate question, so `total` from this render's closure is stale.
    const seq = buildSequence(flowFromGate(answers.gate), answers);
    const realTotal = seq.length;
    if (screenIndex + 1 >= realTotal) {
      const f = flowFromGate(answers.gate);
      const needsCapture = (f === "personal" || f === "business" || f === "both") && !answers.contact;
      if (needsCapture) {
        setPhase("capture");
        return; // No toast — advancing is its own confirmation; progress bar shows it.
      }
      setPhase("celebration");
      setShowBTSX(true);
      // Single milestone toast — completing the entire flow earns +50.
      setToast({ key: Date.now(), text: <><b>+50</b> reward pts · concept demo</> });
      return;
    }
    setScreenIndex(screenIndex + 1);
    // No per-question toast — the progress bar's filling dot is the confirmation.
  };

  const completeCapture = () => {
    setPhase("celebration");
    setShowBTSX(true);
    setToast({ key: Date.now(), text: <><b>Verified</b> · +50 reward pts · concept demo</> });
  };

  const back = () => {
    if (screenIndex === 0) { setPhase("hero"); return; }
    setScreenIndex(Math.max(0, screenIndex - 1));
  };

  const startScan = () => {
    setPhase("questions");
    setScreenIndex(0);
  };

  const restart = () => {
    setPhase("hero");
    setScreenIndex(0);
    setAnswers({});
  };

  const addBiz = () => {
    setAnswers((a) => ({ ...a, gate: "both", _stealth: true }));
    setScreenIndex(1); // start business sub-flow
    setPhase("questions");
    // Stealth-SMB add — no toast, the question screen change itself is the cue.
  };

  // Build screen content
  let screen;
  if (phase === "hero") {
    screen = <Hero
      headlineVariant={tweaks.headlineVariant}
      ctaCopy={tweaks.ctaCopy}
      onScan={startScan}
    />;
  } else if (phase === "capture") {
    // Universal contact capture — used by Personal + Business flows
    screen = <ContactCaptureScreen
      total={total + 1}
      current={total}
      flow={flow}
      value={answers.contact}
      onChange={(v) => setAnswer("contact", v)}
      firstName={answers.firstName}
      onFirstNameChange={(v) => setAnswer("firstName", v)}
      onBack={() => { setPhase("questions"); setScreenIndex(total - 1); }}
      onSubmit={completeCapture}
    />;
  } else if (phase === "celebration") {
    screen = <Celebration state={{ flow, answers, firstName: answers.firstName }} onRestart={restart} onAddBiz={addBiz}/>;
  } else if (currentQ?.isEmail) {
    screen = <EmailScreen
      total={total}
      current={screenIndex}
      value={answers.j_email}
      onChange={(v) => setAnswer("j_email", v)}
      firstName={answers.firstName}
      onFirstNameChange={(v) => setAnswer("firstName", v)}
      onBack={back}
      onSubmit={advance}
    />;
  } else {
    screen = <QuestionScreen
      q={currentQ}
      value={answers[currentQ.id]}
      total={total}
      current={screenIndex}
      onChange={(v) => setAnswer(currentQ.id, v)}
      onNext={advance}
      onBack={back}
    />;
  }

  // Rail (desktop only)
  const rail = (
    <div className="stage__rail">
      <div className="rail__brand">
        <div className="rail__mark"><Mark size={32} color="var(--primary)"/></div>
        <div>
          <div className="rail__name">Chase × Ape Water</div>
          <div className="rail__sub">In-Branch Concept Demo · v1.0</div>
        </div>
      </div>

      <div className="rail__title">Stakeholder demo</div>
      <p style={{fontSize:12, lineHeight:1.5, color:"var(--ink-2)", margin:"0 0 8px"}}>
        The phone is what someone scans on the floor. The right pane is what your branch team sees while they answer.
      </p>

      <div className="rail__title">Jump to</div>
      <div className="rail__list">
        {[
          { i: 0, label: "Hero · scan moment" },
          { i: 1, label: "Q1 · the gate" },
          { i: 2, label: "Q2 · into the flow" },
          { i: 5, label: "Mid-flow" },
          { i: 99, label: "Celebration" },
        ].map(item => (
          <div
            key={item.i}
            className="rail__item"
            data-active={(item.i === 0 && phase === "hero") || (item.i === 99 && phase === "celebration") ? "true" : "false"}
            onClick={() => {
              if (item.i === 0) restart();
              else if (item.i === 99) {
                setAnswers({ gate: "business", biz_role:"owner", biz_industry:"food", biz_age:"3to10", biz_rev:"500_2", biz_intent:"loan", biz_capital:["wc","equip"], biz_bank:"big1", biz_switch:["lending","rates"], biz_payments:"square", biz_q10_use:"inv", firstName:"Sam", contact: { email:"sam@example.com", phone:"5551234567", optIn:true, verified:true }});
                setPhase("celebration");
                setShowBTSX(true);
              } else {
                if (!flow) setAnswers({ gate: "personal" });
                setPhase("questions");
                setScreenIndex(item.i);
              }
            }}
          >
            <span>{item.label}</span>
            <span className="num">{item.i === 99 ? "END" : String(item.i+1).padStart(2,"0")}</span>
          </div>
        ))}
      </div>

      <FlowDiagram/>

      <div className="rail__title">Live state</div>
      <div style={{font:"500 11px/1.5 'Geist Mono', monospace", color:"var(--ink-3)"}}>
        Phase · <span style={{color:"var(--ink)"}}>{phase}</span><br/>
        Flow · <span style={{color:"var(--ink)"}}>{flow || "—"}</span><br/>
        Step · <span style={{color:"var(--ink)"}}>{phase === "questions" ? `${screenIndex+1}/${total}` : phase === "capture" ? "contact" : "—"}</span>
      </div>

      <div className="rail__footer">
        Concept demo · chase.drinkape.com<br/>
        Not affiliated with JPMorgan Chase · For Q-S × Chase review only
      </div>
    </div>
  );

  return (
    <div className="stage" data-mode={mode}>
      {/* Demo CTA modal — fired by celebration buttons */}
      <DemoCTAModal/>

      {/* First-load demo intro overlay — desktop only, dismissible */}
      {introOpen && mode !== "mobile" && <DemoIntro onStart={() => setIntroOpen(false)}/>}

      {/* Behind-the-scenes capstone — auto-shown on celebration, desktop only */}
      {showBTSX && phase === "celebration" && mode !== "mobile" && (
        <BehindScenes flow={flow} answers={answers} onClose={() => setShowBTSX(false)}/>
      )}

      {rail}
      <div className="stage__phone">
        {mode === "mobile"
          ? screen
          : <PhoneFrame label={phase === "hero" ? "Scan landing" : phase === "celebration" ? "Output" : phase === "capture" ? "Contact + verify" : `Q ${screenIndex+1}/${total}`}>{screen}</PhoneFrame>}
        {toast && <div style={{position:"absolute", left:0, right:0, top: mode === "mobile" ? "max(env(safe-area-inset-top), 8px)" : 14, display:"flex", justifyContent:"center", pointerEvents:"none", zIndex:30}}>
          <Toast key={toast.key} onDone={() => setToast(null)}>{toast.text}</Toast>
        </div>}
      </div>
      {tweaks.showBuyerOverlay && (
        <div className="stage__overlay">
          <BuyerOverlay state={{ flow, answers, screenIndex }}/>
        </div>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Demo shell">
          <TweakRadio
            label="View mode"
            value={tweaks.viewMode}
            onChange={(v) => setTweak("viewMode", v)}
            options={[
              { value: "auto",    label: "Auto" },
              { value: "mobile",  label: "Mobile" },
              { value: "desktop", label: "Desktop" },
            ]}
          />
          <TweakToggle
            label="Buyer Overlay (right pane)"
            value={tweaks.showBuyerOverlay}
            onChange={(v) => setTweak("showBuyerOverlay", v)}
          />
        </TweakSection>

        <TweakSection label="Hero copy">
          <TweakRadio
            label="Headline variant"
            value={tweaks.headlineVariant}
            onChange={(v) => setTweak("headlineVariant", v)}
            options={[
              { value: "primary", label: "Primary" },
              { value: "minimal", label: "Minimal" },
              { value: "bold",    label: "Bold" },
            ]}
          />
          <TweakText
            label="CTA copy"
            value={tweaks.ctaCopy}
            onChange={(v) => setTweak("ctaCopy", v)}
          />
        </TweakSection>

        <TweakSection label="Jump to screen">
          <TweakNumber
            label="Step (0 = hero)"
            value={tweaks.jumpLevel}
            onChange={(v) => setTweak("jumpLevel", v)}
            min={0} max={11} step={1}
          />
          <TweakButton label="Jump to celebration (Business)" onClick={() => {
            setAnswers({ gate: "business", biz_role:"owner", biz_industry:"food", biz_age:"3to10", biz_rev:"500_2", biz_intent:"loan", biz_capital:["wc","equip"], biz_bank:"big1", biz_switch:["lending","rates"], biz_payments:"square", biz_q10_use:"inv", firstName:"Sam", contact: { email:"sam@example.com", phone:"5551234567", optIn:true, verified:true }});
            setPhase("celebration");
            setShowBTSX(true);
          }}/>
          <TweakButton label="Jump to celebration (Personal)" onClick={() => {
            setAnswers({ gate: "personal", p_intent:"new", p_bank:"big_boa", p_switch:["travel"], p_travel:"intl", p_move:["home","biz"], p_side:"free", p_stage:"work", firstName:"Sam", contact: { email:"sam@example.com", phone:"5551234567", optIn:true, verified:true }});
            setPhase("celebration");
            setShowBTSX(true);
          }}/>
          <TweakButton label="Jump to celebration (Just here)" onClick={() => {
            setAnswers({ gate: "just", j_customer:"card", j_switch:"rewards", j_market:["card","biz"], j_email: { email:"sam@example.com", optIn:true }, firstName:"Sam" });
            setPhase("celebration");
            setShowBTSX(true);
          }}/>
          <TweakButton label="Show demo intro again" onClick={() => setIntroOpen(true)}/>
          <TweakButton label="Show behind-the-scenes" onClick={() => setShowBTSX(true)}/>
          <TweakButton label="Restart" onClick={restart}/>
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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