// Onboarding flow

const ONBOARDING_ASSETS = {
  hound: "src/assets/hound-video.mp4",
  vault: "src/assets/vault-video.mp4",
  card: "src/assets/card-video.mp4",
  stocks: "src/assets/stocks-video.mp4",
  will: "src/assets/will-video.mp4",
};

const ONBOARDING_EASE = "260ms cubic-bezier(.18,.9,.22,1)";

const ONBOARDING_SLIDES = [
  {
    key: "wealth",
    title: "Unite your finances",
    body: "Bring banks, brokerages, crypto, property and debts into one clean financial picture.",
    src: ONBOARDING_ASSETS.vault,
  },
  {
    key: "spend",
    title: "See the patterns",
    body: "Catch spending drift, benchmark against similar households, and spot rewards you are leaving unused.",
    src: ONBOARDING_ASSETS.card,
  },
  {
    key: "growth",
    title: "Put money to work",
    body: "Track portfolios, idle cash, and opportunities with context that fits your life in the UAE.",
    src: ONBOARDING_ASSETS.stocks,
  },
  {
    key: "plan",
    title: "Plan your financial life",
    body: "Model goals, estate planning, insurance gaps, and future obligations before they become urgent.",
    src: ONBOARDING_ASSETS.will,
  },
];

const PASSWORD_RULES = [
  { key: "upper", label: "Uppercase letter", test: (v) => /[A-Z]/.test(v) },
  { key: "lower", label: "Lowercase letter", test: (v) => /[a-z]/.test(v) },
  { key: "number", label: "Number", test: (v) => /[0-9]/.test(v) },
  {
    key: "length",
    label: "8 to 64 characters",
    test: (v) => v.length >= 8 && v.length <= 64,
  },
  {
    key: "special",
    label: "Special character",
    test: (v) => /[^A-Za-z0-9]/.test(v),
  },
];

const ONBOARDING_GOALS = [
  {
    id: "spending",
    icon: "wallet",
    title: "Manage my spending",
    body: "Budgets, recurring costs, rewards and comparisons.",
    features: [
      "Spending pattern detection",
      "Peer benchmarks",
      "Card reward prompts",
    ],
  },
  {
    id: "portfolio",
    icon: "lineChart",
    title: "Track my portfolio",
    body: "Brokerage, crypto and allocation visibility.",
    features: [
      "Holdings across accounts",
      "Daily movement explainers",
      "Portfolio risk summaries",
    ],
  },
  {
    id: "wealth",
    icon: "chart",
    title: "Grow my wealth",
    body: "Idle cash, opportunities and long-term direction.",
    features: [
      "Idle cash alerts",
      "Savings opportunity scans",
      "Monthly growth notes",
    ],
  },
  {
    id: "planning",
    icon: "umbrella",
    title: "Plan for the future",
    body: "Retirement, insurance, estate and liquidity planning.",
    features: [
      "Life planning checklist",
      "Insurance gap review",
      "Estate planning reminders",
    ],
  },
  {
    id: "debt",
    icon: "target",
    title: "Pay down debt",
    body: "Mortgages, cards and payoff strategy.",
    features: [
      "APR-aware payoff order",
      "Monthly payment guidance",
      "Progress tracking",
    ],
  },
];

