// Shared Privy-style connect modal — used on both landing and app.
// Self-contained (inline styles, no app-kit dependency) so landing can mount it
// without loading the app store. Brand-book faithful: square corners, oxblood
// accent, Inter Tight + JetBrains Mono, uppercase mono eyebrows.
//
// Props:
//   open       — boolean, whether modal is visible
//   onClose    — fired when user dismisses (scrim click / ✕)
//   onConnect  — fired with { method, address, ensOrEmail } on fake success
//   emailDefault — optional pre-filled email (unused for now)

const { useState: cUS, useEffect: cUE } = React;

const ConnectModal = ({ open, onClose, onConnect, emailDefault = "" }) => {
  const [step, setStep] = cUS("chooser"); // chooser | email | connecting
  const [email, setEmail] = cUS(emailDefault);
  const [otp, setOtp] = cUS(["", "", "", "", "", ""]);
  const [connecting, setConnecting] = cUS(null); // { method, wallet }

  cUE(() => {
    if (open) {
      setStep("chooser");
      setEmail(emailDefault);
      setOtp(["", "", "", "", "", ""]);
      setConnecting(null);
    }
  }, [open, emailDefault]);

  cUE(() => {
    if (step === "email") {
      const id = setTimeout(() => document.getElementById("connect-otp-0")?.focus(), 30);
      return () => clearTimeout(id);
    }
  }, [step]);

  if (!open) return null;

  const fakeConnectWallet = (wallet) => {
    setConnecting({ method: "external", wallet });
    setTimeout(() => {
      onConnect({
        method: "external",
        address: "0x45804880caa7d84fd22a5be5f55bedaecaf78abc",
        ensOrEmail: "daria.eth",
      });
    }, 700);
  };

  const onEmailSubmit = (e) => {
    e.preventDefault();
    if (!email) return;
    setStep("email");
  };

  const onOtpDigit = (idx, val) => {
    if (!/^\d?$/.test(val)) return;
    const next = [...otp]; next[idx] = val;
    setOtp(next);
    if (val && idx < 5) document.getElementById("connect-otp-" + (idx + 1))?.focus();
    if (next.every((d) => d)) {
      setConnecting({ method: "email" });
      setTimeout(() => {
        onConnect({
          method: "email",
          address: "0xembeddedwalletviaprivy7d84fd22a5be5f55bedaecaf7802",
          ensOrEmail: email,
        });
      }, 500);
    }
  };

  // ─── Shared styles ───
  const scrim = {
    position: "fixed", inset: 0, background: "rgba(15,13,11,0.72)",
    backdropFilter: "blur(8px)", zIndex: 300, display: "grid",
    placeItems: "center", padding: 20,
  };
  const box = {
    width: 540, maxWidth: "100%", background: "var(--paper)",
    border: "1px solid var(--ink)", fontFamily: "var(--font-sans)",
  };
  const head = {
    padding: "16px 22px", borderBottom: "1px solid var(--ink)",
    display: "flex", justifyContent: "space-between", alignItems: "center",
  };
  const eyebrow = {
    fontSize: 10, letterSpacing: ".1em", textTransform: "uppercase",
    color: "var(--ink-4)", fontFamily: "var(--font-mono)",
  };
  const closeBtn = {
    background: "none", border: "none", fontSize: 14, cursor: "pointer",
    color: "var(--ink-4)", fontFamily: "var(--font-mono)",
  };

  // ─── Connecting spinner ───
  if (connecting) {
    const label = connecting.method === "email"
      ? "verifying code · creating embedded wallet"
      : "connecting · " + connecting.wallet;
    return (
      <div style={scrim}>
        <div style={box}>
          <div style={head}>
            <span style={eyebrow}>◆ connecting</span>
          </div>
          <div style={{ padding: 48, textAlign: "center" }}>
            <div style={{ width: 56, height: 56, margin: "0 auto", border: "1px solid var(--ink)", display: "grid", placeItems: "center", fontFamily: "var(--font-mono)", fontSize: 22 }}>◆</div>
            <div style={{ marginTop: 18, fontSize: 16, fontWeight: 500, letterSpacing: "-.01em" }}>Signing you in</div>
            <div style={{ marginTop: 6, fontSize: 12, color: "var(--ink-4)", fontFamily: "var(--font-mono)", letterSpacing: ".04em" }}>{label}</div>
          </div>
        </div>
      </div>
    );
  }

  // ─── Email OTP step ───
  if (step === "email") {
    return (
      <div style={scrim} onClick={onClose}>
        <div style={{ ...box, width: 480 }} onClick={(e) => e.stopPropagation()}>
          <div style={head}>
            <span style={eyebrow}>◆ verify email</span>
            <button onClick={onClose} style={closeBtn}>✕</button>
          </div>
          <div style={{ padding: 28, textAlign: "center" }}>
            <div style={{ width: 56, height: 56, margin: "0 auto", border: "1px solid var(--ink)", display: "grid", placeItems: "center", fontFamily: "var(--font-mono)", fontSize: 22 }}>@</div>
            <h3 style={{ fontSize: 24, fontWeight: 500, letterSpacing: "-.02em", marginTop: 16 }}>Check your email</h3>
            <p style={{ fontSize: 14, color: "var(--ink-4)", marginTop: 6 }}>We sent a 6-digit code to <span style={{ color: "var(--ink)" }}>{email}</span></p>
            <div style={{ marginTop: 26, display: "flex", gap: 8, justifyContent: "center" }}>
              {otp.map((d, idx) => (
                <input
                  key={idx}
                  id={"connect-otp-" + idx}
                  value={d}
                  onChange={(e) => onOtpDigit(idx, e.target.value)}
                  maxLength={1}
                  style={{ width: 48, height: 56, border: "1px solid var(--ink)", background: "var(--paper-2)", textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 24, outline: "none" }}
                />
              ))}
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 18, fontFamily: "var(--font-mono)" }}>didn't arrive? <a style={{ color: "var(--ox)", textDecoration: "underline", cursor: "pointer" }}>resend in 0:42</a></div>
            <div style={{ marginTop: 22, padding: 14, background: "var(--paper-2)", border: "1px solid var(--paper-3)", textAlign: "left" }}>
              <div style={eyebrow}>what happens next</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 6, lineHeight: 1.5 }}>
                Privy creates a self-custodial embedded wallet tied to your email. The private key is split via Shamir — 1 share with you, 1 with Privy (device-encrypted), 1 recovery. You can export anytime.
              </div>
            </div>
            <button onClick={() => setStep("chooser")} style={{ marginTop: 18, background: "none", border: "none", color: "var(--ink-4)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase", cursor: "pointer" }}>← back</button>
          </div>
        </div>
      </div>
    );
  }

  // ─── Chooser step ───
  return (
    <div style={scrim} onClick={onClose}>
      <div style={box} onClick={(e) => e.stopPropagation()}>
        <div style={head}>
          <span style={eyebrow}>◆ connect · powered by privy</span>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: 28 }}>
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{ width: 40, height: 40, background: "var(--ink)", color: "var(--paper)", display: "grid", placeItems: "center", fontFamily: "var(--font-mono)", fontSize: 16, fontWeight: 500, letterSpacing: "-.04em" }}>dg</div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-.02em" }}>Sign in to deGold</div>
              <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2, fontFamily: "var(--font-mono)" }}>non-custodial · we never see your seed phrase</div>
            </div>
          </div>

          {/* Email path */}
          <div style={{ marginTop: 22, border: "1px solid var(--paper-3)", padding: 16 }}>
            <div style={{ ...eyebrow, marginBottom: 8 }}>new to web3</div>
            <form onSubmit={onEmailSubmit}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 8 }}>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@email.com"
                  style={{ padding: "12px 14px", border: "1px solid var(--ink)", fontFamily: "var(--font-mono)", fontSize: 13, background: "var(--paper-2)", outline: "none" }}
                />
                <button type="submit" style={{ padding: "12px 18px", background: "var(--ink)", color: "var(--paper)", border: "1px solid var(--ink)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".1em", textTransform: "uppercase", cursor: "pointer" }}>Continue →</button>
              </div>
              <div style={{ fontSize: 10, color: "var(--ink-5)", marginTop: 8, fontFamily: "var(--font-mono)" }}>
                we'll send a one-time code · a self-custodial embedded wallet will be created for you
              </div>
            </form>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "22px 0 18px" }}>
            <div style={{ flex: 1, borderBottom: "1px solid var(--paper-3)" }} />
            <span style={{ fontSize: 10, letterSpacing: ".1em", color: "var(--ink-5)", fontFamily: "var(--font-mono)" }}>OR BRING YOUR WALLET</span>
            <div style={{ flex: 1, borderBottom: "1px solid var(--paper-3)" }} />
          </div>

          <div style={{ display: "grid", gap: 8 }}>
            {[
              { k: "metamask", l: "Metamask", sub: "detected · chrome extension", icon: "🦊" },
              { k: "rabby", l: "Rabby", sub: "detected · extension", icon: "🐰" },
              { k: "wc", l: "WalletConnect", sub: "mobile · scan QR", icon: "◇" },
              { k: "ledger", l: "Ledger", sub: "hardware · USB", icon: "▣" },
              { k: "coinbase", l: "Coinbase Wallet", sub: "", icon: "◆" },
            ].map((w) => (
              <button
                key={w.k}
                onClick={() => fakeConnectWallet(w.l)}
                style={{ padding: "12px 16px", border: "1px solid var(--paper-3)", background: "var(--paper)", cursor: "pointer", display: "flex", justifyContent: "space-between", alignItems: "center", fontFamily: "var(--font-sans)" }}
              >
                <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                  <div style={{ width: 30, height: 30, background: "var(--paper-2)", display: "grid", placeItems: "center", fontSize: 14, border: "1px solid var(--paper-3)" }}>{w.icon}</div>
                  <div style={{ textAlign: "left" }}>
                    <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-.01em" }}>{w.l}</div>
                    <div style={{ fontSize: 10, color: "var(--ink-4)", fontFamily: "var(--font-mono)" }}>{w.sub}</div>
                  </div>
                </div>
                <span style={{ fontSize: 12, color: "var(--ox)", fontFamily: "var(--font-mono)" }}>connect →</span>
              </button>
            ))}
          </div>

          <div style={{ fontSize: 10, color: "var(--ink-5)", marginTop: 22, lineHeight: 1.6, textAlign: "center", fontFamily: "var(--font-mono)" }}>
            your address is screened against OFAC / UN / EU sanctions lists<br />
            US, China, Russia IP addresses are blocked on-contract
          </div>
        </div>
      </div>
    </div>
  );
};

window.ConnectModal = ConnectModal;
