/* Meridian Onboarding — Screens Part 1: Signup, Account Type, Authorize */

/* ═══════ Screen 1: Signup ═══════ */
function SignupScreen({ onComplete, density }) {
  const [subState, setSubState] = useState("email"); // email, otp, provisioning
  const [email, setEmail] = useState("");
  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const otpRefs = useRef([]);

  useEffect(() => {
    if (subState === "provisioning") {
      const t = setTimeout(() => onComplete(), 2000);
      return () => clearTimeout(t);
    }
  }, [subState]);

  const handleOtpChange = (i, val) => {
    if (val.length > 1) return;
    const next = [...otp];
    next[i] = val;
    setOtp(next);
    if (val && i < 5) otpRefs.current[i + 1]?.focus();
    if (next.every(c => c !== "")) {
      setTimeout(() => setSubState("provisioning"), 600);
    }
  };

  const handleOtpKeyDown = (i, e) => {
    if (e.key === "Backspace" && !otp[i] && i > 0) {
      otpRefs.current[i - 1]?.focus();
    }
  };

  /* Email entry */
  if (subState === "email") {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "60vh" }}>
        <div className="m-modal" style={{ position: "relative", animation: "none", maxWidth: 420, width: "100%" }}>
          <h2 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", textAlign: "center", marginBottom: "var(--space-6)" }}>
            Log in or sign up
          </h2>

          <div style={{ display: "flex", gap: 0, marginBottom: "var(--space-5)" }}>
            <input className="m-input" placeholder="your@email.com" value={email}
              onChange={e => setEmail(e.target.value)}
              style={{ flex: 1, borderRadius: "var(--radius-sm) 0 0 var(--radius-sm)", borderRight: "none" }}
              onKeyDown={e => { if (e.key === "Enter" && email) setSubState("otp"); }} />
            <button className="m-btn m-btn-dark" onClick={() => email && setSubState("otp")}
              style={{ borderRadius: "0 var(--radius-sm) var(--radius-sm) 0", padding: "12px 16px" }}>
              <Icon name="arrowRight" size={18} />
            </button>
          </div>

          <div className="m-divider" style={{ marginBottom: "var(--space-5)" }}>or</div>

          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2)" }}>
            {[
              { icon: "G", label: "Continue with Google" },
              { icon: "◻", label: "Continue with Apple" },
              { icon: "W", label: "Continue with WhatsApp" },
              { icon: "≡", label: "Continue with SMS" },
              { icon: "X", label: "Continue with X" },
              { icon: "◎", label: "Continue with Instagram" },
              { icon: "→", label: "Continue with a passkey" },
            ].map((s, i) => (
              <button key={i} className="m-social-btn" onClick={() => setSubState("otp")}>
                <span className="m-social-icon">{s.icon}</span>
                <span>{s.label}</span>
              </button>
            ))}
          </div>

          <p style={{ fontSize: "var(--text-xs)", color: "var(--fg-subtle)", textAlign: "center", marginTop: "var(--space-4)" }}>
            Passkey: sign in with your fingerprint or device PIN.
          </p>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginTop: "var(--space-4)", fontSize: "var(--text-xs)", color: "var(--fg-subtle)" }}>
            <Icon name="shield" size={12} color="var(--fg-subtle)" /> Protected by Privy
          </div>
          <div style={{ textAlign: "center", marginTop: "var(--space-3)" }}>
            <a href="#" onClick={e => { e.preventDefault(); onComplete(); }} style={{ fontSize: "var(--text-sm)" }}>
              Proceed to onboarding →
            </a>
          </div>
        </div>
      </div>
    );
  }

  /* OTP entry */
  if (subState === "otp") {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "60vh" }}>
        <div className="m-modal" style={{ position: "relative", animation: "none", maxWidth: 420, width: "100%", textAlign: "center" }}>
          <h2 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>
            Enter verification code
          </h2>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-6)" }}>
            We sent a code to <strong style={{ color: "var(--fg)" }}>{email || "your@email.com"}</strong>
          </p>
          <div style={{ display: "flex", justifyContent: "center", gap: 8, marginBottom: "var(--space-6)" }}>
            {otp.map((digit, i) => (
              <input key={i} ref={el => otpRefs.current[i] = el}
                className="m-input" value={digit} maxLength={1}
                onChange={e => handleOtpChange(i, e.target.value)}
                onKeyDown={e => handleOtpKeyDown(i, e)}
                style={{ width: 48, height: 52, textAlign: "center", fontSize: 20, fontWeight: "var(--w-semibold)", padding: 0 }} />
            ))}
          </div>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-subtle)" }}>
            Didn't receive it? <a href="#" onClick={e => e.preventDefault()}>Resend code</a>
          </p>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginTop: "var(--space-6)", fontSize: "var(--text-xs)", color: "var(--fg-subtle)" }}>
            <Icon name="shield" size={12} color="var(--fg-subtle)" /> Protected by Privy
          </div>
        </div>
      </div>
    );
  }

  /* Provisioning */
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "60vh" }}>
      <div className="m-modal" style={{ position: "relative", animation: "none", maxWidth: 420, width: "100%", textAlign: "center" }}>
        <div className="m-spinner" style={{ margin: "0 auto var(--space-5)", width: 36, height: 36 }}></div>
        <h2 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>
          Setting up your account
        </h2>
        <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>
          Provisioning your wallet and trading infrastructure...
        </p>
      </div>
    </div>
  );
}