function OnboardingFlow({ theme, accent, onComplete, onConnectAccounts }) {
  const [step, setStep] = React.useState(0);
  const [direction, setDirection] = React.useState(1);
  const [slide, setSlide] = React.useState(0);
  const [email, setEmail] = React.useState("");
  const [authMethod, setAuthMethod] = React.useState("email");
  const [password, setPassword] = React.useState("");
  const [showPassword, setShowPassword] = React.useState(false);
  const [name, setName] = React.useState("");
  const [showFacePrompt, setShowFacePrompt] = React.useState(false);
  const [showNotifySheet, setShowNotifySheet] = React.useState(true);
  const [showPushPrompt, setShowPushPrompt] = React.useState(false);
  const [goal, setGoal] = React.useState(null);

  React.useEffect(() => {
    if (step !== 0) return undefined;
    const timer = window.setTimeout(() => goTo(1), 2500);
    return () => window.clearTimeout(timer);
  }, [step]);

  const goTo = (nextStep) => {
    setDirection(nextStep > step ? 1 : -1);
    setStep(nextStep);
  };

  const next = () => goTo(Math.min(8, step + 1));

  const completeToHome = () => {
    if (onComplete) onComplete();
  };

  const connectAccounts = () => {
    if (onConnectAccounts) onConnectAccounts({ goal });
    else completeToHome();
  };

  const screenProps = {
    theme,
    accent,
    direction,
    step,
    next,
    goTo,
    completeToHome,
  };

  if (step === 8) {
    return (
      <DashboardActivationStep
        theme={theme}
        accent={accent}
        selectedGoal={goal}
        onConnectAccounts={connectAccounts}
        onNav={() => {}}
      />
    );
  }

  return (
    <div
      style={{
        height: "100%",
        background: theme.bg,
        color: theme.text,
        position: "relative",
        overflow: "hidden",
      }}
    >
      <OnboardingFrameKeyframes />
      <AnimatedStep step={step} direction={direction}>
        {step === 0 && <SplashStep theme={theme} accent={accent} />}
        {step === 1 && (
          <ValueCarouselStep
            {...screenProps}
            slide={slide}
            setSlide={setSlide}
            onSignIn={completeToHome}
            onSignUp={next}
          />
        )}
        {step === 2 && (
          <AuthSelectionStep
            {...screenProps}
            email={email}
            setEmail={setEmail}
            onGoogle={() => {
              setAuthMethod("google");
              goTo(4);
            }}
            onEmail={() => {
              setAuthMethod("email");
              next();
            }}
          />
        )}
        {step === 3 && (
          <PasswordStep
            {...screenProps}
            password={password}
            setPassword={setPassword}
            showPassword={showPassword}
            setShowPassword={setShowPassword}
          />
        )}
        {step === 4 && (
          <LegalNameStep
            {...screenProps}
            name={name}
            setName={setName}
            authMethod={authMethod}
          />
        )}
        {step === 5 && (
          <BiometricStep
            {...screenProps}
            showFacePrompt={showFacePrompt}
            setShowFacePrompt={setShowFacePrompt}
          />
        )}
        {step === 6 && <TrialPaywallStep {...screenProps} />}
        {step === 7 && (
          <GoalSelectionStep
            {...screenProps}
            goal={goal}
            setGoal={setGoal}
            showNotifySheet={showNotifySheet}
            setShowNotifySheet={setShowNotifySheet}
            showPushPrompt={showPushPrompt}
            setShowPushPrompt={setShowPushPrompt}
          />
        )}
      </AnimatedStep>
    </div>
  );
}

function OnboardingFrameKeyframes() {
  return (
    <style>{`
      @keyframes himma-onb-enter-forward {
        from { opacity: 0; transform: translateX(18px) scale(.992); }
        to { opacity: 1; transform: translateX(0) scale(1); }
      }
      @keyframes himma-onb-enter-back {
        from { opacity: 0; transform: translateX(-18px) scale(.992); }
        to { opacity: 1; transform: translateX(0) scale(1); }
      }
      @keyframes himma-onb-sheet {
        from { opacity: 0; transform: translateY(22px); }
        to { opacity: 1; transform: translateY(0); }
      }
      @keyframes himma-onb-fade {
        from { opacity: 0; }
        to { opacity: 1; }
      }
    `}</style>
  );
}

function AnimatedStep({ children, step, direction }) {
  return (
    <div
      key={step}
      style={{
        height: "100%",
        animation: `${direction >= 0 ? "himma-onb-enter-forward" : "himma-onb-enter-back"} ${ONBOARDING_EASE}`,
      }}
    >
      {children}
    </div>
  );
}

function SplashStep({ theme, accent }) {
  return (
    <div
      style={{
        height: "100%",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        background: "#FFFFFF",
      }}
    >
      <div
        style={{
          width: 172,
          height: 172,
          borderRadius: 100,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          clipPath:
            "path('M0,86 C0,12 12,0 86,0 C160,0 172,12 172,86 C172,160 160,172 86,172 C12,172 0,160 0,86')",
          overflow: "hidden",
        }}
      >
        <video
          src={ONBOARDING_ASSETS.hound}
          autoPlay
          muted
          loop
          playsInline
          preload="auto"
          style={{
            width: "86%",
            height: "86%",
            objectFit: "contain",
            display: "block",
          }}
        />
      </div>
      <div style={{ marginTop: 24 }}>
        <Wordmark color={theme.text} accent={accent} size={24} />
      </div>
    </div>
  );
}

