// login.jsx — Вход через email-код или Telegram. Зависит от api.jsx, icons.jsx, data.jsx.
const { useState, useRef, useEffect } = React;
const LIcon = window.Icon;
const limg = window.FL_imgUrl;
const LoginAPI = window.FL_API;

function Logo() {
  const gradientId = React.useId().replace(/:/g, "");
  return (
    <span className="inline-flex items-center gap-2.5 select-none shrink-0">
      <svg className="shrink-0" width="34" height="34" viewBox="0 0 48 48" fill="none">
        <defs><linearGradient id={gradientId} x1="0" y1="0" x2="48" y2="48"><stop offset="0" stopColor="#F2682F" /><stop offset="1" stopColor="#F5A623" /></linearGradient></defs>
        <g transform="rotate(180 24 24)">
          <path d="M24 24c-4-5-10-6-13-3s-2 9 1 11 8-1 12-8c4 7 9 10 12 8s4-8 1-11-9-2-13 3Z" stroke={`url(#${gradientId})`} strokeWidth="2.6" fill="none" />
          <path d="M24 12l3.5 12h-7Z" fill="#F2682F" /><path d="M24 36l-3.5-12h7Z" fill="#F2682F" />
          <circle cx="24" cy="24" r="2.6" fill="#221A15" />
        </g>
      </svg>
      <span className="font-display font-bold leading-none tracking-[-0.02em] text-[22px] whitespace-nowrap">Файнд<span className="text-coral-500">ли</span></span>
    </span>
  );
}

function LoginNotice({ error }) {
  if (!error) return null;
  return (
    <div role="alert" className="mb-5 rounded-2xl bg-rose-500/10 text-rose-600 ring-1 ring-rose-500/25 px-4 py-3 text-[13.5px] font-semibold leading-snug">
      {error}
    </div>
  );
}

function TelegramLogin({ onAuth, onError, enabled, busy }) {
  const hostRef = useRef(null);
  const mountRef = useRef(null);
  const [status, setStatus] = useState("loading");

  useEffect(() => {
    let cancelled = false;
    LoginAPI.mountTelegramLogin(hostRef.current, onAuth).then((mount) => {
      if (cancelled) return mount.destroy();
      mountRef.current = mount;
      setStatus(mount.configured ? "ready" : "missing");
    }).catch(() => {
      if (!cancelled) {
        setStatus("error");
        onError("Не удалось загрузить вход через Telegram");
      }
    });
    return () => {
      cancelled = true;
      mountRef.current?.destroy();
    };
  }, []);

  const available = enabled && status === "ready";

  return (
    <div className="relative min-h-[48px] w-full flex justify-start">
      <div
        ref={hostRef}
        className={available
          ? "w-full max-w-[332px] min-h-[48px] rounded-[14px] bg-white/70 dark:bg-white/[0.07] ring-1 ring-[#229ED9]/20 flex items-center justify-center px-3 " + (busy ? "pointer-events-none opacity-60" : "")
          : "hidden"}
      />
      {!available && (
        <button
          type="button"
          onClick={() => onError(
            status === "error"
              ? "Вход через Telegram временно недоступен."
              : "Вход через Telegram заработает после подключения бота."
          )}
          className="group w-full max-w-[332px] h-12 rounded-[14px] bg-white/70 dark:bg-white/[0.07] ring-1 ring-black/[0.08] dark:ring-white/10 shadow-[0_4px_14px_rgba(34,26,21,0.04)] hover:ring-[#229ED9]/35 hover:bg-[#229ED9]/[0.055] hover:-translate-y-px transition inline-flex items-center justify-center px-3 sm:px-4"
        >
          <span className="grid grid-cols-[32px_minmax(0,1fr)] items-center gap-2 sm:gap-3 w-full max-w-[232px] min-w-0 text-left">
            <span className="grid place-items-center w-8 h-8">
              {status === "loading"
                ? <span className="w-5 h-5 rounded-full border-2 border-[#229ED9] border-t-transparent animate-spin" />
                : <LIcon name="telegramBrand" className="w-[23px] h-[23px] text-[#229ED9]" />}
            </span>
            <span className="min-w-0 text-[14px] font-bold text-[var(--ink)] whitespace-nowrap">Войти через Telegram</span>
          </span>
        </button>
      )}
    </div>
  );
}