/* ═══════ Screen 2: Choose Account Type ═══════ */
function ChooseAccountScreen({ onChoose, density }) {
  const [selected, setSelected] = useState(null);
  const pad = density === "compact" ? "var(--space-5)" : density === "spacious" ? "var(--space-8)" : "var(--space-6)";

  return (
    <div className={`onboard-main ${density}`} data-screen-label="Choose Account Type">
      <div style={{ textAlign: "center", marginBottom: "var(--space-8)" }}>
        <h1 style={{ fontSize: "var(--text-h1)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)", letterSpacing: "var(--track-tight)" }}>
          How do you want to start?
        </h1>
        <p style={{ fontSize: "var(--text-body)", color: "var(--fg-muted)", maxWidth: 560, margin: "0 auto" }}>
          Pick a real account to fund and trade live, or a demo to practise with $10,000 of play money.
        </p>
      </div>

      <div className="two-col" style={{ maxWidth: 740, margin: "0 auto" }}>
        {/* Real Account */}
        <div className={`m-acct-card ${selected === 'real' ? 'selected' : ''}`}
          onClick={() => setSelected("real")} style={{ padding: pad }}>
          <span className="label-upper" style={{ marginBottom: "var(--space-2)", display: "block" }}>Real account</span>
          <h2 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>
            Deposit and trade live
          </h2>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)", lineHeight: 1.6 }}>
            Fund in minutes with USDC, card, or bank. Start trading on MetaTrader. Withdraw any time — no review, no delay.
          </p>
          <ul style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", paddingLeft: 18, marginBottom: "var(--space-6)", display: "flex", flexDirection: "column", gap: 4 }}>
            <li>Funds stay in your own account</li>
            <li>No KYC, no broker holding your money</li>
            <li>Spread-only, no deposit fee</li>
          </ul>
          <button className="m-btn m-btn-dark m-btn-full m-btn-lg" onClick={(e) => { e.stopPropagation(); onChoose("real"); }}>
            Start with a real account
          </button>
        </div>

        {/* Demo Account */}
        <div className={`m-acct-card ${selected === 'demo' ? 'selected' : ''}`}
          onClick={() => setSelected("demo")} style={{ padding: pad }}>
          <span className="label-upper" style={{ marginBottom: "var(--space-2)", display: "block" }}>Demo account</span>
          <h2 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>
            Practise with $10,000
          </h2>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)", lineHeight: 1.6 }}>
            Try Meridian risk-free. Signatures, order flow, and spreads behave exactly like the live account — we don't fudge demo numbers like other brokers do.
          </p>
          <div className="m-callout" style={{ marginBottom: "var(--space-6)", fontSize: "var(--text-sm)" }}>
            <strong style={{ color: "var(--fg)" }}>Honest demo.</strong>{" "}
            <span style={{ color: "var(--fg-muted)" }}>What you see here matches the live spreads. Test your strategy here before you fund.</span>
          </div>
          <button className="m-btn m-btn-ghost m-btn-full m-btn-lg" onClick={(e) => { e.stopPropagation(); onChoose("demo"); }}>
            Open a demo account
          </button>
        </div>
      </div>

      <p style={{ textAlign: "center", fontSize: "var(--text-sm)", color: "var(--fg-subtle)", marginTop: "var(--space-6)" }}>
        You can switch between demo and live any time from your account.
      </p>
    </div>
  );
}