function ValueCarouselStep({
  theme,
  accent,
  slide,
  setSlide,
  onSignIn,
  onSignUp,
}) {
  const touchStart = React.useRef(null);
  const current = ONBOARDING_SLIDES[slide];

  const moveSlide = (delta) => {
    setSlide((value) =>
      Math.max(0, Math.min(ONBOARDING_SLIDES.length - 1, value + delta)),
    );
  };

  const onTouchEnd = (event) => {
    if (touchStart.current == null) return;
    const dx = event.changedTouches[0].clientX - touchStart.current;
    touchStart.current = null;
    if (Math.abs(dx) < 36) return;
    moveSlide(dx < 0 ? 1 : -1);
  };

  return (
    <div
      style={{
        height: "100%",
        position: "relative",
        background: "#FFFFFF",
        color: theme.text,
        overflow: "hidden",
      }}
      onTouchStart={(event) => {
        touchStart.current = event.touches[0].clientX;
      }}
      onTouchEnd={onTouchEnd}
    >
      <div
        style={{
          position: "absolute",
          top: 14,
          left: 20,
          right: 20,
          zIndex: 4,
          display: "flex",
          justifyContent: "center",
        }}
      >
        <Wordmark color={theme.text} accent={accent} size={18} />
      </div>

      <div
        style={{
          position: "relative",
          zIndex: 2,
          height: "100%",
          padding: "76px 20px 130px",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <div
          style={{
            textAlign: "center",
            width: "100%",
          }}
        >
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 45,
              lineHeight: 1.02,
              letterSpacing: 0,
              color: theme.text,
              fontWeight: 500,
              maxWidth: 280,
              margin: "0 auto",
            }}
          >
            {current.title}
          </div>
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 14,
              lineHeight: 1.45,
              color: theme.textDim,
              margin: "14px auto 0",
              maxWidth: 310,
            }}
          >
            {current.body}
          </div>
        </div>

        <div
          style={{
            position: "relative",
            width: "calc(100% + 40px)",
            flex: 1,
            minHeight: 250,
            marginTop: 30,
            overflow: "hidden",
          }}
        >
          {ONBOARDING_SLIDES.map((item, index) => (
            <div
              key={item.key}
              style={{
                position: "absolute",
                inset: 0,
                transform: `translateX(${(index - slide) * 100}%)`,
                transition: `transform ${ONBOARDING_EASE}`,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <OnboardingVideo src={item.src} active={index === slide} />
            </div>
          ))}
        </div>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 6,
            justifyContent: "center",
            marginTop: 12,
          }}
        >
          {ONBOARDING_SLIDES.map((item, index) => (
            <button
              key={item.key}
              onClick={() => setSlide(index)}
              aria-label={`Go to slide ${index + 1}`}
              style={{
                width: 6,
                height: 6,
                borderRadius: 999,
                border: "none",
                background: index === slide ? theme.text : theme.line2,
                transition: "background 160ms",
                cursor: "pointer",
                padding: 0,
              }}
            />
          ))}
        </div>
      </div>

      <div
        style={{
          position: "absolute",
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 3,
          padding: "14px 20px 34px",
          background: `linear-gradient(to top, #FFFFFF 72%, #FFFFFF00)`,
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 8,
        }}
      >
        <button
          onClick={onSignIn}
          style={{
            ...onboardingButtonStyle({
              bg: "transparent",
              color: theme.text,
              border: theme.text,
            }),
          }}
        >
          SIGN IN
        </button>
        <button
          onClick={onSignUp}
          style={onboardingButtonStyle({
            bg: theme.text,
            color: "#FFFFFF",
            border: theme.text,
          })}
        >
          SIGN UP
        </button>
      </div>

      <button
        onClick={() => moveSlide(-1)}
        aria-label="Previous slide"
        disabled={slide === 0}
        style={carouselArrowStyle("left", slide === 0)}
      >
        <Ico.chevL size={16} />
      </button>
      <button
        onClick={() => moveSlide(1)}
        aria-label="Next slide"
        disabled={slide === ONBOARDING_SLIDES.length - 1}
        style={carouselArrowStyle(
          "right",
          slide === ONBOARDING_SLIDES.length - 1,
        )}
      >
        <Ico.chevR size={16} />
      </button>
    </div>
  );
}

function OnboardingVideo({ src, active }) {
  const ref = React.useRef(null);

  React.useEffect(() => {
    const video = ref.current;
    if (!video) return;
    if (active) {
      video.play().catch(() => {});
    } else {
      video.pause();
    }
  }, [active, src]);

  return (
    <video
      ref={ref}
      src={src}
      muted
      loop
      playsInline
      preload={active ? "auto" : "metadata"}
      style={{
        width: "100%",
        height: "100%",
        objectFit: "contain",
        display: "block",
      }}
    />
  );
}

function AuthSelectionStep({
  theme,
  accent,
  email,
  setEmail,
  onGoogle,
  onEmail,
}) {
  const validEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());

  return (
    <OnboardingShell
      theme={theme}
      accent={accent}
      title="Let's get started"
      footer={
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 12,
            lineHeight: 1.45,
            fontWeight: 400,
            color: theme.textMute,
            textAlign: "center",
          }}
        >
          By creating an account, you agree to our{" "}
          <span style={{ textDecoration: "underline" }}>Terms of Service</span>{" "}
          and{" "}
          <span style={{ textDecoration: "underline" }}>Privacy Policy</span>.
        </div>
      }
    >
      <button
        onClick={onGoogle}
        style={{
          width: "100%",
          height: 52,
          borderRadius: 16,
          border: `0.5px solid ${theme.line2}`,
          background: theme.surface,
          color: theme.text,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 10,
          fontFamily: FONTS.ui,
          fontSize: 14,
          fontWeight: 400,
          cursor: "pointer",
        }}
      >
        Continue with Google
        <span
          style={{
            width: 22,
            height: 22,
            borderRadius: 11,
            background: theme.surface2,
            color: accent,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontWeight: 800,
          }}
        >
          G
        </span>
      </button>

      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 12,
          margin: "22px 0",
        }}
      >
        <div style={{ height: 1, flex: 1, background: theme.line }} />
        <span
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            color: theme.textMute,
            letterSpacing: 1,
            textTransform: "uppercase",
          }}
        >
          or sign up with email
        </span>
        <div style={{ height: 1, flex: 1, background: theme.line }} />
      </div>

      <OnboardingInput
        theme={theme}
        label="Email"
        value={email}
        onChange={setEmail}
        placeholder="carol@example.com"
        type="email"
        autoFocus
      />

      <button
        disabled={!validEmail}
        onClick={onEmail}
        style={{
          ...primaryActionStyle(theme, accent, validEmail),
          marginTop: 12,
        }}
      >
        SIGN UP
      </button>
    </OnboardingShell>
  );
}

