// Auth + onboarding screens (1–4) for Fortune VPN ЛК. Controlled inputs via window.appState.

// Screen 1: Login (email)
function Screen_Login() {
  const s = useAppState();
  const email = s.draft.loginEmail;
  const authBusy = s.api?.pendingAction === "auth_request";
  const googleBusy = s.api?.pendingAction === "auth_google";
  const googleButtonRef = React.useRef(null);
  const [googleNativeReady, setGoogleNativeReady] = React.useState(false);
  const onChange = (e) => window.actions.setLoginEmail(e.target.value);
  const onSubmit = (e) => { e.preventDefault(); window.actions.submitLogin(); };
  const onGoogle = () => window.actions.loginWithGoogle();

  React.useEffect(() => {
    let cancelled = false;
    let attempts = 0;
    const renderGoogle = () => {
      if (cancelled || !googleButtonRef.current) return;
      attempts += 1;
      const rendered = !!window.FortuneVPNGoogleAuth?.renderButton?.(
        googleButtonRef.current,
        (token) => window.actions.loginWithGoogleToken(token),
      );
      if (rendered) {
        setGoogleNativeReady(true);
        return;
      }
      if (attempts < 20) window.setTimeout(renderGoogle, 250);
    };
    renderGoogle();
    return () => { cancelled = true; };
  }, []);

  return (
    <AuthShell screenLabel="01 Login">
      <h1 style={{ margin: 0, fontSize: 26, fontWeight: 800, letterSpacing: "-0.03em", color: "#FFF" }}>
        Вход в Личный кабинет
      </h1>
      <p style={{ margin: "10px 0 22px", fontSize: 15, color: "var(--muted)", lineHeight: 1.55 }}>
        Один аккаунт работает в личном кабинете и в Android-приложении.
      </p>

      {/* Google Sign-In — primary alternate auth method per requirements §2.2 */}
      <div ref={googleButtonRef} style={{ display: googleNativeReady ? "grid" : "none", placeItems: "center", minHeight: 44 }} />
      {!googleNativeReady ? (
        <button
          type="button"
          onClick={onGoogle}
          disabled={authBusy || googleBusy}
          className="btn btn-block"
          style={{
            background: "#FFF", color: "#0D111A",
            fontSize: 15, fontWeight: 600,
            padding: "12px 18px", borderRadius: 12,
            border: "1px solid var(--border-strong)",
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10,
          }}
        >
          <GoogleGIcon />
          <span>{googleBusy ? "Открываем Google..." : "Войти через Google"}</span>
        </button>
      ) : null}

      {/* Separator */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "18px 0" }}>
        <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
        <span style={{ fontSize: 12, color: "var(--muted)" }}>или</span>
        <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
      </div>

      <form onSubmit={onSubmit}>
        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Email</label>
          <input
            type="email"
            inputMode="email"
            autoFocus
            value={email}
            onChange={onChange}
            placeholder="name@example.com"
            className="field-input"
            style={{ width: "100%", fontSize: 15 }}
          />
        </div>

        <button type="submit" className="btn btn-primary btn-lg btn-block" disabled={authBusy} style={authBusy ? { opacity: 0.65, cursor: "wait" } : null}>
          {authBusy ? "Отправляем..." : "Получить код"}
        </button>
      </form>

      <div style={{ marginTop: 18, fontSize: 13, color: "var(--muted)", textAlign: "center", lineHeight: 1.6 }}>
        Не получаете код? Напишите в поддержку:<br />
        <a href="https://t.me/FortuneVPNsupportbot" target="_blank" rel="noopener" style={{ color: "var(--accent-soft)", textDecoration: "none" }}>@FortuneVPNsupportbot</a>
        {" · "}
        <a href="mailto:support@fortunetavern.com" style={{ color: "var(--accent-soft)", textDecoration: "none" }}>support@fortunetavern.com</a>
      </div>
    </AuthShell>
  );
}

// Multi-color Google "G" mark
const GoogleGIcon = () => (
  <svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
    <path fill="#4285F4" d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"/>
    <path fill="#34A853" d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z"/>
    <path fill="#FBBC05" d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"/>
    <path fill="#EA4335" d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"/>
  </svg>
);

