// Main app — Lucy AI prototype shell

const Phone = ({ children, theme, T, accent, focused, onFocus, label, lang, setLang, setTheme, screen, setScreen, t, name, setName, phone, setPhone, gender, setGender, consent, setConsent, alloc, setAlloc, goals, setGoals, vizVariant, density }) => {
  const W = 402, H = 874;
  const scrollRef = React.useRef(null);
  
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTo(0, 0);
  }, [screen]);

  const scale = focused ? 1 : 1;
  return (
    <div style={{
      width: W, height: H, borderRadius: 56, position: "relative", overflow: "hidden",
      background: T.bg,
      boxShadow: theme === "dark"
        ? "0 60px 120px rgba(0,0,0,0.6), 0 0 0 12px #0a0a0c, 0 0 0 13px rgba(255,255,255,0.06), 0 0 0 14px #0a0a0c"
        : "0 60px 120px rgba(11,15,25,0.18), 0 0 0 12px #1a1f2e, 0 0 0 13px rgba(255,255,255,0.1), 0 0 0 14px #1a1f2e",
      fontFamily: FONTS.ui,
      WebkitFontSmoothing: "antialiased",
      transition: "all 300ms ease",
    }} data-screen-label={`${label}`}>

      {/* dynamic island */}
      <div style={{
        position: "absolute", top: 11, left: "50%", transform: "translateX(-50%)",
        width: 126, height: 37, borderRadius: 24, background: "#000", zIndex: 100,
      }} />

      {/* status bar */}
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0, height: 54, zIndex: 80,
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "18px 32px 0",
      }}>
        <span style={{ fontFamily: '-apple-system, "SF Pro", system-ui', fontWeight: 600, fontSize: 16, color: T.text }}>9:41</span>
        <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
          <svg width="18" height="11" viewBox="0 0 18 11"><rect x="0" y="7" width="3" height="4" rx="0.6" fill={T.text}/><rect x="4.5" y="5" width="3" height="6" rx="0.6" fill={T.text}/><rect x="9" y="2.5" width="3" height="8.5" rx="0.6" fill={T.text}/><rect x="13.5" y="0" width="3" height="11" rx="0.6" fill={T.text}/></svg>
          <svg width="25" height="12" viewBox="0 0 25 12"><rect x="0.5" y="0.5" width="22" height="11" rx="3" stroke={T.text} strokeOpacity="0.4" fill="none"/><rect x="2" y="2" width="18" height="8" rx="1.6" fill={T.text}/></svg>
        </div>
      </div>

      {/* main content surface */}
      <div style={{
        position: "absolute", top: 54, left: 0, right: 0, bottom: 0,
        display: "flex", flexDirection: "column",
      }}>
        <LucyHeader T={T} t={t} lang={lang} setLang={setLang} theme={theme} setTheme={setTheme}
          accent={accent} showBack={screen !== "landing" && screen !== "report"}
          onBack={() => setScreen(prev(screen))}
          onRestart={screen === "report" ? () => setScreen("landing") : null}
          step={STEPS[screen]} />

        <div ref={scrollRef} style={{ flex: 1, overflow: "auto", scrollbarWidth: "none" }} className="lucy-scroll">
          {screen === "landing" && <LandingScreen T={T} t={t} accent={accent} theme={theme} onStart={() => setScreen("contact")} />}
          {screen === "contact" && <ContactScreen T={T} t={t} accent={accent} theme={theme}
            name={name} setName={setName} phone={phone} setPhone={setPhone} consent={consent} setConsent={setConsent}
            onNext={() => setScreen("alloc")} />}
          {screen === "alloc" && <AllocationScreen T={T} t={t} accent={accent} theme={theme} alloc={alloc} setAlloc={setAlloc} onNext={() => setScreen("goals")} />}
          {screen === "goals" && <GoalsScreen T={T} t={t} accent={accent} theme={theme} goals={goals} setGoals={setGoals} onNext={() => setScreen("processing")} />}
          {screen === "processing" && <ProcessingScreen T={T} t={t} accent={accent} theme={theme} onDone={() => setScreen("report")} />}
          {screen === "report" && <ReportScreen T={T} t={t} accent={accent} theme={theme} name={name} alloc={alloc} onRestart={() => setScreen("landing")} onOptimize={() => setScreen("missingOut2")} vizVariant={vizVariant} />}
          {screen === "missingOut2" && <MissingOutPanel2Screen T={T} t={t} accent={accent} theme={theme} alloc={alloc} onNext={() => setScreen("missingOut3")} />}
          {screen === "missingOut3" && <MissingOutPanel3Screen T={T} t={t} accent={accent} theme={theme} alloc={alloc} onNext={() => setScreen("simulator")} />}
          {screen === "simulator" && <SimulatorScreen T={T} t={t} accent={accent} theme={theme} alloc={alloc} onNext={() => setScreen("fundPreview")} />}
          {screen === "fundPreview" && <FundPreviewScreen T={T} t={t} accent={accent} theme={theme} onNext={() => setScreen("bookingForm")} onRestart={() => setScreen("landing")} />}
          {screen === "bookingForm" && <BookingFormScreen T={T} t={t} accent={accent} theme={theme} name={name} gender={gender} setGender={setGender} onNext={() => setScreen("bookingConfirm")} />}
          {screen === "bookingConfirm" && <BookingConfirmScreen T={T} t={t} accent={accent} theme={theme} name={name} gender={gender} onNext={() => setScreen("dashboard")} />}
          {screen === "dashboard" && <DashboardScreen T={T} t={t} accent={accent} theme={theme} alloc={alloc} name={name} onRestart={() => setScreen("landing")} onGoToReport={() => setScreen("report")} />}
        </div>
      </div>

      {/* home indicator */}
      <div style={{
        position: "absolute", bottom: 8, left: "50%", transform: "translateX(-50%)",
        width: 139, height: 5, borderRadius: 100,
        background: theme === "dark" ? "rgba(255,255,255,0.55)" : "rgba(0,0,0,0.32)", zIndex: 90,
      }} />
    </div>
  );
};