function App() {
  const requestedNext = new URLSearchParams(location.search).get("next") || "";
  const nextPage = /^\/?[^:/\\]+\.html(?:[?#].*)?$/u.test(requestedNext) ? requestedNext : "/";
  const [phase, setPhase] = useState("start"); // start | developer | email | code | done
  const [loginConfig, setLoginConfig] = useState({
    loaded: false,
    publicLoginEnabled: false,
    emailLoginEnabled: false,
    telegramLoginEnabled: false,
    developerLoginEnabled: true,
  });
  const [developerName, setDeveloperName] = useState("");
  const [developerPassword, setDeveloperPassword] = useState("");
  const [developerPasswordVisible, setDeveloperPasswordVisible] = useState(false);
  const [email, setEmail] = useState("");
  const [code, setCode] = useState(["","","","","",""]);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [devCode, setDevCode] = useState("");
  const [resendIn, setResendIn] = useState(0);
  const codeRefs = useRef([]);
  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const codeValid = code.every(Boolean);
  const developerValid = developerName.trim().length >= 3 && developerPassword.length >= 12;

  useEffect(() => {
    let cancelled = false;
    Promise.allSettled([LoginAPI.me(), LoginAPI.config()]).then(([userResult, configResult]) => {
      if (cancelled) return;
      if (userResult.status === "fulfilled" && userResult.value) {
        setPhase("done");
        return;
      }
      if (configResult.status === "fulfilled") {
        const legacyPublicLoginEnabled = Boolean(configResult.value?.publicLoginEnabled);
        setLoginConfig({
          loaded: true,
          publicLoginEnabled: legacyPublicLoginEnabled,
          emailLoginEnabled:
            configResult.value?.emailLoginEnabled === undefined
              ? legacyPublicLoginEnabled
              : Boolean(configResult.value.emailLoginEnabled),
          telegramLoginEnabled:
            configResult.value?.telegramLoginEnabled === undefined
              ? legacyPublicLoginEnabled
              : Boolean(configResult.value.telegramLoginEnabled),
          developerLoginEnabled: Boolean(configResult.value?.developerLoginEnabled),
        });
      } else {
        setLoginConfig((current) => ({ ...current, loaded: true }));
      }
    });
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    if (phase !== "done") return;
    const timer = setTimeout(() => { location.href = nextPage; }, 900);
    return () => clearTimeout(timer);
  }, [phase]);

  useEffect(() => {
    if (resendIn <= 0) return;
    const timer = setTimeout(() => setResendIn((value) => value - 1), 1000);
    return () => clearTimeout(timer);
  }, [resendIn]);

  const onCode = (index, value) => {
    const digits = value.replace(/\D/g, "");
    if (digits.length > 1) {
      const next = [...code];
      digits.slice(0, 6).split("").forEach((digit, offset) => {
        if (index + offset < 6) next[index + offset] = digit;
      });
      setCode(next);
      codeRefs.current[Math.min(index + digits.length, 5)]?.focus();
      return;
    }
    setCode((current) => {
      const next = [...current];
      next[index] = digits;
      return next;
    });
    if (digits && index < 5) codeRefs.current[index + 1]?.focus();
  };

  const requestCode = async () => {
    if (!emailValid || busy) return;
    setBusy(true);
    setError("");
    try {
      const result = await LoginAPI.requestEmailCode(email);
      setEmail(email.trim().toLowerCase());
      setCode(["","","","","",""]);
      setDevCode(result?.devCode || "");
      setResendIn(30);
      setPhase("code");
      setTimeout(() => codeRefs.current[0]?.focus(), 30);
    } catch (requestError) {
      setError(requestError.message);
    } finally {
      setBusy(false);
    }
  };

  const verifyCode = async () => {
    if (!codeValid || busy) return;
    setBusy(true);
    setError("");
    try {
      await LoginAPI.verifyEmailCode(email, code.join(""));
      setPhase("done");
    } catch (requestError) {
      setError(requestError.message);
    } finally {
      setBusy(false);
    }
  };

  const telegramAuth = async (telegramUser) => {
    if (busy) return;
    setBusy(true);
    setError("");
    try {
      await LoginAPI.telegramLogin(telegramUser);
      setPhase("done");
    } catch (requestError) {
      setError(requestError.message);
    } finally {
      setBusy(false);
    }
  };

  const developerAuth = async (event) => {
    event?.preventDefault();
    if (!developerValid || busy) return;
    setBusy(true);
    setError("");
    try {
      await LoginAPI.developerLogin(developerName, developerPassword);
      setDeveloperPassword("");
      setPhase("done");
    } catch (requestError) {
      setError(requestError.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="min-h-screen bg-[var(--paper)] text-[var(--ink)] lg:grid lg:grid-cols-2">
      {/* мобильная обложка */}
      <div className="relative h-[220px] sm:h-[280px] lg:hidden overflow-hidden">
        <img src={limg(window.FL_HERO_IMG, 1000, 700)} alt="" className="absolute inset-0 w-full h-full object-cover object-[center_38%]" />
        <div className="absolute inset-0 mix-blend-overlay opacity-35" style={{ background:"linear-gradient(150deg,#F2682F,#FB6F84 70%,#F5A623)" }} />
        <div className="absolute inset-0" style={{ background:"linear-gradient(180deg, rgba(18,13,9,.18), rgba(18,13,9,.5))" }} />
      </div>

      {/* левая — бренд */}
      <div className="relative hidden lg:flex flex-col justify-between p-12 overflow-hidden text-white">
        <img src={limg(window.FL_HERO_IMG, 1200, 1600)} alt="" className="absolute inset-0 w-full h-full object-cover" />
        <div className="absolute inset-0 mix-blend-overlay opacity-40" style={{ background:"linear-gradient(150deg,#F2682F,#FB6F84 70%,#F5A623)" }} />
        <div className="absolute inset-0" style={{ background:"linear-gradient(120deg, rgba(18,13,9,.92), rgba(18,13,9,.5) 70%, rgba(18,13,9,.7))" }} />
        <div className="relative"><Logo /></div>
        <div className="relative">
          <h1 className="font-display text-[36px] xl:text-[40px] font-extrabold leading-[1.05]">
            <span className="block">Место, где планы</span>
            <span className="block text-coral-400">находят людей</span>
          </h1>
          <p className="text-[16px] text-white/80 mt-4 max-w-[420px]">Выбирай события от людей рядом или создавай свои — чтобы находить компанию и встречаться вживую.</p>
          <div className="flex flex-col gap-3 mt-8">
            {[["users","Люди с похожими интересами"],["shield","Верификация и рейтинг участников"],["pin","События в твоём городе и рядом"]].map(([ic,t])=>(
              <div key={t} className="flex items-center gap-3 text-[14.5px] text-white/90"><span className="grid place-items-center w-9 h-9 rounded-xl bg-white/12 backdrop-blur"><LIcon name={ic} className="w-5 h-5" stroke={2} /></span>{t}</div>
            ))}
          </div>
        </div>
        <div className="relative text-[12.5px] text-white/50">© Файндли</div>
      </div>

      {/* правая — вход */}
      <div className="flex flex-col items-center justify-center p-6 md:p-12">
        <div className="w-full max-w-[400px]">
          <div className="lg:hidden mb-8 flex justify-center"><Logo /></div>

          {phase==="developer" && (
            <form onSubmit={developerAuth} className="fl-rise">
              <h2 className="font-display text-[26px] font-extrabold">Вход в Файндли</h2>
              <div className="mt-6"><LoginNotice error={error} /></div>
              <label className="block text-[12px] font-extrabold uppercase tracking-[.1em] text-[var(--mute)] mb-2" htmlFor="developer-login">Логин</label>
              <input
                id="developer-login"
                autoFocus
                autoComplete="username"
                autoCapitalize="none"
                spellCheck={false}
                value={developerName}
                onChange={event=>setDeveloperName(event.target.value)}
                className="w-full rounded-2xl bg-black/[0.04] dark:bg-white/[0.07] px-4 py-4 text-[16px] font-semibold outline-none focus:ring-2 ring-coral-400 text-left"
              />
              <label className="block text-[12px] font-extrabold uppercase tracking-[.1em] text-[var(--mute)] mt-5 mb-2" htmlFor="developer-password">Пароль</label>
              <div className="relative">
                <input
                  id="developer-password"
                  type={developerPasswordVisible ? "text" : "password"}
                  autoComplete="current-password"
                  value={developerPassword}
                  onChange={event=>setDeveloperPassword(event.target.value)}
                  className="w-full rounded-2xl bg-black/[0.04] dark:bg-white/[0.07] pl-4 pr-14 py-4 text-[16px] font-semibold outline-none focus:ring-2 ring-coral-400 text-left"
                />
                <button
                  type="button"
                  onClick={()=>setDeveloperPasswordVisible((visible)=>!visible)}
                  aria-label={developerPasswordVisible ? "Скрыть пароль" : "Показать пароль"}
                  aria-pressed={developerPasswordVisible}
                  className={"absolute inset-y-0 right-1.5 my-auto grid place-items-center w-11 h-11 rounded-xl transition " + (developerPasswordVisible ? "text-coral-600 bg-coral-500/10" : "text-[var(--mute)] hover:text-[var(--ink)] hover:bg-black/[0.04]")}
                >
                  <LIcon name="eye" className="w-5 h-5" />
                </button>
              </div>
              <button type="submit" disabled={!developerValid||busy} className="w-full mt-6 py-3.5 rounded-2xl text-[15px] font-bold text-white bg-coral-500 hover:bg-coral-600 disabled:opacity-40 transition">
                {busy ? "Проверяем…" : "Войти"}
              </button>
              <button
                type="button"
                onClick={()=>{ setError(""); setPhase("start"); }}
                className="w-full mt-5 text-[13.5px] font-semibold text-[var(--mute)] hover:text-[var(--ink)] transition"
              >
                Войти другим способом
              </button>
            </form>
          )}

          {phase==="start" && (
            <div className="fl-rise">
              <h2 className="font-display text-[26px] font-extrabold">Вход в Файндли</h2>
              <p className="text-[14.5px] text-[var(--mute)] mt-2 mb-7">Выбери удобный способ.</p>
              <LoginNotice error={error} />
              <div className="flex flex-col items-start gap-2.5">
                <button
                  type="button"
                  onClick={()=>{
                    setError("");
                    if (!loginConfig.loaded) return;
                    if (!loginConfig.emailLoginEnabled) {
                      setError("Вход по email заработает после подключения почтового сервиса.");
                      return;
                    }
                    setPhase("email");
                  }}
                  className="group w-full max-w-[332px] h-12 rounded-[14px] bg-white/70 dark:bg-white/[0.07] ring-1 ring-black/[0.08] dark:ring-white/10 shadow-[0_4px_14px_rgba(34,26,21,0.04)] hover:ring-coral-400/35 hover:bg-coral-500/[0.035] hover:-translate-y-px transition inline-flex items-center justify-center px-3 sm:px-4"
                >
                  <span className="grid grid-cols-[32px_minmax(0,1fr)] items-center gap-2 sm:gap-3 w-full max-w-[232px] min-w-0 text-left">
                    <span className="grid place-items-center w-8 h-8 rounded-[10px] bg-coral-500/10 text-coral-600">
                      <LIcon name="mail" className="w-[18px] h-[18px]" stroke={1.9} />
                    </span>
                    <span className="min-w-0 text-[14px] font-bold text-[var(--ink)] whitespace-nowrap">Войти по email</span>
                  </span>
                </button>
                <TelegramLogin
                  onAuth={telegramAuth}
                  onError={setError}
                  enabled={loginConfig.telegramLoginEnabled}
                  busy={busy}
                />
              </div>
              {loginConfig.developerLoginEnabled && (
                <button
                  type="button"
                  onClick={()=>{ setError(""); setPhase("developer"); }}
                  className="w-full max-w-[332px] mt-6 text-[13.5px] font-semibold text-[var(--mute)] hover:text-[var(--ink)] transition"
                >
                  Войти с паролем
                </button>
              )}
              <p className="w-full max-w-[332px] text-[12px] text-[var(--mute)] text-center mt-5 leading-relaxed">Продолжая, ты соглашаешься с правилами сообщества и политикой конфиденциальности.</p>
            </div>
          )}

          {phase==="email" && (
            <div className="fl-rise">
              <button onClick={()=>setPhase("start")} className="inline-flex items-center gap-1.5 text-[13.5px] font-semibold text-[var(--mute)] mb-5 hover:text-[var(--ink)]"><LIcon name="chevronLeft" className="w-4 h-4" />Назад</button>
              <h2 className="font-display text-[24px] font-extrabold">Твоя почта</h2>
              <p className="text-[14px] text-[var(--mute)] mt-1.5 mb-6">Отправим шестизначный код. Пароль не нужен.</p>
              <LoginNotice error={error} />
              <input autoFocus inputMode="email" autoComplete="email" value={email} onChange={event=>setEmail(event.target.value)} onKeyDown={event=>{ if(event.key==="Enter") requestCode(); }} placeholder="name@example.ru"
                className="w-full rounded-2xl bg-black/[0.04] dark:bg-white/[0.07] px-4 py-4 text-[16px] font-semibold outline-none focus:ring-2 ring-coral-400 text-left" />
              <button onClick={requestCode} disabled={!emailValid||busy} className="w-full mt-5 py-3.5 rounded-2xl text-[15px] font-bold text-white bg-coral-500 hover:bg-coral-600 disabled:opacity-40 transition">{busy ? "Отправляем…" : "Получить код"}</button>
            </div>
          )}

          {phase==="code" && (
            <div className="fl-rise">
              <button onClick={()=>{ setError(""); setPhase("email"); }} className="inline-flex items-center gap-1.5 text-[13.5px] font-semibold text-[var(--mute)] mb-5 hover:text-[var(--ink)]"><LIcon name="chevronLeft" className="w-4 h-4" />Назад</button>
              <h2 className="font-display text-[24px] font-extrabold">Введи код</h2>
              <p className="text-[14px] text-[var(--mute)] mt-1.5 mb-6">Отправили на <span className="font-semibold text-[var(--ink)] break-all">{email}</span>.</p>
              <LoginNotice error={error} />
              {devCode && <div className="mb-4 rounded-xl bg-teal-500/10 text-teal-600 px-3 py-2 text-[12.5px]">Код для локальной разработки: <b className="font-mono">{devCode}</b></div>}
              <div className="grid grid-cols-6 gap-1.5 sm:gap-2.5">
                {code.map((c,i)=>(
                  <input key={i} ref={el=>codeRefs.current[i]=el} value={c} onChange={e=>onCode(i,e.target.value)} onKeyDown={e=>{ if(e.key==="Backspace"&&!c&&i>0) codeRefs.current[i-1]?.focus(); if(e.key==="Enter") verifyCode(); }}
                    inputMode="numeric" autoComplete={i===0 ? "one-time-code" : "off"} maxLength={6} aria-label={`Цифра ${i+1}`} className="w-full aspect-square rounded-xl sm:rounded-2xl bg-black/[0.04] dark:bg-white/[0.07] text-center text-[20px] sm:text-[24px] font-bold outline-none focus:ring-2 ring-coral-400" />
                ))}
              </div>
              <button onClick={verifyCode} disabled={!codeValid||busy} className="w-full mt-6 py-3.5 rounded-2xl text-[15px] font-bold text-white bg-coral-500 hover:bg-coral-600 disabled:opacity-40 transition">{busy ? "Проверяем…" : "Войти"}</button>
              <button onClick={requestCode} disabled={busy||resendIn>0} className="w-full mt-3 text-[13px] font-semibold text-[var(--mute)] hover:text-[var(--ink)] disabled:opacity-50">{resendIn>0 ? `Отправить повторно через ${resendIn} сек.` : "Отправить код повторно"}</button>
            </div>
          )}

          {phase==="done" && (
            <div className="fl-rise text-center">
              <div className="grid place-items-center w-20 h-20 rounded-3xl bg-teal-500/15 text-teal-600 mx-auto mb-5"><LIcon name="check" className="w-10 h-10" stroke={2.4} /></div>
              <h2 className="font-display text-[26px] font-extrabold">Добро пожаловать!</h2>
              <p className="text-[14.5px] text-[var(--mute)] mt-2">Открываем ленту событий…</p>
              <div className="mt-6 flex justify-center"><span className="w-6 h-6 rounded-full border-2 border-coral-500 border-t-transparent animate-spin" /></div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