function PasswordStep({
  theme,
  accent,
  password,
  setPassword,
  showPassword,
  setShowPassword,
  next,
}) {
  const started = password.length > 0;
  const statuses = PASSWORD_RULES.map((rule) => ({
    ...rule,
    valid: rule.test(password),
  }));
  const valid = statuses.every((rule) => rule.valid);

  return (
    <OnboardingShell
      theme={theme}
      accent={accent}
      title="Create a password"
      footer={
        <button
          disabled={!valid}
          onClick={next}
          style={primaryActionStyle(theme, accent, valid)}
        >
          NEXT
        </button>
      }
    >
      <div style={{ position: "relative" }}>
        <OnboardingInput
          theme={theme}
          label="Password"
          value={password}
          onChange={setPassword}
          placeholder="Enter a secure password"
          type={showPassword ? "text" : "password"}
          autoFocus
          style={{ paddingRight: 48 }}
        />
        <button
          onClick={() => setShowPassword(!showPassword)}
          aria-label={showPassword ? "Hide password" : "Show password"}
          style={{
            position: "absolute",
            right: 8,
            bottom: 7,
            width: 38,
            height: 38,
            borderRadius: 13,
            border: "none",
            background: "transparent",
            color: theme.textDim,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            cursor: "pointer",
          }}
        >
          <Ico.eye size={17} />
        </button>
      </div>

      <div
        style={{
          marginTop: 18,
          display: "flex",
          flexDirection: "column",
          gap: 10,
        }}
      >
        {statuses.map((rule) => {
          const color = !started
            ? theme.textMute
            : rule.valid
              ? theme.positive
              : theme.negative;
          return (
            <div
              key={rule.key}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 10,
                color,
                fontFamily: FONTS.ui,
                fontSize: 13,
              }}
            >
              <div
                style={{
                  width: 18,
                  height: 18,
                  borderRadius: 9,
                  border: `0.5px solid ${!started ? theme.line2 : color}`,
                  background:
                    started && rule.valid
                      ? `${theme.positive}14`
                      : "transparent",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  flexShrink: 0,
                }}
              >
                {started && rule.valid ? (
                  <Ico.check size={11} stroke={theme.positive} sw={2.2} />
                ) : started ? (
                  <Ico.close size={9} stroke={theme.negative} sw={2.2} />
                ) : null}
              </div>
              <span>{rule.label}</span>
            </div>
          );
        })}
      </div>
    </OnboardingShell>
  );
}

function LegalNameStep({ theme, accent, name, setName, authMethod, next }) {
  const valid = name.trim().length >= 2;

  return (
    <OnboardingShell
      theme={theme}
      accent={accent}
      title="What's your legal name?"
      footer={
        <button
          disabled={!valid}
          onClick={next}
          style={primaryActionStyle(theme, accent, valid)}
        >
          NEXT
        </button>
      }
    >
      <OnboardingInput
        theme={theme}
        label="Legal name"
        value={name}
        onChange={setName}
        placeholder="e.g. Carol Smith"
        autoFocus
      />
    </OnboardingShell>
  );
}

function BiometricStep({
  theme,
  accent,
  next,
  showFacePrompt,
  setShowFacePrompt,
}) {
  const finishChoice = () => {
    setShowFacePrompt(false);
    next();
  };

  return (
    <OnboardingShell
      theme={theme}
      accent={accent}
      center
      title="Want to use Face ID?"
      footer={
        <>
          <button
            onClick={() => setShowFacePrompt(true)}
            style={primaryActionStyle(theme, accent, true)}
          >
            YES
          </button>
          <button
            onClick={next}
            style={{ ...secondaryActionStyle(theme), marginTop: 10 }}
          >
            NO
          </button>
        </>
      }
    >
      <div
        style={{ display: "flex", justifyContent: "center", paddingTop: 38 }}
      >
        <FaceIdMark theme={theme} accent={accent} />
      </div>
      <div
        style={{
          textAlign: "center",
          margin: "24px auto 0",
          maxWidth: 276,
          color: theme.textDim,
          fontFamily: FONTS.ui,
          fontSize: 14,
          lineHeight: 1.55,
        }}
      >
        Set up Face ID to quickly and securely log in.
      </div>

      {showFacePrompt && (
        <SystemPrompt
          theme={theme}
          title="Allow Himma to use Face ID?"
          body="Face ID keeps your financial view protected on this device."
          primary="Allow"
          secondary="Not Now"
          onPrimary={finishChoice}
          onSecondary={finishChoice}
        />
      )}
    </OnboardingShell>
  );
}