const STEPS = {
  landing: null,
  contact: "01 / 03",
  alloc: "02 / 03",
  goals: "03 / 03",
  processing: null,
  report: null,
  missingOut2: null,
  missingOut3: null,
  simulator: null,
  fundPreview: null,
  bookingForm: null,
  bookingConfirm: null,
  dashboard: null,
};

const ORDER = ["landing", "contact", "alloc", "goals", "processing", "report", "missingOut2", "missingOut3", "simulator", "fundPreview", "bookingForm", "bookingConfirm", "dashboard"];
function prev(s) { return ORDER[Math.max(0, ORDER.indexOf(s) - 1)]; }

const DEFAULT_ALLOC = { bank: 35, realEstate: 30, stocks: 15, bonds: 5, gold: 10, crypto: 5 };

// Helper for persistence
const getStored = (key, fallback) => {
  try {
    const v = localStorage.getItem(key);
    if (v === null) return fallback;
    if (v === "true") return true;
    if (v === "false") return false;
    if (!isNaN(v) && v !== "") return JSON.parse(v);
    return v;
  } catch(e) { return fallback; }
};

const getStoredObj = (key, fallback) => {
  try {
    const v = localStorage.getItem(key);
    return v ? JSON.parse(v) : fallback;
  } catch(e) { return fallback; }
};

