import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  ArrowRight,
  Code2,
  Expand,
  Filter,
  Inbox,
  ListVideo,
  Lock,
  PlayCircle,
  Search,
  X,
  type LucideIcon,
} from "lucide-react";

// Siftlode is open source; the landing footer links to the public repository.
const REPO_URL = "https://forge.b1fr0st.eu/peter/siftlode";
import { api } from "../lib/api";
import { HttpError } from "../lib/api";
import { setLanguage, type LangCode } from "../i18n";
import LanguageSwitcher from "./LanguageSwitcher";

const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
const PASSWORD_MIN = 10;

type Mode = "signin" | "register" | "forgot" | "reset";

// Public landing + authentication. One scrollable page: a hero with the auth card (email+
// password, Google, explicit demo) over a short marketing pitch with feature cards. Shown
// whenever the user isn't signed in (see App.tsx). The auth forms talk to /auth/* (see the
// backend); errors are surfaced inline (the api calls use the quiet flag).
export default function Welcome() {
  const { t, i18n } = useTranslation();
  // Which screenshot (if any) is open in the full-size lightbox.
  const [zoomed, setZoomed] = useState<{ src: string; label: string } | null>(null);
  const open = (src: string, label: string) => setZoomed({ src, label });
  return (
    <div className="min-h-screen bg-bg text-fg overflow-y-auto">
      <header className="flex items-center justify-between px-5 sm:px-8 py-4">
        <div className="text-xl font-bold tracking-tight">
          Sift<span className="text-accent">lode</span>
        </div>
        <LanguageSwitcher value={i18n.language as LangCode} onChange={setLanguage} />
      </header>

      <main className="max-w-6xl mx-auto px-5 sm:px-8 pb-16">
        {/* Hero: pitch + auth card */}
        <section className="grid lg:grid-cols-2 gap-10 items-center py-8 lg:py-14">
          <div className="max-w-xl">
            <h1 className="text-3xl sm:text-4xl font-bold tracking-tight leading-tight">
              {t("welcome.hero.title")}
            </h1>
            <p className="text-muted mt-4 text-lg leading-relaxed">{t("welcome.hero.subtitle")}</p>
            <p className="text-sm text-muted mt-4">{t("welcome.hero.trust")}</p>
          </div>
          <AuthCard />
        </section>

        {/* App preview */}
        <Preview
          src="/welcome/feed.webp"
          label={t("welcome.preview.feed")}
          className="aspect-video"
          onOpen={open}
        />

        {/* Open source — Siftlode's code is public; nudge visitors to read it or self-host. The
            footer keeps a compact link too. */}
        <a
          href={REPO_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="group mt-8 flex flex-col items-center gap-x-4 gap-y-2 rounded-2xl border border-accent/25 bg-accent/[0.06] px-5 py-4 text-center sm:flex-row sm:text-left hover:border-accent/50 transition"
        >
          <span className="grid place-items-center w-10 h-10 rounded-xl bg-accent/15 text-accent shrink-0">
            <Code2 className="w-5 h-5" />
          </span>
          <span className="flex-1">
            <span className="block font-semibold">{t("welcome.openSource.title")}</span>
            <span className="block text-sm text-muted leading-relaxed">
              {t("welcome.openSource.body")}
            </span>
          </span>
          <span className="inline-flex items-center gap-1 text-sm font-medium text-accent whitespace-nowrap">
            {t("welcome.openSource.link")}
            <ArrowRight className="w-4 h-4 transition group-hover:translate-x-0.5" />
          </span>
        </a>

        {/* Features */}
        <section className="mt-14">
          <h2 className="text-2xl font-semibold text-center">{t("welcome.features.heading")}</h2>
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-8">
            {FEATURES.map((f) => (
              <FeatureCard key={f.key} icon={f.icon} k={f.key} />
            ))}
          </div>
        </section>

        {/* Secondary showcase — smaller thumbnails; click to view full size. */}
        <section className="mt-12 flex flex-wrap justify-center gap-4">
          <Preview
            src="/welcome/channels.webp"
            label={t("welcome.preview.channels")}
            className="w-full sm:w-72 aspect-[4/3]"
            onOpen={open}
          />
          <Preview
            src="/welcome/playlists.webp"
            label={t("welcome.preview.playlists")}
            className="w-full sm:w-72 aspect-[4/3]"
            onOpen={open}
          />
        </section>
      </main>

      {zoomed && (
        <Lightbox src={zoomed.src} label={zoomed.label} onClose={() => setZoomed(null)} />
      )}

      <footer className="border-t border-border py-6 text-center text-xs text-muted flex flex-col sm:flex-row gap-3 justify-center items-center">
        <span>
          Sift<span className="text-accent">lode</span>
        </span>
        <span className="hidden sm:inline">·</span>
        <a href="/privacy" className="hover:text-fg transition">
          {t("common.privacyPolicy")}
        </a>
        <a href="/terms" className="hover:text-fg transition">
          {t("common.termsOfService")}
        </a>
        <a
          href={REPO_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-1.5 hover:text-fg transition"
        >
          <Code2 className="w-3.5 h-3.5" />
          {t("common.sourceCode")}
        </a>
      </footer>
    </div>
  );
}

const FEATURES: { key: string; icon: LucideIcon }[] = [
  { key: "readable", icon: Filter },
  { key: "neverMiss", icon: Inbox },
  { key: "search", icon: Search },
  { key: "playlists", icon: ListVideo },
  { key: "player", icon: PlayCircle },
  { key: "private", icon: Lock },
];

function FeatureCard({ icon: Icon, k }: { icon: LucideIcon; k: string }) {
  const { t } = useTranslation();
  return (
    <div className="glass-card rounded-2xl p-5">
      <div className="w-10 h-10 rounded-xl bg-accent/15 text-accent grid place-items-center mb-3">
        <Icon className="w-5 h-5" />
      </div>
      <h3 className="font-semibold">{t(`welcome.features.${k}.title`)}</h3>
      <p className="text-sm text-muted leading-relaxed mt-1">{t(`welcome.features.${k}.body`)}</p>
    </div>
  );
}

// Image with a graceful fallback: if the file isn't present yet, show a tasteful placeholder
// frame instead of a broken image (the demo screenshots drop into frontend/public/welcome/).
// When loaded it's a button that opens the full-size lightbox (onOpen).
function Preview({
  src,
  label,
  className,
  onOpen,
}: {
  src: string;
  label: string;
  className?: string;
  onOpen?: (src: string, label: string) => void;
}) {
  const [failed, setFailed] = useState(false);
  if (failed) {
    return (
      <div className={`glass-card rounded-2xl overflow-hidden ${className ?? ""}`}>
        <div className="w-full h-full grid place-items-center bg-gradient-to-br from-accent/10 to-card text-muted text-sm p-6 text-center">
          {label}
        </div>
      </div>
    );
  }
  return (
    <button
      type="button"
      onClick={() => onOpen?.(src, label)}
      aria-label={label}
      className={`group relative glass-card rounded-2xl overflow-hidden block cursor-zoom-in ${className ?? ""}`}
    >
      <img
        src={src}
        alt={label}
        loading="lazy"
        onError={() => setFailed(true)}
        className="w-full h-full object-cover object-top"
      />
      <span className="absolute inset-0 grid place-items-center bg-black/0 opacity-0 transition group-hover:bg-black/30 group-hover:opacity-100">
        <Expand className="w-6 h-6 text-white drop-shadow-lg" />
      </span>
    </button>
  );
}

// Full-size image viewer: a dimmed, blurred backdrop with the screenshot fit to the viewport
// (aspect ratio preserved via object-contain). Closes on backdrop click, the ✕, or Escape.
function Lightbox({ src, label, onClose }: { src: string; label: string; onClose: () => void }) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden"; // no background scroll while open
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [onClose]);
  return (
    <div
      className="fixed inset-0 z-[60] grid place-items-center bg-black/80 backdrop-blur-sm p-4 sm:p-8"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-label={label}
    >
      <button
        type="button"
        onClick={onClose}
        aria-label="Close"
        className="absolute top-4 right-4 p-2 rounded-full glass-card glass-hover text-fg"
      >
        <X className="w-5 h-5" />
      </button>
      <figure
        className="flex max-h-full max-w-full flex-col items-center gap-3"
        onClick={(e) => e.stopPropagation()}
      >
        <img
          src={src}
          alt={label}
          className="max-h-[82vh] max-w-[92vw] w-auto h-auto rounded-xl border border-border object-contain shadow-2xl"
        />
        <figcaption className="text-sm text-muted">{label}</figcaption>
      </figure>
    </div>
  );
}