/* ═══════ Screen 3: Authorize Trading ═══════ */
function AuthorizeScreen({ onContinue, onBack, stepVariant, currentStep, density, btnStyle }) {
  const [checks, setChecks] = useState([false, false, false, false]);
  const [signingState, setSigningState] = useState(null); // null | "signing" | "broadcasting" | "confirming" | "settled"
  const allChecked = checks.every(Boolean);
  const pad = density === "compact" ? "var(--space-4)" : density === "spacious" ? "var(--space-8)" : "var(--space-6)";

  const toggleCheck = (i) => {
    const next = [...checks]; next[i] = !next[i]; setChecks(next);
  };

  const handleSign = () => {
    setSigningState("signing");
    setTimeout(() => setSigningState("broadcasting"), 2000);
    setTimeout(() => setSigningState("confirming"), 3500);
    setTimeout(() => setSigningState("settled"), 5000);
  };

  const checkLabels = [
    "I am not in the United States or any other restricted jurisdiction.",
    "I accept the Terms of Use and Privacy Policy.",
    "I approve the MetaTrader interface to place trades on my behalf.",
    "I generate my MetaTrader account with this signature."
  ];

  return (
    <div data-screen-label="Authorize Trading">
      <StepIndicator current={currentStep} variant={stepVariant} />
      <div className={`onboard-main ${density}`}>
        <h1 style={{ fontSize: "var(--text-h1)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-8)", letterSpacing: "var(--track-tight)" }}>
          Authorize trading
        </h1>

        <div className="two-col">
          {/* Left: Explainer */}
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-5)" }}>
            <div className="m-card" style={{ padding: pad }}>
              <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>
                One signature, four things
              </h3>
              <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)", lineHeight: 1.6 }}>
                Signing the transaction below confirms all of the following at once. We bundle them so you don't have to sign four separate times.
              </p>
              <ol style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", paddingLeft: 18, display: "flex", flexDirection: "column", gap: 6, lineHeight: 1.6 }}>
                <li>You're outside restricted jurisdictions.</li>
                <li>You accept Terms of Use + Privacy Policy.</li>
                <li>Meridian can place trades on your behalf — never move your money.</li>
                <li>Your MetaTrader account is generated.</li>
              </ol>
            </div>
            <Accordion title="Learn more about how this works">
              <p>When you sign, a single on-chain transaction registers your trading key. This key can submit orders through the Meridian smart contract but cannot move, withdraw, or transfer your funds. You keep full custody at all times. You can revoke this key from your Account page.</p>
            </Accordion>
          </div>

          {/* Right: Confirm & Sign */}
          <div className="m-card" style={{ padding: pad }}>
            {signingState === "settled" ? (
              <div>
                <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Authorized</h3>
                <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", lineHeight: 1.6, marginBottom: "var(--space-3)" }}>
                  You're all set. Your trading authorization is active, your MetaTrader account is generated, and your money is still in your account.
                </p>
                <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-5)" }}>
                  You can revoke this any time from <a href="#">Account</a>.
                </p>
                <button className={`m-btn m-btn-full m-btn-lg ${btnStyle === 'outline' ? 'm-btn-ghost' : 'm-btn-dark'}`} onClick={onContinue}>
                  Continue to deposit
                </button>
                <div style={{ fontSize: "var(--text-xs)", color: "var(--fg-subtle)", display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginTop: "var(--space-3)" }}>
                  <Icon name="shield" size={12} color="var(--fg-subtle)" /> Protected by Privy
                </div>
              </div>
            ) : (
              <div>
                <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>Confirm and sign</h3>
                <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-5)" }}>
                  Check each item below, then sign once.
                </p>
                <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2)", marginBottom: "var(--space-5)" }}>
                  {checkLabels.map((label, i) => (
                    <div key={i} className={`m-checkbox ${checks[i] ? 'checked' : ''}`} onClick={() => toggleCheck(i)}>
                      <div className="m-check-box">
                        {checks[i] && <Icon name="check" size={14} stroke={3} color="#fff" />}
                      </div>
                      <span style={{ fontSize: "var(--text-sm)", lineHeight: 1.5 }}>{label}</span>
                    </div>
                  ))}
                </div>
                <button className={`m-btn m-btn-full m-btn-lg ${btnStyle === 'outline' ? 'm-btn-ghost' : 'm-btn-dark'}`}
                  disabled={!allChecked} onClick={handleSign}>
                  Sign & continue
                </button>
                <div style={{ textAlign: "center", marginTop: "var(--space-3)" }}>
                  <a href="#" onClick={e => { e.preventDefault(); }} style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>
                    Not yet, come back to this
                  </a>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Bottom nav */}
        <div className="m-bottom-nav">
          <button className="m-btn m-btn-ghost" onClick={onBack}>Back</button>
          <button className={`m-btn ${btnStyle === 'outline' ? 'm-btn-ghost' : 'm-btn-dark'}`}
            disabled={signingState !== "settled"} onClick={onContinue}>Continue</button>
        </div>
      </div>

      {/* Privy Modal */}
      {signingState && signingState !== "settled" && (
        <PrivyModal state={signingState}
          onSign={() => {}}
          onClose={() => { if (signingState === "settled") setSigningState("settled"); }} />
      )}
    </div>
  );
}

Object.assign(window, { SignupScreen, ChooseAccountScreen, AuthorizeScreen });