function TrialPaywallStep({ theme, accent, next }) {
  const dates = getTrialDates();
  const rows = [
    {
      label: "Today",
      title: "Get instant access",
      body: "Unlock Himma's powerful tools.",
      icon: "check",
      active: true,
    },
    {
      label: dates.reminder,
      title: "Trial reminder",
      body: "We'll remind you before the first paid month begins.",
      icon: "bell",
    },
    {
      label: dates.billing,
      title: "Become a member",
      body: "Your subscription starts. Cancel anytime in settings.",
      icon: "target",
    },
  ];

  return (
    <OnboardingShell
      theme={theme}
      accent={accent}
      title="Start with one week free."
      topAction={
        <button
          onClick={next}
          style={{ ...skipButtonStyle(theme), textDecoration: "underline" }}
        >
          SKIP
        </button>
      }
      footer={
        <button onClick={next} style={primaryActionStyle(theme, accent, true)}>
          Subscribe with Apple Pay
        </button>
      }
    >
      <div style={{ marginTop: 24 }}>
        <div
          style={{
            marginTop: 14,
            position: "relative",
            padding: "15px 10px",
            borderRadius: 10,
            background: `linear-gradient(155deg, #F2F2F2 0%, #eff0f4 90%)`,
          }}
        >
          {rows.map((row, index) => (
            <TimelineRow
              key={row.label}
              theme={theme}
              accent={accent}
              row={row}
              last={index === rows.length - 1}
            />
          ))}
        </div>
      </div>

      <div
        style={{
          marginTop: 28,
          textAlign: "center",
          fontFamily: FONTS.ui,
          color: theme.text,
        }}
      >
        <div
          style={{
            fontSize: 16,
            lineHeight: 1.25,
            fontWeight: 600,
          }}
        >
          Enjoy one month free, then <Dh /> 48 per month.
        </div>
        <div
          style={{
            marginTop: 8,
            fontSize: 12,
            lineHeight: 1.35,
            color: theme.textDim,
          }}
        >
          or <Dh /> 480, billed annually (save <Dh /> 96)
        </div>
      </div>

      <div
        style={{
          marginTop: 24,
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 10,
        }}
      >
        <PaywallMiniCard
          theme={theme}
          accent={accent}
          icon="sparkles"
          title="Unlimited AI"
        />
        <PaywallMiniCard
          theme={theme}
          accent={accent}
          icon="wallet"
          title="All accounts"
        />
        <PaywallMiniCard
          theme={theme}
          accent={accent}
          icon="chart"
          title="Portfolio context"
        />
        <PaywallMiniCard
          theme={theme}
          accent={accent}
          icon="shield"
          title="Priority support"
        />
      </div>
    </OnboardingShell>
  );
}

function GoalSelectionStep({
  theme,
  accent,
  goal,
  setGoal,
  next,
  showNotifySheet,
  setShowNotifySheet,
  showPushPrompt,
  setShowPushPrompt,
}) {
  const active = !!goal;

  const dismissPermission = () => {
    setShowPushPrompt(false);
    setShowNotifySheet(false);
  };

  return (
    <OnboardingShell
      theme={theme}
      accent={accent}
      title="What should Himma help with first?"
      topAction={
        <button
          onClick={next}
          style={{ ...skipButtonStyle(theme), textDecoration: "underline" }}
        >
          SKIP
        </button>
      }
      footer={
        <button
          disabled={!active}
          onClick={next}
          style={primaryActionStyle(theme, accent, active)}
        >
          NEXT
        </button>
      }
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {ONBOARDING_GOALS.map((item) => {
          const selected = goal === item.id;
          const Icon = Ico[item.icon] || Ico.target;
          return (
            <button
              key={item.id}
              onClick={() => setGoal(item.id)}
              style={{
                width: "100%",
                display: "flex",
                alignItems: "center",
                gap: 12,
                textAlign: "left",
                border: `0.5px solid ${selected ? theme.line2 : theme.line}`,
                background: selected ? theme.surface3 : theme.surface,
                color: theme.text,
                borderRadius: 16,
                padding: 14,
                cursor: "pointer",
                transition: `background ${ONBOARDING_EASE}, border ${ONBOARDING_EASE}`,
              }}
            >
              <div
                style={{
                  width: 38,
                  height: 38,
                  borderRadius: 14,
                  background: selected ? theme.surface : theme.surface2,
                  color: selected ? accent : theme.textDim,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  flexShrink: 0,
                }}
              >
                <Icon size={18} />
              </div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div
                  style={{
                    fontFamily: FONTS.ui,
                    fontSize: 14,
                    fontWeight: 500,
                    color: theme.text,
                  }}
                >
                  {item.title}
                </div>
                <div
                  style={{
                    fontFamily: FONTS.ui,
                    fontSize: 12.5,
                    color: theme.textDim,
                    marginTop: 3,
                    lineHeight: 1.35,
                  }}
                >
                  {item.body}
                </div>
              </div>
              {selected && <Ico.check size={18} stroke={accent} sw={2.3} />}
            </button>
          );
        })}
      </div>

      {showNotifySheet && (
        <NotificationSheet
          theme={theme}
          accent={accent}
          onRemind={() => setShowPushPrompt(true)}
          onLater={() => setShowNotifySheet(false)}
        />
      )}

      {showPushPrompt && (
        <SystemPrompt
          theme={theme}
          title="Allow Himma to send notifications?"
          body="Receive trial reminders and important account alerts."
          primary="Allow"
          secondary="Don't Allow"
          onPrimary={dismissPermission}
          onSecondary={dismissPermission}
        />
      )}
    </OnboardingShell>
  );
}