// Screen 2: Code verification — 6 digit inputs, auto-advance, auto-submit on full code.
function Screen_Code() {
  const s = useAppState();
  const digits = s.draft.code;
  const userEmail = s.user.email || "name@example.com";
  const verifyBusy = s.api?.pendingAction === "auth_verify";
  const refs = React.useRef([]);

  const setDigit = (i, v) => {
    window.actions.setCodeDigit(i, v);
    const cleaned = v.replace(/\D/g, "");
    if (cleaned && i < 5) refs.current[i + 1]?.focus();
    // Auto-submit when last digit filled.
    setTimeout(() => {
      const full = window.appState.draft.code.join("");
      if (full.length === 6) window.actions.submitCode();
    }, 0);
  };

  const onKeyDown = (i, e) => {
    if (e.key === "Backspace" && !digits[i] && i > 0) refs.current[i - 1]?.focus();
    if (e.key === "ArrowLeft" && i > 0) refs.current[i - 1]?.focus();
    if (e.key === "ArrowRight" && i < 5) refs.current[i + 1]?.focus();
  };

  const onPaste = (e) => {
    const pasted = (e.clipboardData.getData("text") || "").replace(/\D/g, "").slice(0, 6);
    if (!pasted) return;
    e.preventDefault();
    pasted.split("").forEach((ch, idx) => window.actions.setCodeDigit(idx, ch));
    setTimeout(() => {
      if (window.appState.draft.code.join("").length === 6) window.actions.submitCode();
    }, 0);
  };

  const onSubmit = (e) => { e.preventDefault(); window.actions.submitCode(); };
  const fmtTimer = (sec) => `${String(Math.floor(sec / 60)).padStart(2, "0")}:${String(sec % 60).padStart(2, "0")}`;

  return (
    <AuthShell screenLabel="02 Code">
      <h1 style={{ margin: 0, fontSize: 26, fontWeight: 800, letterSpacing: "-0.03em", color: "#FFF" }}>
        Введите код
      </h1>
      <p style={{ margin: "10px 0 24px", fontSize: 15, color: "var(--muted)", lineHeight: 1.55 }}>
        Код отправлен на <span style={{ color: "var(--ink)" }}>{userEmail}</span>. Проверьте почту, в т.ч. спам.
      </p>

      <form onSubmit={onSubmit}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6, minmax(0, 1fr))", gap: 8, marginBottom: 22 }}>
          {digits.map((d, i) => (
            <input
              key={i}
              ref={(el) => (refs.current[i] = el)}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={d}
              autoFocus={i === 0}
              onChange={(e) => setDigit(i, e.target.value)}
              onKeyDown={(e) => onKeyDown(i, e)}
              onPaste={onPaste}
              style={{
                width: "100%", minWidth: 0, padding: 0, boxSizing: "border-box",
                height: 56, borderRadius: 10,
                background: "var(--panel)",
                border: `1.5px solid ${d ? "var(--accent)" : "var(--border)"}`,
                textAlign: "center",
                fontSize: 24, fontWeight: 700, fontFamily: "ui-monospace, monospace",
                color: "var(--ink)",
                outline: "none",
              }}
            />
          ))}
        </div>

        <button type="submit" className="btn btn-primary btn-lg btn-block" disabled={verifyBusy} style={verifyBusy ? { opacity: 0.65, cursor: "wait" } : null}>
          {verifyBusy ? "Проверяем..." : "Войти"}
        </button>
      </form>

      <div style={{ marginTop: 16, fontSize: 13, color: "var(--muted)", textAlign: "center" }}>
        {s.codeResendIn > 0 ? (
          <>Получить новый код через <span style={{ color: "var(--ink)", fontVariantNumeric: "tabular-nums" }}>{fmtTimer(s.codeResendIn)}</span></>
        ) : (
          <a href="#" onClick={(e) => { e.preventDefault(); window.actions.resendCode(); }} style={{ color: "var(--accent-soft)", textDecoration: "none" }}>
            Получить код повторно
          </a>
        )}
      </div>

      <div style={{ marginTop: 18, textAlign: "center" }}>
        <a href="#" onClick={(e) => { e.preventDefault(); window.navigate("login"); }} style={{ fontSize: 13.5, color: "var(--accent-soft)", textDecoration: "none" }}>
          ← Изменить email
        </a>
      </div>
    </AuthShell>
  );
}