function AuthCard() {
  const { t } = useTranslation();
  // Snapshot the pre-login params ONCE (query + fragment) so we can clean the address bar below
  // without dismissing the banners/reset-mode they drive. Secret tokens (reset, verify) ride the
  // URL FRAGMENT so they never reach the server / proxy logs / Referer (SB3); plain status flags
  // stay in the query string.
  const [params] = useState(() => new URLSearchParams(window.location.search));
  const [hashParams] = useState(() => new URLSearchParams(window.location.hash.replace(/^#/, "")));
  const resetToken = hashParams.get("reset");
  const verifyToken = hashParams.get("verify"); // raw token → POST to confirm (new flow)
  const bounced = params.get("access"); // Google denied → "requested" | "denied"
  const login = params.get("login"); // Google login blocked → "suspended"
  const deleted = params.get("deleted"); // self-service account deletion just completed
  // Verification outcome: from POSTing the fragment token (new flow), or the legacy
  // ?verify=ok|invalid redirect (pre-SB3 emails still in flight).
  const [verify, setVerify] = useState<string | null>(() => params.get("verify"));

  // Strip BOTH the query string and the fragment so the address bar stays clean and the token
  // doesn't linger in history.
  useEffect(() => {
    if (window.location.search || window.location.hash) {
      window.history.replaceState(null, "", window.location.pathname);
    }
  }, []);

  // Confirm a fragment verification token by POSTing it (new SB3 flow). Fire ONCE: the token is
  // single-use, so a double POST (StrictMode remount / any re-render) would 400 on the second call
  // and wrongly flip the banner to "invalid".
  const verifyFired = useRef(false);
  useEffect(() => {
    if (!verifyToken || verifyFired.current) return;
    verifyFired.current = true;
    api
      .verifyEmail(verifyToken)
      .then(() => setVerify("ok"))
      .catch(() => setVerify("invalid"));
  }, [verifyToken]);

  const [mode, setMode] = useState<Mode>(resetToken ? "reset" : "signin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  // Whether to offer "Continue with Google" — hidden when the instance has no Google OAuth
  // configured. Optimistic (most instances have it); the rare Google-less instance just sees it
  // disappear once the config loads.
  const [googleEnabled, setGoogleEnabled] = useState(true);
  useEffect(() => {
    api.authConfig().then((c) => setGoogleEnabled(c.google_enabled)).catch(() => {});
  }, []);
  const [done, setDone] = useState<string>(""); // success/info message replacing the form

  // Explicit demo entry (replaces the old hidden probe): a labelled email field, still gated
  // by the demo whitelist server-side.
  const [showDemo, setShowDemo] = useState(false);
  const [demoEmail, setDemoEmail] = useState("");
  const [demoBusy, setDemoBusy] = useState(false);
  const [demoError, setDemoError] = useState("");

  const reset = () => {
    setError("");
    setDone("");
  };

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    reset();
    const mail = email.trim().toLowerCase();
    if ((mode === "signin" || mode === "register" || mode === "forgot") && !EMAIL_RE.test(mail)) {
      setError(t("welcome.auth.invalidEmail"));
      return;
    }
    if ((mode === "register" || mode === "reset") && password.length < PASSWORD_MIN) {
      setError(t("welcome.auth.weakPassword", { min: PASSWORD_MIN }));
      return;
    }
    setBusy(true);
    try {
      if (mode === "signin") {
        await api.passwordLogin(mail, password);
        window.location.reload();
        return;
      }
      if (mode === "register") {
        await api.register(mail, password);
        setDone(t("welcome.auth.registerDone"));
      } else if (mode === "forgot") {
        await api.requestPasswordReset(mail);
        setDone(t("welcome.auth.forgotDone"));
      } else if (mode === "reset") {
        await api.confirmPasswordReset(resetToken ?? "", password);
        setDone(t("welcome.auth.resetDone"));
      }
    } catch (err) {
      setError(err instanceof HttpError && err.detail ? err.detail : t("welcome.auth.genericError"));
    } finally {
      setBusy(false);
    }
  }

  async function onDemo(e: React.FormEvent) {
    e.preventDefault();
    setDemoError("");
    const mail = demoEmail.trim().toLowerCase();
    if (!EMAIL_RE.test(mail)) {
      setDemoError(t("welcome.auth.invalidEmail"));
      return;
    }
    setDemoBusy(true);
    try {
      const r = await api.demoLogin(mail);
      if (r.authenticated) window.location.reload();
      else setDemoError(t("welcome.auth.demoDenied"));
    } catch {
      setDemoError(t("welcome.auth.demoDenied"));
    } finally {
      setDemoBusy(false);
    }
  }

  const inputCls =
    "w-full bg-card border border-border rounded-xl px-3 py-2.5 text-sm outline-none focus:border-accent";
  const titleKey =
    mode === "register"
      ? "welcome.auth.createTitle"
      : mode === "forgot"
        ? "welcome.auth.forgotTitle"
        : mode === "reset"
          ? "welcome.auth.resetTitle"
          : "welcome.auth.signinTitle";

  return (
    <div className="glass rounded-2xl p-6 sm:p-7 w-full max-w-md lg:justify-self-end">
      <h2 className="text-lg font-semibold mb-1">{t(titleKey)}</h2>

      {/* One-time status banners from a redirect (Google-denied, email verification). */}
      {verify === "ok" && <Banner tone="ok">{t("welcome.auth.verifyOk")}</Banner>}
      {verify === "invalid" && <Banner tone="warn">{t("welcome.auth.verifyInvalid")}</Banner>}
      {bounced === "requested" && <Banner tone="ok">{t("welcome.auth.accessRequested")}</Banner>}
      {bounced === "denied" && <Banner tone="warn">{t("welcome.auth.accessDenied")}</Banner>}
      {login === "suspended" && <Banner tone="warn">{t("welcome.auth.suspended")}</Banner>}
      {deleted && <Banner tone="ok">{t("welcome.auth.deleted")}</Banner>}

      {done ? (
        <div className="mt-3">
          <p className="text-sm text-fg/80 leading-relaxed">{done}</p>
          <button
            onClick={() => {
              setMode("signin");
              setDone("");
            }}
            className="mt-4 text-sm text-accent hover:underline"
          >
            {t("welcome.auth.backToSignin")}
          </button>
        </div>
      ) : (
        <>
          <form onSubmit={onSubmit} className="flex flex-col gap-3 mt-3">
            {mode !== "reset" && (
              <input
                type="email"
                autoComplete="email"
                required
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={t("welcome.auth.email")}
                className={inputCls}
              />
            )}
            {mode !== "forgot" && (
              <input
                type="password"
                autoComplete={mode === "signin" ? "current-password" : "new-password"}
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={
                  mode === "reset" || mode === "register"
                    ? t("welcome.auth.newPassword", { min: PASSWORD_MIN })
                    : t("welcome.auth.password")
                }
                className={inputCls}
              />
            )}
            {error && <p className="text-xs text-red-400">{error}</p>}
            <button
              type="submit"
              disabled={busy}
              className="px-4 py-2.5 rounded-xl font-semibold bg-accent text-accent-fg hover:opacity-90 disabled:opacity-50 transition"
            >
              {busy
                ? t("welcome.auth.working")
                : t(
                    mode === "register"
                      ? "welcome.auth.createButton"
                      : mode === "forgot"
                        ? "welcome.auth.forgotButton"
                        : mode === "reset"
                          ? "welcome.auth.resetButton"
                          : "welcome.auth.signinButton"
                  )}
            </button>
          </form>

          {/* Mode switches */}
          <div className="flex items-center justify-between mt-3 text-xs">
            {mode === "signin" ? (
              <>
                <button onClick={() => { reset(); setMode("register"); }} className="text-accent hover:underline">
                  {t("welcome.auth.createLink")}
                </button>
                <button onClick={() => { reset(); setMode("forgot"); }} className="text-muted hover:text-fg">
                  {t("welcome.auth.forgotLink")}
                </button>
              </>
            ) : (
              <button onClick={() => { reset(); setMode("signin"); }} className="text-accent hover:underline">
                {t("welcome.auth.backToSignin")}
              </button>
            )}
          </div>

          {mode === "signin" && (
            <>
              <div className="flex items-center gap-3 my-4 text-[11px] uppercase tracking-wide text-muted">
                <span className="h-px flex-1 bg-border" />
                {t("welcome.auth.or")}
                <span className="h-px flex-1 bg-border" />
              </div>
              {googleEnabled && (
                <a
                  href="/auth/login"
                  className="block text-center px-4 py-2.5 rounded-xl text-sm font-semibold bg-card border border-border hover:border-accent transition"
                >
                  {t("welcome.auth.google")}
                </a>
              )}
              {!showDemo ? (
                <button
                  onClick={() => setShowDemo(true)}
                  className="w-full mt-2 px-4 py-2.5 rounded-xl text-sm bg-card border border-border hover:border-accent transition"
                >
                  {t("welcome.auth.tryDemo")}
                </button>
              ) : (
                <form onSubmit={onDemo} className="mt-2 flex flex-col gap-2">
                  <p className="text-[11px] text-muted">{t("welcome.auth.demoHint")}</p>
                  <div className="flex gap-2">
                    <input
                      type="email"
                      value={demoEmail}
                      onChange={(e) => setDemoEmail(e.target.value)}
                      placeholder={t("welcome.auth.demoEmail")}
                      className={inputCls}
                    />
                    <button
                      type="submit"
                      disabled={demoBusy}
                      className="shrink-0 px-3 py-2.5 rounded-xl text-sm font-semibold bg-card border border-border hover:border-accent disabled:opacity-50 transition"
                    >
                      {demoBusy ? t("welcome.auth.working") : t("welcome.auth.demoEnter")}
                    </button>
                  </div>
                  {demoError && <p className="text-xs text-red-400">{demoError}</p>}
                </form>
              )}
            </>
          )}
        </>
      )}
    </div>
  );
}

function Banner({ tone, children }: { tone: "ok" | "warn"; children: React.ReactNode }) {
  const cls = tone === "ok" ? "bg-accent/15 text-fg" : "bg-amber-500/15 text-fg";
  return <div className={`rounded-xl px-3 py-2 text-xs leading-relaxed mt-3 ${cls}`}>{children}</div>;
}