function DashboardActivationStep({
  theme,
  accent,
  selectedGoal,
  onConnectAccounts,
  onNav,
}) {
  const selected =
    ONBOARDING_GOALS.find((item) => item.id === selectedGoal) ||
    ONBOARDING_GOALS[0];

  return (
    <div style={{ height: "100%", position: "relative", background: theme.bg }}>
      <OnboardingFrameKeyframes />
      <HomeScreen
        theme={theme}
        accent={accent}
        onNav={onNav}
        onAskHimma={() => {}}
        onOpenPaywall={() => {}}
      />
      <TabBar current="home" onNav={onNav} theme={theme} accent={accent} />

      <div
        style={{
          position: "absolute",
          inset: 0,
          zIndex: 70,
          backdropFilter: "blur(1px)",
          animation: "himma-onb-fade 180ms",
        }}
      />
      <div
        style={{
          position: "absolute",
          inset: 0,
          zIndex: 75,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          padding: 24,
        }}
      >
        <div
          style={{
            width: "100%",
            borderRadius: 26,
            background: theme.surface,
            border: `0.5px solid ${theme.line2}`,
            boxShadow: theme.shadow?.modal,
            padding: 22,
            animation: `himma-onb-sheet ${ONBOARDING_EASE}`,
          }}
        >
          <div
            style={{
              padding: 14,
              borderRadius: 18,
            }}
          >
            <div
              style={{
                fontFamily: FONTS.ui,
                fontSize: 22,
                fontWeight: 700,
                color: theme.text,
              }}
            >
              {selected.title}
            </div>
            <div
              style={{
                marginTop: 12,
                display: "flex",
                flexDirection: "column",
                gap: 8,
              }}
            >
              {selected.features.map((feature) => (
                <div
                  key={feature}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 9,
                    fontFamily: FONTS.ui,
                    fontSize: 13,
                    lineHeight: 1.35,
                  }}
                >
                  <Ico.check size={13} stroke={accent} sw={2.2} />
                  <span>{feature}</span>
                </div>
              ))}
            </div>
          </div>

          <button
            onClick={onConnectAccounts}
            style={{
              ...primaryActionStyle(theme, accent, true),
              marginTop: 10,
              minHeight: 0,
              padding: "15px 5px",
            }}
          >
            CONNECT YOUR ACCOUNTS
          </button>
        </div>
      </div>
    </div>
  );
}

function NotificationSheet({ theme, accent, onRemind, onLater }) {
  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 50,
        display: "flex",
        alignItems: "flex-end",
        background: "rgba(0,0,0,0.22)",
        animation: "himma-onb-fade 180ms",
      }}
    >
      <div
        style={{
          width: "100%",
          borderRadius: "28px 28px 0 0",
          background: theme.surface,
          borderTop: `0.5px solid ${theme.line2}`,
          boxShadow: theme.shadow?.sheet,
          padding: "10px 20px 34px",
          animation: `himma-onb-sheet ${ONBOARDING_EASE}`,
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            paddingBottom: 14,
          }}
        >
          <div
            style={{
              width: 40,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>
        <div
          style={{
            width: 46,
            height: 46,
            borderRadius: 17,
            background: `${accent}16`,
            color: accent,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Ico.bell size={22} />
        </div>
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 22,
            color: theme.text,
            fontWeight: 760,
            marginTop: 16,
          }}
        >
          Don't miss a beat
        </div>
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 13.5,
            lineHeight: 1.52,
            color: theme.textDim,
            marginTop: 8,
          }}
        >
          Get the trial reminder before billing starts and receive account
          alerts only when they matter.
        </div>
        <button
          onClick={onRemind}
          style={{ ...primaryActionStyle(theme, accent, true), marginTop: 20 }}
        >
          REMIND ME
        </button>
        <button
          onClick={onLater}
          style={{ ...secondaryActionStyle(theme), marginTop: 10, border: 0 }}
        >
          MAYBE LATER
        </button>
      </div>
    </div>
  );
}

