/* screen-onboarding.jsx — first-run welcome + quick company setup → window.QScreens.Onboarding */
(function () {
  const { useState } = React;
  const Q = window.Q, Icons = window.Icons;

  /* Directional step slide: replaces the plain cross-fade between the intro
     and profile steps so "next" reads as forward motion (content enters from
     the right, like the app's iOS push) and "back" reverses it. Injected once;
     the index.html prefers-reduced-motion media query collapses it to instant. */
  if (typeof document !== "undefined" && !document.getElementById("q-ob-anim")) {
    const s = document.createElement("style");
    s.id = "q-ob-anim";
    s.textContent =
      "@keyframes q-ob-fwd { from { opacity: 0; transform: translateX(22px); } to { opacity: 1; transform: none; } }" +
      "@keyframes q-ob-back { from { opacity: 0; transform: translateX(-22px); } to { opacity: 1; transform: none; } }" +
      ".q-ob-fwd { animation: q-ob-fwd .34s cubic-bezier(.32,.72,0,1) both; }" +
      ".q-ob-back { animation: q-ob-back .34s cubic-bezier(.32,.72,0,1) both; }";
    document.head.appendChild(s);
  }
  const { Icon, NitaMark } = Icons;
  const { Button, Field, Input, Select, Segmented, Kicker, Sparkle } = Q;
  const t = window.t;

  function Bullet({ icon, title, body }) {
    return (
      <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
        <div style={{ width: 40, height: 40, borderRadius: 11, background: "var(--color-primary-muted)", color: "var(--color-primary)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <Icon name={icon} size={19} />
        </div>
        <div>
          <div style={{ fontSize: 15, fontWeight: 600, color: "var(--color-text-1)" }}>{title}</div>
          <div style={{ fontSize: 13.5, color: "var(--color-text-2)", lineHeight: 1.45, marginTop: 2 }}>{body}</div>
        </div>
      </div>
    );
  }

  /* ── First-run choice (tester builds) ──────────────────────────
     Rendered by App before anything else when tester mode is on and no
     saved db / stored nita_mode exists: demo tour vs. clean setup.
     q-stagger gives the q-fade-up entrance; the global
     prefers-reduced-motion rule in index.html collapses it to instant. */
  function ChoiceCard({ icon, title, sub, primary, onClick }) {
    const [pressed, setPressed] = useState(false);
    const release = () => setPressed(false);
    return (
      <button onClick={onClick} className="q-tap"
        onPointerDown={() => setPressed(true)}
        onPointerUp={release} onPointerLeave={release} onPointerCancel={release}
        style={{
        display: "flex", alignItems: "flex-start", gap: 14, textAlign: "left",
        width: "100%", padding: "18px 16px", borderRadius: 18, cursor: "pointer",
        border: primary ? "1.4px solid var(--color-primary)" : "1.4px solid var(--color-border-strong)",
        background: "var(--color-surface-0)",
        boxShadow: pressed ? "var(--elev-1)" : "var(--elev-2)",
        color: "var(--color-text-1)", font: "inherit",
        transform: pressed ? "translateY(1px) scale(0.985)" : "none",
        transition: "transform .2s var(--spring), box-shadow .2s var(--spring)",
      }}>{/* q-tap layers a tap-highlight reset; the pressed state adds a
            cause→effect depth dip (lift on rest, settle on press) — this is
            the first physical tap a new user makes. reduced-motion zeroes
            the transition globally; the resting elevation still reads. */}
        <div style={{
          width: 44, height: 44, borderRadius: 13, flexShrink: 0,
          display: "flex", alignItems: "center", justifyContent: "center",
          background: primary ? "var(--color-primary)" : "var(--color-primary-muted)",
          color: primary ? "var(--color-primary-fg)" : "var(--color-primary)",
        }}>
          <Icon name={icon} size={20} />
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 650, letterSpacing: "-0.01em", lineHeight: 1.25 }}>{title}</div>
          <div style={{ fontSize: 13.5, color: "var(--color-text-2)", lineHeight: 1.45, marginTop: 4 }}>{sub}</div>
        </div>
      </button>
    );
  }

  function FirstRun({ onChoose }) {
    return (
      <div style={{ height: "100%", display: "flex", flexDirection: "column", background: "var(--color-bg)", overflowY: "auto", padding: "0 28px" }}>
        <div className="q-stagger" style={{ flex: 1, display: "flex", flexDirection: "column", minHeight: "100%" }}>
          <div style={{ paddingTop: Q.SAFE_TOP + 44, display: "flex", alignItems: "center", gap: 12 }}>
            <NitaMark size={44} />
            <div style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 27, letterSpacing: "-0.01em", color: "var(--color-text-1)" }}>{t("brand.name")}</div>
          </div>
          <Kicker style={{ marginTop: 44, color: "var(--color-primary)" }}>{t("firstrun.kicker")}</Kicker>
          <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 34, lineHeight: 1.12, letterSpacing: "-0.02em", color: "var(--color-text-1)", margin: "12px 0 0" }}>{t("firstrun.title")}</h1>
          <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 30 }}>
            <ChoiceCard primary icon="sparkle"
              title={t("firstrun.demo.title")} sub={t("firstrun.demo.sub")}
              onClick={() => onChoose("demo")} />
            <ChoiceCard icon="briefcase"
              title={t("firstrun.fresh.title")} sub={t("firstrun.fresh.sub")}
              onClick={() => onChoose("fresh")} />
          </div>
          <div style={{ flex: 1, minHeight: 24 }} />
          <div style={{ padding: "0 0 34px", fontSize: 12.5, color: "var(--color-text-3)", lineHeight: 1.45, textAlign: "center" }}>{t("firstrun.note")}</div>
        </div>
      </div>
    );
  }

  function Onboarding({ api, onFinish }) {
    const { useRef, useEffect } = React;
    const [step, setStep] = useState(0);
    /* Track which way the user moved so the step container animates
       directionally (forward on "continue", back on the chevron). */
    const [dir, setDir] = useState("fwd");
    /* Scroll cue for the intro step: on short viewports the three value
       props (and the CTA) fall below the fold with no hint that there's
       more. Track "is there more below" and paint a bottom fade + chevron
       while the user hasn't reached the end. The fade lives behind the CTA
       block so it only suggests "scroll", never hides the button. */
    const introRef = useRef(null);
    const [moreBelow, setMoreBelow] = useState(false);
    const checkScroll = () => {
      const el = introRef.current;
      if (!el) { setMoreBelow(false); return; }
      setMoreBelow(el.scrollHeight - el.clientHeight - el.scrollTop > 12);
    };
    useEffect(() => {
      if (step !== 0) { setMoreBelow(false); return; }
      checkScroll();
      const el = introRef.current;
      if (!el || typeof ResizeObserver === "undefined") return;
      const ro = new ResizeObserver(checkScroll);
      ro.observe(el);
      return () => ro.disconnect();
    }, [step]);
    const go = (n) => { setDir(n > step ? "fwd" : "back"); setStep(n); };
    const [owner, setOwner] = useState("");
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const [currency, setCurrency] = useState(api.db.COMPANY.currency);
    const [biztype, setBiztype] = useState(api.db.COMPANY.businessType || "both");
    const curOpts = Object.values(window.CURRENCIES).map(c => ({ value: c.code, label: `${c.code} · ${c.name}` }));
    /* Build the profile the same way whether the user finishes or skips, so
       "Skip for now" still keeps the currency + business-type they picked
       (and a name they typed) — only the explicit text fields are optional.
       owner → COMPANY.owner drives the personalized Home greeting. */
    const buildProfile = () => {
      const profile = { currency, businessType: biztype };
      if (owner.trim()) profile.owner = owner.trim();
      if (name.trim()) profile.name = name.trim();
      if (email.trim()) profile.email = email.trim();
      return profile;
    };
    const finish = () => onFinish(buildProfile());
    const skip = () => onFinish(buildProfile());

    return (
      <div style={{ height: "100%", display: "flex", flexDirection: "column", background: "var(--color-bg)", overflow: "hidden" }}>
        {step === 0 ? (
          <div key="intro" className={dir === "back" ? "q-ob-back" : "q-ob-fwd"} style={{ flex: 1, position: "relative", minHeight: 0, display: "flex", flexDirection: "column" }}>
          <div ref={introRef} onScroll={checkScroll} style={{ flex: 1, display: "flex", flexDirection: "column", padding: "0 28px", overflowY: "auto" }}>
            <div style={{ paddingTop: Q.SAFE_TOP + 36 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <NitaMark size={44} />
                <div style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 27, letterSpacing: "-0.01em", color: "var(--color-text-1)" }}>{t("brand.name")}</div>
              </div>
              <Kicker style={{ marginTop: 40, color: "var(--color-primary)" }}>{t("ob.kicker")}</Kicker>
              <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 38, lineHeight: 1.08, letterSpacing: "-0.025em", color: "var(--color-text-1)", margin: "12px 0 0", whiteSpace: "pre-line" }}>{t("ob.title")}</h1>
              <p style={{ fontSize: 15.5, color: "var(--color-text-2)", lineHeight: 1.5, marginTop: 16 }}>{t("ob.body")}</p>
            </div>

            {/* faux AI demo chip */}
            <div className="q-ai-materialize" style={{ marginTop: 28, border: "1.4px solid var(--color-primary)", borderRadius: 16, background: "var(--color-surface-0)", padding: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 10 }}>
                <Sparkle size={13} />
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--color-primary)" }}>{t("brand.name")}</span>
              </div>
              <div style={{ fontSize: 14, color: "var(--color-text-2)", fontStyle: "normal", lineHeight: 1.45 }}>
                &ldquo;{t("ob.sample.prompt")}&rdquo;
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 12, color: "var(--color-primary)", fontSize: 13, fontWeight: 600 }}>
                <Icon name="arrowRight" size={15} />
                <span>{t("ob.sample.result")}</span>
              </div>
            </div>

            {/* q-stagger cascades the three value props ~40ms apart so they
                land one at a time under the AI chip — classic onboarding rhythm
                (collapses to instant under prefers-reduced-motion). */}
            <div className="q-stagger" style={{ display: "flex", flexDirection: "column", gap: 20, marginTop: 30 }}>
              <Bullet icon="sparkle" title={t("ob.b1.title")} body={t("ob.b1.body")} />
              <Bullet icon="edit" title={t("ob.b2.title")} body={t("ob.b2.body")} />
              <Bullet icon="send" title={t("ob.b3.title")} body={t("ob.b3.body")} />
            </div>

            <div style={{ flex: 1 }} />
            <div style={{ padding: "24px 0 34px" }}>
              <Button variant="primary" size="lg" full onClick={() => go(1)}>{t("ob.cta")}</Button>
            </div>
          </div>
          {/* Bottom scroll cue: a soft fade + chevron, shown only while there
              is more content below the fold. Pointer-events:none so it never
              eats taps; opacity-only transition keeps it calm. */}
          <div aria-hidden="true" style={{
            position: "absolute", left: 0, right: 0, bottom: 0, height: 56,
            pointerEvents: "none",
            display: "flex", alignItems: "flex-end", justifyContent: "center", paddingBottom: 8,
            background: "linear-gradient(180deg, transparent, var(--color-bg) 78%)",
            color: "var(--color-text-3)",
            opacity: moreBelow ? 1 : 0,
            transition: "opacity .22s ease-out",
          }}>
            <Icon name="chevronDown" size={20} />
          </div>
          </div>
        ) : (
          <div key="profile" className={dir === "back" ? "q-ob-back" : "q-ob-fwd"} style={{ flex: 1, display: "flex", flexDirection: "column", padding: "0 28px", overflowY: "auto" }}>
            <div style={{ paddingTop: Q.SAFE_TOP + 24 }}>
              <button onClick={() => go(0)} className="q-tap" style={{ background: "none", border: "none", color: "var(--color-text-2)", display: "flex", alignItems: "center", gap: 4, cursor: "pointer", padding: "11px 10px", margin: "-11px -10px", fontSize: 14, marginBottom: 7 }}>
                <Icon name="chevronLeft" size={18} /> {t("g.back")}
              </button>
              <Kicker style={{ color: "var(--color-primary)" }}>{t("ob.profile.kicker")}</Kicker>
              <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 32, letterSpacing: "-0.02em", color: "var(--color-text-1)", margin: "10px 0 0" }}>{t("ob.profile.title")}</h1>
              <p style={{ fontSize: 14.5, color: "var(--color-text-2)", lineHeight: 1.5, marginTop: 10 }}>{t("ob.profile.body")}</p>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 16, marginTop: 26 }}>
              {/* Logo upload is a later-build feature. Render it as a plainly
                informational placeholder — no action word ("Upload"), no
                button affordance — so it reads as "Logo · optional, add it
                in Settings" rather than a broken dropzone control. The
                "change anytime in Settings" context lives in ob.profile.body
                above. cursor:default + userSelect:none keep it inert. */}
            <div style={{ display: "flex", alignItems: "center", gap: 14, cursor: "default", userSelect: "none" }}>
                <div style={{ width: 60, height: 60, borderRadius: 16, border: "1.4px dashed var(--color-border-strong)", background: "var(--color-surface-1)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-text-3)", flexShrink: 0 }}>
                  <Icon name="image" size={22} />
                </div>
                <div style={{ fontSize: 13, color: "var(--color-text-3)", lineHeight: 1.4 }}>{t("set.logo")} <span style={{ opacity: 0.85 }}>({t("g.optional")})</span></div>
              </div>
              <Field label={t("ob.profile.owner")}><Input value={owner} onChange={e => setOwner(e.target.value)} placeholder={t("ob.profile.owner.ph")} /></Field>
              <Field label={t("ob.profile.name")}><Input value={name} onChange={e => setName(e.target.value)} placeholder={t("ob.profile.name.ph")} /></Field>
              <Field label={t("ob.profile.email")}><Input value={email} onChange={e => setEmail(e.target.value)} type="email" placeholder={t("ob.profile.email.ph")} /></Field>
              <Field label={t("ob.profile.currency")}><Select value={currency} onChange={e => setCurrency(e.target.value)} options={curOpts} /></Field>
              <Field label={t("ob.profile.biztype")} hint={t("ob.biz." + biztype + ".sub")}>
                <Segmented value={biztype} onChange={setBiztype} options={[
                  { value: "services", label: t("biz.services") },
                  { value: "products", label: t("biz.products") },
                  { value: "both", label: t("biz.both") },
                ]} />
              </Field>
            </div>

            <div style={{ flex: 1, minHeight: 20 }} />
            <div style={{ padding: "20px 0 34px", display: "flex", flexDirection: "column", gap: 10 }}>
              <Button variant="primary" size="lg" full onClick={finish}>{t("ob.profile.finish")}</Button>
              <Button variant="ghost" size="md" full onClick={skip}>{t("ob.profile.skip")}</Button>
            </div>
          </div>
        )}
      </div>
    );
  }

  window.QScreens = Object.assign(window.QScreens || {}, { Onboarding, FirstRun });
})();