// Screen 4: New user empty dashboard.
// После оплаты подписка активируется автоматически по email.
// Ручной ввод кода не предусмотрен.
function Screen_NewUser() {
  const go = (r) => () => window.navigate(r);
  return (
    <Shell active="home" screenLabel="04 New user">
      <Hero pill={null} title="Оформите подписку" note="Одна подписка — до 3 подключений: V2Ray, Incy и (скоро) приложения для Android и iOS.">
      </Hero>

      <div style={{ marginTop: 12 }}>
        <PsCard onClick={go("keys-checkout")} style={{ cursor: "pointer" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <PsIcon icon={Icons.key} />
            <div style={{ flex: 1 }}>
              <h3 style={{ margin: "0 0 6px", fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>
                Подписка · 1 месяц
              </h3>
              <p style={{ margin: 0, fontSize: 15, color: "#9898AE", lineHeight: 1.6 }}>
                До 3 подключений · V2Ray и Incy · Android и iOS после релиза. 99 ₽ за 30 дней, без автопродления.
              </p>
            </div>
            <button className="btn btn-primary" onClick={(e) => { e.stopPropagation(); window.navigate("keys-checkout"); }}>Оформить</button>
          </div>
        </PsCard>
      </div>

      {/* Info: уже оплатил на сайте — подписка активируется автоматически */}
      <div style={{
        marginTop: 16,
        padding: "14px 18px",
        background: "rgba(46,168,255,.06)", border: "1px solid rgba(46,168,255,.22)",
        borderRadius: 12,
        display: "flex", gap: 12, alignItems: "flex-start",
      }}>
        <span style={{ color: "var(--accent-soft)", flexShrink: 0, marginTop: 2 }}><Icons.info /></span>
        <div style={{ fontSize: 13.5, color: "var(--ink)", lineHeight: 1.55 }}>
          <b style={{ color: "var(--accent-soft)" }}>Уже оплатили?</b> Подписка появится здесь через 1–2 минуты. Если статус не обновился, обновите страницу или напишите в поддержку.
        </div>
      </div>

      <div data-grid="cards" style={{ marginTop: 28, display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14, opacity: 0.7 }}>
        <SoonAppCard platform="Android" />
        <SoonAppCard platform="iOS" />
      </div>

      <div style={{ marginTop: 28, fontSize: 13.5, color: "var(--muted)", textAlign: "center" }}>
        Не уверены, что выбрать? <a href="https://fortunetavern.com/faq" target="_blank" rel="noopener" style={{ color: "var(--accent-soft)", textDecoration: "none" }}>FAQ →</a>
      </div>
    </Shell>
  );
}

// Small "скоро" card used in onboarding + dashboard
function SoonAppCard({ platform }) {
  // Единый текст для обеих платформ — чтобы на /home они выглядели как пара.
  const desc = "VPN в одной кнопке. Активируется автоматически по вашему email после релиза.";
  return (
    <div style={{
      padding: 22, borderRadius: 16, border: "1px solid var(--border)",
      background: "linear-gradient(180deg, rgba(255,255,255,0.025), rgba(255,255,255,0.005))",
      display: "flex", flexDirection: "column", gap: 10,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ width: 32, height: 32, borderRadius: 8, background: "rgba(162,172,184,.10)", border: "1px solid var(--border)", color: "var(--muted)", display: "grid", placeItems: "center" }}>
          {platform === "iOS" ? <Icons.apple /> : <Icons.android />}
        </div>
        <span style={{ fontWeight: 700, fontSize: 16, color: "var(--ink)" }}>{platform}-приложение</span>
        <span style={{ marginLeft: "auto", fontSize: 10, fontWeight: 700, letterSpacing: "0.03em", padding: "2px 7px", borderRadius: 999, background: "rgba(162,172,184,.18)", color: "var(--muted)" }}>скоро</span>
      </div>
      <div style={{ fontSize: 13.5, color: "var(--muted)", lineHeight: 1.55 }}>{desc}</div>
    </div>
  );
}

// Screen: /buy-start — email-capture, начало flow с лендинга.
// По WEB_SERVICE_ACCOUNT_FLOW_V2.md: новый email → создать ЛК+сессию (без письма),
// существующий email → «У вас уже есть аккаунт, войдите в ЛК».
function Screen_BuyStart() {
  const s = useAppState();
  const [email, setEmail] = React.useState("");
  const err = s.buyStart?.error;
  const errMsg = s.buyStart?.message;
  const buyStartBusy = s.api?.pendingAction === "web_account_start";
  const invite = s.referralInvite || {};
  const showInvite = !!(invite.loaded && invite.valid && invite.code);

  React.useEffect(() => {
    if (invite.code && !invite.loaded && !invite.loading && window.actions?.loadReferralInvite) {
      window.actions.loadReferralInvite();
    }
  }, [invite.code, invite.loaded, invite.loading]);

  const onSubmit = (e) => {
    e.preventDefault();
    window.actions.startBuyFlow(email);
  };
  const onChange = (e) => {
    setEmail(e.target.value);
    if (err) window.actions.resetBuyStart();
  };

  return (
    <AuthShell screenLabel="Buy · email capture">
      <h1 style={{ margin: 0, fontSize: 26, fontWeight: 800, letterSpacing: "-0.03em", color: "#FFF" }}>
        Оформите подписку
      </h1>
      <p style={{ margin: "10px 0 24px", fontSize: 15, color: "var(--muted)", lineHeight: 1.55 }}>
        Введите email — откроем для вас личный кабинет, где вы оплатите подписку. Подтверждать почту не нужно.
      </p>

      {showInvite && (
        <div style={{
          padding: "12px 14px",
          borderRadius: 12,
          marginBottom: 16,
          background: "rgba(46,168,255,.08)",
          border: "1px solid rgba(46,168,255,.28)",
          display: "flex",
          gap: 10,
          alignItems: "flex-start",
          fontSize: 13.5,
          color: "var(--ink)",
          lineHeight: 1.5,
        }}>
          <span style={{ color: "var(--accent-soft)", flexShrink: 0, marginTop: 1 }}><Icons.users size={16} /></span>
          <div>
            <b>{invite.inviter?.email_masked ? `Вас пригласил ${invite.inviter.email_masked}` : "Вы пришли по приглашению Fortune VPN"}</b>
            <div style={{ color: "var(--muted)", marginTop: 4 }}>
              После подтверждения первой реальной оплаты вы оба получите +{Number(invite.reward_days || 10)} дней.
            </div>
          </div>
        </div>
      )}
      {!showInvite && invite.loaded && invite.error && (
        <div style={{
          padding: "10px 12px",
          borderRadius: 10,
          marginBottom: 14,
          background: "rgba(245,166,35,.08)",
          border: "1px solid rgba(245,166,35,.24)",
          color: "var(--muted)",
          fontSize: 13,
          lineHeight: 1.45,
        }}>
          Не удалось проверить приглашение. Можно продолжить регистрацию; если бонус не появится после оплаты, напишите в поддержку.
        </div>
      )}

      <form onSubmit={onSubmit}>
        <div className="field" style={{ marginBottom: 14 }}>
          <label className="field-label">Email</label>
          <input
            type="email"
            inputMode="email"
            autoFocus
            value={email}
            onChange={onChange}
            placeholder="name@example.com"
            className={`field-input ${err ? "err" : ""}`}
            style={{ width: "100%", fontSize: 15 }}
          />
        </div>

        {err === "account_exists" && (
          <div style={{
            padding: "12px 14px", borderRadius: 10, marginBottom: 14,
            background: "rgba(245,166,35,.10)", border: "1px solid rgba(245,166,35,.30)",
            display: "flex", gap: 10, alignItems: "flex-start",
            fontSize: 13.5, color: "var(--ink)", lineHeight: 1.5,
          }}>
            <span style={{ color: "var(--warning)", flexShrink: 0, marginTop: 1 }}><Icons.info size={16} /></span>
            <div>
              {errMsg || "У вас уже есть аккаунт, войдите в ЛК"}
              <div style={{ marginTop: 8 }}>
                <a href="#" onClick={(e) => { e.preventDefault(); window.actions.resetBuyStart(); window.navigate("login"); }} style={{ color: "var(--accent-soft)", textDecoration: "none" }}>
                  Войти в кабинет →
                </a>
              </div>
            </div>
          </div>
        )}

        <button type="submit" className="btn btn-primary btn-lg btn-block" disabled={buyStartBusy} style={buyStartBusy ? { opacity: 0.65, cursor: "wait" } : null}>
          {buyStartBusy ? "Создаем кабинет..." : "Продолжить"}
        </button>
      </form>

      <div style={{ marginTop: 18, fontSize: 13, color: "var(--muted)", textAlign: "center" }}>
        Уже есть аккаунт?{" "}
        <a href="#" onClick={(e) => { e.preventDefault(); window.navigate("login"); }} style={{ color: "var(--accent-soft)", textDecoration: "none" }}>
          Войти
        </a>
      </div>

      <div style={{ marginTop: 14, fontSize: 12.5, color: "var(--dim)", textAlign: "center", lineHeight: 1.6 }}>
        Возникли проблемы? Напишите в <a href="https://t.me/FortuneVPNsupportbot" target="_blank" rel="noopener" style={{ color: "var(--accent-soft)", textDecoration: "none" }}>@FortuneVPNsupportbot</a> или на <a href="mailto:support@fortunetavern.com" style={{ color: "var(--accent-soft)", textDecoration: "none" }}>support@fortunetavern.com</a>
      </div>
    </AuthShell>
  );
}

Object.assign(window, { Screen_Login, Screen_Code, Screen_NewUser, Screen_BuyStart, SoonAppCard });