function SystemPrompt({
  theme,
  title,
  body,
  primary,
  secondary,
  onPrimary,
  onSecondary,
}) {
  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 90,
        background: "rgba(0,0,0,0.22)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 32,
        animation: "himma-onb-fade 160ms",
      }}
    >
      <div
        style={{
          width: "100%",
          borderRadius: 18,
          background: "rgba(248,248,248,0.94)",
          color: "#111111",
          overflow: "hidden",
          boxShadow: "0 20px 50px rgba(0,0,0,0.26)",
          backdropFilter: "blur(20px)",
        }}
      >
        <div style={{ padding: "20px 20px 16px", textAlign: "center" }}>
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 17,
              fontWeight: 700,
              lineHeight: 1.25,
            }}
          >
            {title}
          </div>
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: 13,
              lineHeight: 1.42,
              color: "rgba(0,0,0,0.62)",
              marginTop: 8,
            }}
          >
            {body}
          </div>
        </div>
        <button
          onClick={onPrimary}
          style={systemPromptButtonStyle("#007AFF", true)}
        >
          {primary}
        </button>
        <button
          onClick={onSecondary}
          style={systemPromptButtonStyle("#007AFF", false)}
        >
          {secondary}
        </button>
      </div>
    </div>
  );
}

function OnboardingShell({
  theme,
  accent,
  eyebrow,
  title,
  children,
  footer,
  topAction,
  center,
}) {
  return (
    <div
      style={{
        height: "100%",
        position: "relative",
        background: theme.bg,
        color: theme.text,
      }}
    >
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          right: 0,
          padding: "12px 20px 0",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          zIndex: 5,
        }}
      >
        <Wordmark color={theme.text} accent={accent} size={18} />
        {topAction}
      </div>
      <Screen
        theme={theme}
        padBottom={footer ? 132 : 34}
        style={{ paddingTop: 55, paddingLeft: 20, paddingRight: 20 }}
      >
        <div style={{ textAlign: center ? "center" : "left" }}>
          {eyebrow && (
            <SectionLabel theme={theme} style={{ color: accent }}>
              {eyebrow}
            </SectionLabel>
          )}
          <div
            style={{
              fontFamily: FONTS.ui,
              fontSize: center ? 30 : 32,
              lineHeight: 1.06,
              letterSpacing: -0.2,
              color: theme.text,
              fontWeight: 600,
              marginTop: eyebrow ? 8 : 0,
            }}
          >
            {title}
          </div>
        </div>
        <div style={{ marginTop: center ? 14 : 28 }}>{children}</div>
      </Screen>
      {footer && (
        <div
          style={{
            position: "absolute",
            left: 0,
            right: 0,
            bottom: 0,
            padding: "14px 20px 34px",
            background: `linear-gradient(to top, ${theme.bg} 72%, ${theme.bg}00)`,
            zIndex: 20,
          }}
        >
          {footer}
        </div>
      )}
    </div>
  );
}

function OnboardingInput({
  theme,
  label,
  value,
  onChange,
  placeholder,
  type = "text",
  autoFocus,
  style = {},
}) {
  return (
    <label style={{ display: "block" }}>
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 10,
          letterSpacing: 1.2,
          textTransform: "uppercase",
          color: theme.textMute,
          marginBottom: 8,
        }}
      >
        {label}
      </div>
      <input
        value={value}
        onChange={(event) => onChange(event.target.value)}
        placeholder={placeholder}
        type={type}
        autoFocus={autoFocus}
        style={{
          width: "100%",
          height: 54,
          borderRadius: 16,
          border: `0.5px solid ${theme.line2}`,
          background: theme.surface,
          color: theme.text,
          padding: "0 16px",
          fontFamily: FONTS.ui,
          fontSize: 14,
          outline: "none",
          ...style,
        }}
      />
    </label>
  );
}

function FaceIdMark({ theme, accent }) {
  return (
    <div
      style={{
        width: 118,
        height: 118,
        borderRadius: 36,
        border: `2px solid ${accent}`,
        color: accent,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        background: `${accent}0D`,
      }}
    >
      <svg
        width="70"
        height="70"
        viewBox="0 0 70 70"
        fill="none"
        stroke="currentColor"
        strokeWidth="3"
        strokeLinecap="round"
        strokeLinejoin="round"
      >
        <path d="M20 10h-6a4 4 0 0 0-4 4v6" />
        <path d="M50 10h6a4 4 0 0 1 4 4v6" />
        <path d="M20 60h-6a4 4 0 0 1-4-4v-6" />
        <path d="M50 60h6a4 4 0 0 0 4-4v-6" />
        <path d="M26 28v12" />
        <path d="M44 28v12" />
        <path d="M31 48c3 2 6 2 9 0" />
      </svg>
    </div>
  );
}