function App() {
  const tweaks = useTweaks(/*EDITMODE-BEGIN*/{
    "theme": "dark",
    "lang": "vn",
    "accent": "classic",
    "serif": "fraunces",
    "density": "comfortable",
    "vizVariant": "single"
  }/*EDITMODE-END*/);

  const [{ theme: tweakTheme, lang: tweakLang, accent: accentKey, serif, density, vizVariant }, setTweak] = tweaks;

  // Persistent state
  const [theme, setTheme] = React.useState(() => getStored("lucy-theme", tweakTheme));
  const [lang, setLang] = React.useState(() => getStored("lucy-lang", tweakLang));
  const [name, setName] = React.useState(() => getStored("lucy-name", ""));
  const [phone, setPhone] = React.useState(() => getStored("lucy-phone", ""));
  const [gender, setGender] = React.useState(() => getStored("lucy-gender", "anh"));
  const [alloc, setAlloc] = React.useState(() => getStoredObj("lucy-alloc", DEFAULT_ALLOC));
  const [screen, setScreen] = React.useState(() => getStored("lucy-screen", "landing"));
  const [consent, setConsent] = React.useState(() => getStored("lucy-consent", false));
  const [goals, setGoals] = React.useState(() => getStoredObj("lucy-goals", []));

  // Sync to localStorage
  React.useEffect(() => { localStorage.setItem("lucy-theme", theme); }, [theme]);
  React.useEffect(() => { localStorage.setItem("lucy-lang", lang); }, [lang]);
  React.useEffect(() => { localStorage.setItem("lucy-name", name); }, [name]);
  React.useEffect(() => { localStorage.setItem("lucy-phone", phone); }, [phone]);
  React.useEffect(() => { localStorage.setItem("lucy-gender", gender); }, [gender]);
  React.useEffect(() => { localStorage.setItem("lucy-alloc", JSON.stringify(alloc)); }, [alloc]);
  React.useEffect(() => { localStorage.setItem("lucy-screen", screen); }, [screen]);
  React.useEffect(() => { localStorage.setItem("lucy-consent", consent); }, [consent]);
  React.useEffect(() => { localStorage.setItem("lucy-goals", JSON.stringify(goals)); }, [goals]);

  const T = THEMES[theme];
  const t = COPY[lang];
  const accent = ACCENTS.classic;

  // Canvas mode
  const [canvasMode, setCanvasMode] = React.useState(false);

  // Replace serif font (overrides the alias FONTS.fraunces used by SerifTitle)
  const SERIF_MAP = {
    fraunces: "'Fraunces', 'Times New Roman', serif",
    instrument: "'Instrument Serif', 'Times New Roman', serif",
    playfair: "'Playfair Display', 'Times New Roman', serif",
    dmserif: "'DM Serif Display', 'Times New Roman', serif",
  };
  React.useEffect(() => { FONTS.fraunces = SERIF_MAP[serif]; }, [serif]);

  return (
    <div style={{
      minHeight: "100vh", width: "100%",
      background: theme === "dark"
        ? "radial-gradient(ellipse at 30% 0%, #131927, #060810 60%)"
        : "radial-gradient(ellipse at 30% 0%, #ECE6D6, #DDD6C2 70%)",
      transition: "background 400ms ease",
      padding: "32px 20px 80px",
      display: "flex", flexDirection: "column", alignItems: "center", gap: 20,
    }}>
      {/* Top bar — mode toggle */}
      <div style={{ width: "100%", maxWidth: 1400, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <LucyMark size={32} accent={accent.primary} />
          <div>
            <div style={{ fontFamily: FONTS.fraunces, fontSize: 18, fontWeight: 500, color: theme === "dark" ? "#F4F2EC" : "#0B0F19", letterSpacing: -0.3 }}>Lucy AI</div>
            <div style={{ fontFamily: FONTS.ui, fontSize: 10.5, color: theme === "dark" ? "#94A3B8" : "#62748E", letterSpacing: 0.4, textTransform: "uppercase" }}>Wealth Diagnostic — Prototype</div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 4, padding: 4, borderRadius: 999, background: theme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(11,15,25,0.05)", border: `1px solid ${theme === "dark" ? "rgba(255,255,255,0.08)" : "rgba(11,15,25,0.08)"}` }}>
          {[
            { k: false, label: "Prototype" },
            { k: true,  label: "Canvas overview" },
          ].map(o => (
            <button key={String(o.k)} onClick={() => setCanvasMode(o.k)} style={{
              fontFamily: FONTS.ui, fontSize: 12, fontWeight: 500,
              padding: "8px 16px", border: "none", cursor: "pointer", borderRadius: 999,
              background: canvasMode === o.k ? accent.primary : "transparent",
              color: canvasMode === o.k ? "#0B0F19" : (theme === "dark" ? "#94A3B8" : "#45556C"),
              transition: "all 200ms",
            }}>{o.label}</button>
          ))}
        </div>
      </div>

      {/* Body */}
      {!canvasMode ? (
        <Phone
          theme={theme} T={T} accent={accent} label={`${screen}`}
          lang={lang} setLang={(l) => setTweak("lang", l)}
          setTheme={(th) => setTweak("theme", th)}
          screen={screen} setScreen={setScreen} t={t}
          name={name} setName={setName} phone={phone} setPhone={setPhone}
          gender={gender} setGender={setGender}
          consent={consent} setConsent={setConsent}
          alloc={alloc} setAlloc={setAlloc} goals={goals} setGoals={setGoals}
          vizVariant={vizVariant} density={density}
        />
      ) : (
        <CanvasOverview
          theme={theme} setTheme={(th) => setTweak("theme", th)}
          lang={lang} setLang={(l) => setTweak("lang", l)}
          accent={accent} accentKey={accentKey}
          vizVariant={vizVariant}
          alloc={alloc} setAlloc={setAlloc}
          goals={goals} setGoals={setGoals}
          name={name} phone={phone}
          setName={setName} setPhone={setPhone}
          consent={consent} setConsent={setConsent}
        />
      )}

      <TweaksPanel>
        <TweakSection title="Theme">
          <TweakRadio value={theme} options={["dark", "light"]} onChange={(v) => setTweak("theme", v)} />
        </TweakSection>
        <TweakSection title="Language">
          <TweakRadio value={lang} options={["vn", "en"]} onChange={(v) => setTweak("lang", v)} />
        </TweakSection>
        <TweakSection title="Accent">
          <TweakSelect value={accentKey} options={[
            { value: "classic", label: "Editorial gold" },
            { value: "ivory", label: "Ivory" },
            { value: "copper", label: "Copper" },
            { value: "sage", label: "Sage" },
          ]} onChange={(v) => setTweak("accent", v)} />
        </TweakSection>
        <TweakSection title="Serif headline">
          <TweakSelect value={serif} options={[
            { value: "fraunces", label: "Fraunces" },
            { value: "instrument", label: "Instrument Serif" },
            { value: "playfair", label: "Playfair Display" },
            { value: "dmserif", label: "DM Serif Display" },
          ]} onChange={(v) => setTweak("serif", v)} />
        </TweakSection>
        <TweakSection title="Report viz">
          <TweakSelect value={vizVariant} options={[
            { value: "single", label: "Single radial dial" },
            { value: "rings", label: "Radial + sub-rings" },
            { value: "editorial", label: "Editorial — big number" },
          ]} onChange={(v) => setTweak("vizVariant", v)} />
        </TweakSection>
        <TweakSection title="Density">
          <TweakRadio value={density} options={["comfortable", "compact"]} onChange={(v) => setTweak("density", v)} />
        </TweakSection>
        <TweakSection title="Jump to screen">
          <TweakSelect value={screen} options={[
            { value: "landing", label: "1. Landing" },
            { value: "contact", label: "2. Contact" },
            { value: "alloc", label: "3. Allocation" },
            { value: "goals", label: "4. Goals" },
            { value: "processing", label: "5. Processing" },
            { value: "report", label: "6. Report" },
            { value: "missingOut2", label: "7. Missing Out 2" },
            { value: "missingOut3", label: "8. Missing Out 3" },
            { value: "simulator", label: "9. Simulator" },
            { value: "fundPreview", label: "10. Fund Preview" },
            { value: "bookingConfirm", label: "11. Booking Confirm" },
            { value: "dashboard", label: "12. Dashboard" },
          ]} onChange={setScreen} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Mini phone cards for canvas overview
function CanvasOverview({ theme, setTheme, lang, setLang, accent, accentKey, vizVariant, alloc, setAlloc, goals, setGoals, name, phone, setName, setPhone, consent, setConsent }) {
  const screens = ["landing", "contact", "alloc", "goals", "processing", "report"];
  const labels = { landing: "01. Landing", contact: "02. Contact gate", alloc: "03. Allocation", goals: "04. Goals", processing: "05. Processing", report: "06. Report" };
  // mini state for each
  return (
    <div style={{ width: "100%", maxWidth: 1400, display: "flex", flexDirection: "column", gap: 40 }}>
      <div style={{ display: "flex", gap: 40, flexWrap: "wrap", justifyContent: "center" }}>
        {["dark", "light"].map(th => (
          <div key={th} style={{ display: "flex", flexDirection: "column", gap: 16, alignItems: "center" }}>
            <div style={{ fontFamily: FONTS.ui, fontSize: 11, fontWeight: 700, letterSpacing: 1.5, textTransform: "uppercase",
              color: theme === "dark" ? "#94A3B8" : "#45556C" }}>{th} mode</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 28 }}>
              {screens.map(s => (
                <MiniPhone key={`${th}-${s}`} screen={s} theme={th} accent={accent} lang={lang}
                  alloc={alloc} goals={goals} name={name} phone={phone} consent={consent}
                  vizVariant={vizVariant}
                  label={labels[s]} />
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function MiniPhone({ screen, theme, accent, lang, alloc, goals, name, phone, consent, vizVariant, label }) {
  const W = 280, H = 608;
  const T = THEMES[theme];
  const t = COPY[lang];
  // Use no-op setters; canvas is preview-only
  const noop = () => {};
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10, alignItems: "center" }}>
      <div style={{
        fontFamily: FONTS.ui, fontSize: 10.5, fontWeight: 600, letterSpacing: 1.4, textTransform: "uppercase",
        color: theme === "dark" ? "#94A3B8" : "#45556C",
      }}>{label}</div>
      <div style={{
        width: W, height: H, borderRadius: 40, position: "relative", overflow: "hidden",
        background: T.bg,
        boxShadow: theme === "dark"
          ? "0 30px 60px rgba(0,0,0,0.5), 0 0 0 8px #0a0a0c, 0 0 0 9px rgba(255,255,255,0.06)"
          : "0 30px 60px rgba(11,15,25,0.15), 0 0 0 8px #1a1f2e, 0 0 0 9px rgba(255,255,255,0.08)",
        pointerEvents: "none",
        fontFamily: FONTS.ui,
      }}>
        <div style={{ position: "absolute", top: 8, left: "50%", transform: "translateX(-50%)", width: 88, height: 26, borderRadius: 18, background: "#000", zIndex: 100 }} />
        <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 38, zIndex: 80, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "13px 22px 0" }}>
          <span style={{ fontFamily: '-apple-system, system-ui', fontWeight: 600, fontSize: 11, color: T.text }}>9:41</span>
        </div>
        <div style={{ position: "absolute", top: 38, left: 0, right: 0, bottom: 0, display: "flex", flexDirection: "column", transform: `scale(${W/402})`, transformOrigin: "top left", width: 402, height: (H - 38) / (W / 402) }}>
          <LucyHeader T={T} t={t} lang={lang} setLang={noop} theme={theme} setTheme={noop} accent={accent} showBack={false} step={STEPS[screen]} />
          <div style={{ flex: 1, overflow: "hidden" }}>
            {screen === "landing" && <LandingScreen T={T} t={t} accent={accent} theme={theme} onStart={noop} />}
            {screen === "contact" && <ContactScreen T={T} t={t} accent={accent} theme={theme} name={name || (lang === "vn" ? "Nguyễn Văn A" : "Jane Nguyen")} setName={noop} phone={phone || "+84 901 234 567"} setPhone={noop} consent={consent || true} setConsent={noop} onNext={noop} />}
            {screen === "alloc" && <AllocationScreen T={T} t={t} accent={accent} theme={theme} alloc={alloc} setAlloc={noop} onNext={noop} />}
            {screen === "goals" && <GoalsScreen T={T} t={t} accent={accent} theme={theme} goals={goals.length ? goals : ["growth", "income"]} setGoals={noop} onNext={noop} />}
            {screen === "processing" && <ProcessingFrozen T={T} t={t} accent={accent} theme={theme} />}
            {screen === "report" && <ReportScreen T={T} t={t} accent={accent} theme={theme} name={name || (lang === "vn" ? "Nguyễn Văn A" : "Jane")} alloc={alloc} onRestart={noop} vizVariant={vizVariant} />}
          </div>
        </div>
        <div style={{ position: "absolute", bottom: 6, left: "50%", transform: "translateX(-50%)", width: 96, height: 4, borderRadius: 100, background: theme === "dark" ? "rgba(255,255,255,0.55)" : "rgba(0,0,0,0.32)", zIndex: 90 }} />
      </div>
    </div>
  );
}

// Static processing screen for canvas (no auto-advance)
function ProcessingFrozen({ T, t, accent, theme }) {
  const steps = [t.proc1, t.proc2, t.proc3, t.proc4];
  return (
    <div style={{ position: "relative", minHeight: "100%", padding: "20px 22px 100px" }}>
      <AmbientBg T={T} accent={accent} theme={theme} />
      <div style={{ position: "relative", zIndex: 1, display: "flex", flexDirection: "column", alignItems: "center", paddingTop: 24 }}>
        <Kicker T={T} accent={accent}>{t.procKicker}</Kicker>
        <div style={{ height: 16 }} />
        <LucyOrb size={150} accent={accent} theme={theme} processing />
        <div style={{ height: 24 }} />
        <SerifTitle T={T} size={38}>{t.procTitle}</SerifTitle>
        <div style={{ height: 10 }} />
        <Body T={T} size={13} style={{ textAlign: "center" }}>{t.procSub}</Body>
        <div style={{ height: 36 }} />
        <div style={{ width: "100%" }}>
          {steps.map((s, i) => (
            <div key={i} style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: "16px 14px",
              borderTop: `1px solid ${T.border}`,
              opacity: i <= 1 ? 1 : 0.45,
              ...(i === steps.length - 1 ? { borderBottom: `1px solid ${T.border}` } : {}),
            }}>
              <div style={{
                width: 24, height: 24, borderRadius: "50%",
                border: `1.5px solid ${i <= 1 ? accent.primary : T.borderStrong}`,
                background: i < 1 ? accent.primary : "transparent",
                display: "flex", alignItems: "center", justifyContent: "center",
                flexShrink: 0,
              }}>
                {i < 1 && <svg width="11" height="11" viewBox="0 0 11 11"><path d="M2 5.5L4.5 8L9 3" stroke="#0B0F19" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                {i === 1 && <div style={{ width: 8, height: 8, borderRadius: "50%", background: accent.primary }} />}
              </div>
              <span style={{ flex: 1, fontFamily: FONTS.ui, fontSize: 13.5, color: T.text, fontWeight: i === 1 ? 600 : 400 }}>{s}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

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