function TimelineRow({ theme, accent, row, last }) {
  const Icon = Ico[row.icon] || Ico.check;
  const activeColor = "#2563EB";
  const isActive = Boolean(row.active);

  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "24px 1fr",
        gap: 12,
        position: "relative",
        paddingBottom: last ? 0 : 20,
      }}
    >
      {!last && (
        <div
          style={{
            position: "absolute",
            left: 11,
            top: 24,
            bottom: 0,
            width: 1,
            background: theme.line2,
          }}
        />
      )}
      <div
        style={{
          width: 24,
          height: 24,
          borderRadius: 12,
          background: isActive ? activeColor : theme.surface2,
          color: isActive ? "#FFFFFF" : theme.textMute,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          border: isActive ? "none" : `0.5px solid ${theme.line2}`,
          zIndex: 1,
        }}
      >
        <Icon size={12} stroke="currentColor" sw={isActive ? 2.3 : 1.8} />
      </div>
      <div>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            letterSpacing: 1,
            textTransform: "uppercase",
            color: isActive ? activeColor : theme.textMute,
          }}
        >
          {row.label}
        </div>
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 14,
            fontWeight: 700,
            color: theme.text,
            marginTop: 3,
          }}
        >
          {row.title}
        </div>
        <div
          style={{
            fontFamily: FONTS.ui,
            fontSize: 12.5,
            color: theme.textDim,
            lineHeight: 1.45,
            marginTop: 3,
          }}
        >
          {row.body}
        </div>
      </div>
    </div>
  );
}

function PaywallMiniCard({ theme, accent, icon, title }) {
  const Icon = Ico[icon] || Ico.check;
  return (
    <div
      style={{
        border: `0.5px solid ${theme.line}`,
        background: theme.surface,
        borderRadius: 16,
        padding: 13,
        display: "flex",
        alignItems: "center",
        gap: 8,
      }}
    >
      <div style={{ color: accent, flexShrink: 0 }}>
        <Icon size={18} />
      </div>
      <div
        style={{
          fontFamily: FONTS.ui,
          fontSize: 12.5,
          color: theme.text,
          lineHeight: 1.3,
          fontWeight: 400,
          whiteSpace: "nowrap",
        }}
      >
        {title}
      </div>
    </div>
  );
}

function getTrialDates() {
  const today = new Date();
  const reminder = new Date(today);
  reminder.setDate(today.getDate() + 5);
  const billing = new Date(today);
  billing.setDate(today.getDate() + 7);
  const fmt = new Intl.DateTimeFormat("en-AE", {
    month: "short",
    day: "numeric",
  });
  return {
    reminder: fmt.format(reminder),
    billing: fmt.format(billing),
  };
}

function onboardingButtonStyle({ bg, color, border }) {
  return {
    width: "100%",
    minHeight: 52,
    borderRadius: 18,
    border: `0.5px solid ${border}`,
    background: bg,
    color,
    fontFamily: FONTS.ui,
    fontSize: 13.5,
    fontWeight: 500,
    letterSpacing: 0.4,
    cursor: "pointer",
  };
}

function primaryActionStyle(theme, accent, enabled) {
  return {
    width: "100%",
    minHeight: 52,
    borderRadius: 18,
    border: "none",
    background: enabled ? "#071124" : theme.surface3,
    color: enabled ? "#FFFFFF" : theme.textMute,
    fontFamily: FONTS.ui,
    fontSize: 13.5,
    fontWeight: 500,
    letterSpacing: 0.4,
    cursor: enabled ? "pointer" : "not-allowed",
    transition: `background ${ONBOARDING_EASE}, color ${ONBOARDING_EASE}`,
  };
}

function secondaryActionStyle(theme) {
  return {
    width: "100%",
    minHeight: 52,
    borderRadius: 18,
    border: `0.5px solid ${theme.line2}`,
    background: theme.surface,
    color: theme.text,
    fontFamily: FONTS.ui,
    fontSize: 13.5,
    fontWeight: 500,
    letterSpacing: 0.35,
    cursor: "pointer",
  };
}

function skipButtonStyle(theme) {
  return {
    border: "none",
    background: "transparent",
    color: theme.textDim,
    fontFamily: FONTS.mono,
    fontSize: 10,
    letterSpacing: 1.2,
    fontWeight: 650,
    cursor: "pointer",
    padding: "8px 0 8px 12px",
  };
}

function carouselArrowStyle(side, disabled) {
  return {
    position: "absolute",
    top: "50%",
    [side]: 14,
    width: 34,
    height: 34,
    borderRadius: 17,
    border: "0.5px solid rgba(7,17,36,0.12)",
    background: "rgba(255,255,255,0.72)",
    color: "#071124",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    opacity: disabled ? 0.28 : 1,
    cursor: disabled ? "not-allowed" : "pointer",
    zIndex: 4,
    backdropFilter: "blur(12px)",
  };
}

function systemPromptButtonStyle(color, strong) {
  return {
    width: "100%",
    minHeight: 46,
    border: "none",
    borderTop: "0.5px solid rgba(0,0,0,0.14)",
    background: "transparent",
    color,
    fontFamily: FONTS.ui,
    fontSize: 16,
    fontWeight: strong ? 700 : 500,
    cursor: "pointer",
  };
}

Object.assign(window, { OnboardingFlow });
