"use client";

import React, { useState, useEffect, useCallback } from "react";
import {
  Smartphone,
  Laptop,
  AlertTriangle,
  CheckCircle2,
  Save,
  Shield,
  Zap,
  Sparkles,
  RefreshCw,
  Clock,
  RotateCcw,
  Check,
  Trash2,
} from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { validatePassword } from "@/lib/auth/validation";
import { PaywallModal } from "@/components/paywall/PaywallModal";
import { FREE_SCAN_LIMIT } from "@/lib/limits";

interface ProfileUser {
  id: string;
  name: string;
  email: string;
  emailVerified: boolean;
  isGuest: boolean;
  isPro: boolean;
  plan: string;
  cancelAtPeriodEnd: boolean;
  hasPassword: boolean;
  scanCount: number;
  scanPeriod: string | null;
  launchBonus: boolean;
  freeScanAllowance: number;
  expiresAt: string | null;
  createdAt: string | null;
  company: string;
  useCase: string;
  receiptCount: number;
}

interface ActiveSessionItem {
  id: string;
  userAgent: string;
  createdAt: string;
  expiresAt: string;
  isCurrent: boolean;
}

function parseDeviceFromUserAgent(ua: string): {
  deviceLabel: string;
  isMobile: boolean;
} {
  if (!ua) return { deviceLabel: "Browser", isMobile: false };
  let os = "Desktop";
  let browser = "Browser";

  if (/windows/i.test(ua)) os = "Windows";
  else if (/macintosh|mac os x/i.test(ua)) os = "macOS";
  else if (/iphone|ipad|ipod/i.test(ua)) os = "iOS";
  else if (/android/i.test(ua)) os = "Android";
  else if (/linux/i.test(ua)) os = "Linux";

  if (/edg\//i.test(ua)) browser = "Microsoft Edge";
  else if (/chrome|crios/i.test(ua)) browser = "Google Chrome";
  else if (/firefox|fxios/i.test(ua)) browser = "Mozilla Firefox";
  else if (/safari/i.test(ua) && !/chrome|crios/i.test(ua)) browser = "Apple Safari";
  else if (/opr\//i.test(ua)) browser = "Opera";

  const isMobile = /mobile|iphone|ipod|android/i.test(ua);
  return {
    deviceLabel: `${os} • ${browser}`,
    isMobile,
  };
}

export default function AccountSettingsPage() {
  const { language } = useI18n();
  const isDe = language === "de";

  const [loadedUser, setLoadedUser] = useState<ProfileUser | null>(null);
  const [sessions, setSessions] = useState<ActiveSessionItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // Editable Profile fields
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [companyOrRole, setCompanyOrRole] = useState("");

  const [isSaving, setIsSaving] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);

  // Paywall modal state
  const [isPaywallOpen, setIsPaywallOpen] = useState(false);

  // Downgrade subscription state
  const [isDowngrading, setIsDowngrading] = useState(false);
  const [showDowngradeConfirm, setShowDowngradeConfirm] = useState(false);
  const [downgradeNotice, setDowngradeNotice] = useState<string | null>(null);
  const [downgradeError, setDowngradeError] = useState<string | null>(null);

  // Change-password form state
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [passwordError, setPasswordError] = useState<string | null>(null);
  const [passwordNotice, setPasswordNotice] = useState<string | null>(null);
  const [isChangingPassword, setIsChangingPassword] = useState(false);

  // Delete-account state
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deletePassword, setDeletePassword] = useState("");
  const [deleteConfirmEmail, setDeleteConfirmEmail] = useState("");
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [isDeletingAccount, setIsDeletingAccount] = useState(false);

  const fetchProfile = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await fetch("/api/auth/profile", { credentials: "include" });
      if (res.ok) {
        const data = await res.json();
        const u: ProfileUser = data.user;
        setLoadedUser(u);
        setEmail(u.email || "");
        setCompanyOrRole(u.company || u.useCase || "");

        // Split name into first and last name
        if (u.name) {
          const parts = u.name.trim().split(/\s+/);
          if (parts.length > 1) {
            setFirstName(parts.slice(0, -1).join(" "));
            setLastName(parts[parts.length - 1]);
          } else {
            setFirstName(parts[0] || "");
            setLastName("");
          }
        } else {
          setFirstName("");
          setLastName("");
        }

        if (Array.isArray(data.sessions)) {
          setSessions(data.sessions);
        }
      } else {
        // Fallback to /api/auth/session
        const fallbackRes = await fetch("/api/auth/session", { credentials: "include" });
        if (fallbackRes.ok) {
          const fbData = await fallbackRes.json();
          if (fbData.user) {
            const fu = fbData.user;
            setLoadedUser({
              id: fu.id,
              name: fu.name || "",
              email: fu.email || "",
              emailVerified: fu.emailVerified,
              isGuest: fu.isGuest,
              isPro: fu.isPro,
              plan: fu.plan || "free",
              cancelAtPeriodEnd: Boolean(fu.cancelAtPeriodEnd),
              hasPassword: true,
              scanCount: fu.scanCount || 0,
              scanPeriod: null,
              launchBonus: fu.launchBonus,
              freeScanAllowance: fu.freeScanAllowance || FREE_SCAN_LIMIT,
              expiresAt: fu.expiresAt || null,
              createdAt: fu.createdAt || null,
              company: fu.company || "",
              useCase: fu.useCase || "",
              receiptCount: 0,
            });
            setEmail(fu.email || "");
            setCompanyOrRole(fu.company || fu.useCase || "");
            if (fu.name) {
              const parts = fu.name.trim().split(/\s+/);
              if (parts.length > 1) {
                setFirstName(parts.slice(0, -1).join(" "));
                setLastName(parts[parts.length - 1]);
              } else {
                setFirstName(parts[0] || "");
                setLastName("");
              }
            }
          }
        }
      }
    } catch (err) {
      console.error("Failed to load profile:", err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchProfile();
  }, [fetchProfile]);

  /**
   * Adds the CSRF double-submit header from `sr_csrf` cookie.
   */
  const csrfHeaders = (): Record<string, string> => {
    const headers: Record<string, string> = { "Content-Type": "application/json" };
    try {
      const match = document.cookie.match(/(?:^|;\s*)sr_csrf=([^;]*)/);
      if (match) headers["x-csrf-token"] = decodeURIComponent(match[1]);
    } catch {
      // ignore
    }
    return headers;
  };

  const handleDiscard = () => {
    if (!loadedUser) return;
    setEmail(loadedUser.email || "");
    setCompanyOrRole(loadedUser.company || loadedUser.useCase || "");
    if (loadedUser.name) {
      const parts = loadedUser.name.trim().split(/\s+/);
      if (parts.length > 1) {
        setFirstName(parts.slice(0, -1).join(" "));
        setLastName(parts[parts.length - 1]);
      } else {
        setFirstName(parts[0] || "");
        setLastName("");
      }
    } else {
      setFirstName("");
      setLastName("");
    }
    setSaveSuccess(false);
    setSaveError(null);
  };

  const handleSaveProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    setSaveError(null);
    setSaveSuccess(false);

    try {
      const fullName = [firstName.trim(), lastName.trim()].filter(Boolean).join(" ");
      const res = await fetch("/api/auth/profile", {
        method: "PATCH",
        headers: csrfHeaders(),
        body: JSON.stringify({
          name: fullName,
          company: companyOrRole.trim(),
        }),
      });

      if (res.ok) {
        setSaveSuccess(true);
        if (loadedUser) {
          setLoadedUser({
            ...loadedUser,
            name: fullName,
            company: companyOrRole.trim(),
          });
        }
        setTimeout(() => setSaveSuccess(false), 3000);
      } else {
        const data = await res.json().catch(() => null);
        setSaveError(
          data?.error ||
            (isDe
              ? "Profil konnte nicht gespeichert werden."
              : "Failed to save profile changes.")
        );
      }
    } catch {
      setSaveError(
        isDe
          ? "Netzwerkfehler beim Speichern."
          : "Network error while saving profile."
      );
    } finally {
      setIsSaving(false);
    }
  };

  const handlePasswordChange = async (e: React.FormEvent) => {
    e.preventDefault();
    setPasswordError(null);
    setPasswordNotice(null);

    if (!currentPassword || !newPassword || !confirmPassword) {
      setPasswordError(isDe ? "Bitte fülle alle Felder aus." : "Please fill in every field.");
      return;
    }

    const strengthError = validatePassword(newPassword, isDe, { requireStrength: true });
    if (strengthError) {
      setPasswordError(strengthError);
      return;
    }

    if (newPassword !== confirmPassword) {
      setPasswordError(
        isDe ? "Die neuen Passwörter stimmen nicht überein." : "The new passwords don't match."
      );
      return;
    }

    setIsChangingPassword(true);
    try {
      const res = await fetch("/api/auth/change-password", {
        method: "POST",
        headers: csrfHeaders(),
        body: JSON.stringify({ currentPassword, newPassword, remember: true }),
      });

      if (res.ok) {
        setCurrentPassword("");
        setNewPassword("");
        setConfirmPassword("");
        setPasswordNotice(
          isDe
            ? "Passwort erfolgreich geändert. Alle anderen Sitzungen wurden beendet."
            : "Password updated successfully. All other sessions have been terminated."
        );
        fetchProfile();
        return;
      }

      const data = (await res.json().catch(() => null)) as { error?: string } | null;
      const code = data?.error;

      if (code === "wrong_password") {
        setPasswordError(
          isDe ? "Das aktuelle Passwort ist falsch." : "The current password is incorrect."
        );
      } else if (code === "use_google") {
        setPasswordError(
          isDe ? "Dieses Konto nutzt Google-Anmeldung." : "This account signs in with Google."
        );
      } else if (code === "weak_password") {
        setPasswordError(
          isDe
            ? "Passwort zu schwach — mindestens 8 Zeichen, kombiniert mit Ziffern oder Sonderzeichen."
            : "Password too weak — at least 8 characters, mixed with digits or symbols."
        );
      } else if (code === "rate_limited") {
        setPasswordError(
          isDe
            ? "Zu viele Versuche. Bitte versuche es später erneut."
            : "Too many attempts. Please try again later."
        );
      } else if (code === "csrf_failed") {
        setPasswordError(
          isDe
            ? "Sicherheitsprüfung fehlgeschlagen — bitte lade die Seite neu."
            : "Security check failed — please reload the page."
        );
      } else if (code === "unauthorized") {
        setPasswordError(isDe ? "Bitte melde dich erneut an." : "Please sign in again.");
      } else {
        setPasswordError(
          isDe ? "Etwas ist schiefgelaufen. Bitte versuche es erneut." : "Something went wrong. Please try again."
        );
      }
    } catch {
      setPasswordError(
        isDe ? "Netzwerkfehler — bitte versuche es erneut." : "Network error — please try again."
      );
    } finally {
      setIsChangingPassword(false);
    }
  };

  const handleDowngradeSubscription = async () => {
    setIsDowngrading(true);
    setDowngradeError(null);
    setDowngradeNotice(null);
    try {
      const res = await fetch("/api/subscription/cancel", {
        method: "POST",
        headers: csrfHeaders(),
      });
      if (res.ok) {
        const data = await res.json().catch(() => null);
        if (data?.scheduled) {
          const dateStr = data?.expiresAt
            ? new Date(data.expiresAt).toLocaleDateString(isDe ? "de-DE" : "en-US", {
                year: "numeric",
                month: "short",
                day: "numeric",
              })
            : null;
          setDowngradeNotice(
            isDe
              ? `Kündigung vorgemerkt. Dein Pro-Zugang bleibt aktiv${dateStr ? ` bis ${dateStr}` : ""}, danach wechselt dein Konto automatisch auf den Free-Plan.`
              : `Cancellation scheduled. Your Pro access stays active${dateStr ? ` until ${dateStr}` : ""}, then your account switches to the Free tier automatically.`
          );
        } else {
          setDowngradeNotice(
            isDe
              ? "Abonnement erfolgreich gekündigt. Dein Konto ist jetzt auf dem Free-Plan."
              : "Subscription cancelled successfully. Your account is now on the Free tier."
          );
        }
        setShowDowngradeConfirm(false);
        fetchProfile();
      } else {
        const data = await res.json().catch(() => null);
        setDowngradeError(
          data?.error || (isDe ? "Kündigung fehlgeschlagen." : "Cancellation failed.")
        );
      }
    } catch {
      setDowngradeError(
        isDe ? "Netzwerkfehler bei der Kündigung." : "Network error during cancellation."
      );
    } finally {
      setIsDowngrading(false);
    }
  };

  const handleDeleteAccount = async (e: React.FormEvent) => {
    e.preventDefault();
    setDeleteError(null);

    setIsDeletingAccount(true);
    try {
      const res = await fetch("/api/auth/delete-account", {
        method: "DELETE",
        headers: csrfHeaders(),
        body: JSON.stringify({
          password: loadedUser?.hasPassword ? deletePassword : undefined,
          confirmEmail: deleteConfirmEmail,
        }),
      });

      if (res.ok) {
        // The session is already destroyed server-side; a full navigation
        // (not a client router push) clears any in-memory auth state too.
        window.location.href = "/";
        return;
      }

      const data = (await res.json().catch(() => null)) as { error?: string } | null;
      const code = data?.error;

      if (code === "wrong_password") {
        setDeleteError(isDe ? "Das Passwort ist falsch." : "The password is incorrect.");
      } else if (code === "confirmation_mismatch") {
        setDeleteError(
          isDe
            ? "Die eingegebene E-Mail-Adresse stimmt nicht überein."
            : "The email you typed doesn't match."
        );
      } else if (code === "rate_limited") {
        setDeleteError(
          isDe ? "Zu viele Versuche. Bitte versuche es später erneut." : "Too many attempts. Please try again later."
        );
      } else if (code === "csrf_failed") {
        setDeleteError(
          isDe ? "Sicherheitsprüfung fehlgeschlagen — bitte lade die Seite neu." : "Security check failed — please reload the page."
        );
      } else if (code === "unauthorized") {
        setDeleteError(isDe ? "Bitte melde dich erneut an." : "Please sign in again.");
      } else {
        setDeleteError(
          isDe ? "Löschen fehlgeschlagen. Bitte versuche es erneut." : "Deletion failed. Please try again."
        );
      }
    } catch {
      setDeleteError(isDe ? "Netzwerkfehler — bitte versuche es erneut." : "Network error — please try again.");
    } finally {
      setIsDeletingAccount(false);
    }
  };

  // Compute display values
  const userInitials = (
    [firstName, lastName].filter(Boolean).join(" ") ||
    email ||
    "AC"
  )
    .split(/\s+/)
    .map((part) => part[0] ?? "")
    .join("")
    .slice(0, 2)
    .toUpperCase();

  const isPro = Boolean(loadedUser?.isPro);
  // Falls back to the Free label the instant isPro flips false (expiresAt
  // passed), even if `plan` itself is still waiting on the webhook that
  // resets it — the badge must never claim Pro after access already ended.
  const planName = !isPro
    ? isDe
      ? "Kostenloser Plan (Free Tier)"
      : "Free Tier"
    : loadedUser?.plan === "weekly"
      ? isDe
        ? "Wochen-Pass (Weekly Pro)"
        : "Weekly Pass (Pro)"
      : loadedUser?.plan === "annual"
      ? isDe
        ? "Jahres-Pro (Annual Pro)"
        : "Annual Pro"
      : loadedUser?.plan === "lifetime"
      ? isDe
        ? "Lifetime Lizenz (Unbegrenzt)"
        : "Lifetime License (Unlimited)"
      : isDe
      ? "Kostenloser Plan (Free Tier)"
      : "Free Tier";

  const scanCount = loadedUser?.scanCount ?? 0;
  const scanLimit = isPro ? Infinity : loadedUser?.freeScanAllowance ?? 5;
  const scanPercentage = isPro
    ? 100
    : Math.min(100, Math.round((scanCount / (scanLimit || 1)) * 100));

  // Determine renewal string
  const formatRenewalText = () => {
    if (loadedUser?.plan === "lifetime") {
      return isDe ? "LEBENSLANGER ZUGANG • KEIN ABLAUF" : "LIFETIME ACCESS • NEVER EXPIRES";
    }
    // Once access has actually lapsed, never show a stale "renews on" /
    // "cancelled, access until" date from before expiry — even if `plan`
    // hasn't been reset to "free" by the webhook yet.
    if (!isPro) {
      return isDe ? "KONTINGENT: MONATLICHE ERNEUERUNG" : "QUOTA: MONTHLY RESET";
    }
    if (loadedUser?.expiresAt) {
      try {
        const d = new Date(loadedUser.expiresAt);
        const dateStr = d.toLocaleDateString(isDe ? "de-DE" : "en-US", {
          year: "numeric",
          month: "short",
          day: "numeric",
        });
        if (loadedUser.cancelAtPeriodEnd) {
          return isDe ? `GEKÜNDIGT • ZUGANG BIS: ${dateStr}` : `CANCELLED • ACCESS UNTIL: ${dateStr}`;
        }
        return isDe ? `VERLÄNGERT SICH AM: ${dateStr}` : `RENEWS ON: ${dateStr}`;
      } catch {
        // fallback
      }
    }
    return isDe ? "KONTINGENT: MONATLICHE ERNEUERUNG" : "QUOTA: MONTHLY RESET";
  };

  return (
    <div className="space-y-10 font-sans max-w-5xl">
      {/* Header: System Preferences / Account Settings */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-6 border-b border-[#E2E8F0]">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span className="w-2.5 h-2.5 bg-black"></span>
            <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
              {isDe ? "Einstellungen" : "Settings"}
            </span>
          </div>
          <h1 className="font-display text-3xl sm:text-4xl font-bold tracking-tight text-black">
            {isDe ? "Konto-Einstellungen" : "Account Settings"}
          </h1>
        </div>

        <div className="flex items-center gap-3 font-mono text-xs uppercase tracking-caps">
          <button
            type="button"
            onClick={handleDiscard}
            disabled={isSaving}
            className="px-4 py-2 bg-white border border-[#E2E8F0] text-[#475569] hover:text-black hover:border-black transition-colors disabled:opacity-50 flex items-center gap-1.5"
          >
            <RotateCcw className="w-3.5 h-3.5" />
            <span>{isDe ? "ZURÜCKSETZEN" : "DISCARD"}</span>
          </button>
          <button
            type="button"
            onClick={handleSaveProfile}
            disabled={isSaving}
            className="px-5 py-2 bg-black text-white hover:bg-[#334155] transition-colors font-medium flex items-center gap-2 disabled:opacity-50"
          >
            {isSaving ? (
              <RefreshCw className="w-3.5 h-3.5 animate-spin" />
            ) : (
              <Save className="w-3.5 h-3.5" />
            )}
            <span>
              {saveSuccess
                ? isDe
                  ? "GESPEICHERT ✓"
                  : "SAVED ✓"
                : isSaving
                ? isDe
                  ? "SPEICHERN…"
                  : "SAVING…"
                : isDe
                ? "ÄNDERUNGEN SPEICHERN"
                : "SAVE CHANGES"}
            </span>
          </button>
        </div>
      </div>

      {saveSuccess && (
        <div className="p-3.5 bg-emerald-50 border border-emerald-300 font-mono text-xs text-emerald-900 flex items-center gap-2">
          <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
          <span>{isDe ? "Profiländerungen wurden erfolgreich aktualisiert." : "Profile updated successfully."}</span>
        </div>
      )}

      {saveError && (
        <div className="p-3.5 bg-red-50 border border-red-300 font-mono text-xs text-red-900 flex items-center gap-2">
          <AlertTriangle className="w-4 h-4 text-red-600 shrink-0" />
          <span>{saveError}</span>
        </div>
      )}

      {/* Section 1: Profile Configuration */}
      <section className="bg-white border border-[#E2E8F0] p-6 sm:p-8 space-y-6">
        <div className="border-b border-[#E2E8F0] pb-4">
          <h2 className="font-display text-xl font-bold text-black tracking-tight">
            {isDe ? "Profil-Konfiguration" : "Profile Configuration"}
          </h2>
          <p className="text-xs text-[#64748B] mt-0.5 font-sans">
            {isDe
              ? "Passe deinen Vor- und Nachnamen sowie Unternehmens- und Profilinformationen an."
              : "Update your identity details, name, and account preferences."}
          </p>
        </div>

        {/* Avatar block */}
        <div className="flex items-center gap-6">
          <div className="w-20 h-20 bg-[#1E293B] text-white flex items-center justify-center font-mono text-xl font-bold border border-black shrink-0">
            {userInitials}
          </div>
          <div>
            <div className="font-display font-bold text-base text-black">
              {[firstName, lastName].filter(Boolean).join(" ") || (isDe ? "Benutzerkonto" : "User Account")}
            </div>
            <p className="text-xs text-[#64748B] font-mono mt-0.5">
              {email || (isDe ? "Keine E-Mail angegeben" : "No email set")}
            </p>
            <div className="mt-2 inline-flex items-center gap-1.5 px-2 py-0.5 bg-[#F8FAFC] border border-[#E2E8F0] font-mono text-[10px] uppercase text-[#475569]">
              <span className="w-1.5 h-1.5 bg-emerald-500 rounded-full"></span>
              <span>{loadedUser?.emailVerified ? (isDe ? "Konto Verifiziert" : "Account Verified") : (isDe ? "Aktiv" : "Active")}</span>
            </div>
          </div>
        </div>

        {/* Form fields */}
        <form onSubmit={handleSaveProfile} className="grid grid-cols-1 sm:grid-cols-2 gap-6 pt-2">
          <div>
            <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
              {isDe ? "VORNAME" : "FIRST NAME"}
            </label>
            <input
              type="text"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              placeholder={isDe ? "Vorname eingeben" : "First name"}
              className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-black focus:border-black focus:outline-none"
            />
          </div>

          <div>
            <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
              {isDe ? "NACHNAME" : "LAST NAME"}
            </label>
            <input
              type="text"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              placeholder={isDe ? "Nachname eingeben" : "Last name"}
              className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-black focus:border-black focus:outline-none"
            />
          </div>

          <div className="sm:col-span-2">
            <div className="flex items-center justify-between mb-1.5">
              <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium">
                {isDe ? "E-MAIL-ADRESSE" : "EMAIL ADDRESS"}
              </label>
              <span className="font-mono text-[10px] text-[#64748B]">
                {isDe ? "Konto-ID (Verknüpft)" : "Account ID (Linked)"}
              </span>
            </div>
            <input
              type="email"
              value={email}
              readOnly
              disabled
              className="w-full bg-[#F1F5F9] border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-[#334155] cursor-not-allowed select-all"
            />
          </div>

          <div className="sm:col-span-2">
            <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
              {isDe ? "UNTERNEHMEN / ROLLE / EINSATZZWECK" : "COMPANY / ROLE / USE CASE"}
            </label>
            <textarea
              rows={2}
              value={companyOrRole}
              onChange={(e) => setCompanyOrRole(e.target.value)}
              placeholder={isDe ? "z.B. Freelancer, E-Commerce, Einzelhandel..." : "e.g. Freelance, E-Commerce, Retail..."}
              className="w-full bg-[#F8FAFC] border border-[#E2E8F0] p-3.5 font-sans text-xs text-black focus:border-black focus:outline-none"
            />
          </div>
        </form>
      </section>

      {/* Section 2: Access & Security */}
      <section className="bg-white border border-[#E2E8F0] p-6 sm:p-8 space-y-6">
        <div className="border-b border-[#E2E8F0] pb-4">
          <div className="flex items-center gap-2">
            <Shield className="w-4 h-4 text-black" />
            <h2 className="font-display text-xl font-bold text-black tracking-tight">
              {isDe ? "Zugang & Sicherheit" : "Access & Security"}
            </h2>
          </div>
          <p className="text-xs text-[#64748B] mt-0.5 font-sans">
            {isDe
              ? "Passwort-Verwaltung und Übersicht der aktiven Anmeldesitzungen."
              : "Manage authentication credentials and inspect active sessions."}
          </p>
        </div>

        <div className="space-y-4">
          {/* Password Change Box */}
          <div className="p-5 bg-[#F8FAFC] border border-[#E2E8F0] space-y-4">
            <div>
              <div className="flex items-center gap-2">
                <span className="font-sans font-semibold text-xs text-black">
                  {isDe ? "Passwort ändern" : "Password Verification & Change"}
                </span>
                <span className="font-mono text-[9px] bg-emerald-100 text-emerald-800 px-1.5 py-0.2 uppercase font-bold">
                  {loadedUser?.hasPassword ? (isDe ? "PASSWORT AKTIV" : "ACTIVE") : (isDe ? "GOOGLE AUTH" : "GOOGLE AUTH")}
                </span>
              </div>
              <p className="text-xs text-[#64748B] font-mono mt-1">
                {isDe
                  ? "Ändere dein Passwort. Aus Sicherheitsgründen werden alle anderen aktiven Sitzungen sofort beendet."
                  : "Change your password. For security, all other active sessions will be terminated immediately."}
              </p>
            </div>

            <form onSubmit={handlePasswordChange} className="space-y-3 pt-1">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
                    {isDe ? "AKTUELLES PASSWORT" : "CURRENT PASSWORD"}
                  </label>
                  <input
                    type="password"
                    autoComplete="current-password"
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    className="w-full bg-white border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-black focus:border-black focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
                    {isDe ? "NEUES PASSWORT" : "NEW PASSWORD"}
                  </label>
                  <input
                    type="password"
                    autoComplete="new-password"
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    className="w-full bg-white border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-black focus:border-black focus:outline-none"
                  />
                </div>

                <div>
                  <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
                    {isDe ? "PASSWORT BESTÄTIGEN" : "CONFIRM PASSWORD"}
                  </label>
                  <input
                    type="password"
                    autoComplete="new-password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className="w-full bg-white border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-black focus:border-black focus:outline-none"
                  />
                </div>
              </div>

              {passwordError && (
                <p className="text-[11px] font-mono text-red-600 flex items-center gap-1.5">
                  <AlertTriangle className="w-3.5 h-3.5 shrink-0" />
                  {passwordError}
                </p>
              )}
              {passwordNotice && (
                <p className="text-[11px] font-mono text-emerald-700 flex items-center gap-1.5">
                  <CheckCircle2 className="w-3.5 h-3.5 shrink-0" />
                  {passwordNotice}
                </p>
              )}

              <div className="flex items-center gap-3 flex-wrap pt-1">
                <button
                  type="submit"
                  disabled={isChangingPassword}
                  className="px-4 py-2 bg-black text-white hover:bg-[#334155] disabled:opacity-50 font-mono text-xs uppercase tracking-caps font-medium"
                >
                  {isChangingPassword
                    ? isDe
                      ? "WIRD GEÄNDERT…"
                      : "UPDATING…"
                    : isDe
                    ? "PASSWORT AKTUALISIEREN"
                    : "UPDATE PASSWORD"}
                </button>
                <span className="font-mono text-[10px] text-[#94A3B8]">
                  {isDe
                    ? "Mindestens 8 Zeichen, kombiniert mit Ziffern oder Sonderzeichen."
                    : "At least 8 characters, mixed with digits or symbols."}
                </span>
              </div>
            </form>
          </div>
        </div>

        {/* Dynamic Active Sessions */}
        <div className="pt-2">
          <div className="flex items-center justify-between mb-3">
            <span className="font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium">
              {isDe ? "AKTIVE SITZUNGEN (GERÄTEÜBERSICHT)" : "ACTIVE SESSIONS (DEVICE OVERVIEW)"}
            </span>
            <span className="font-mono text-[10px] text-[#64748B]">
              {sessions.length > 0
                ? isDe
                  ? `${sessions.length} aktive Verbindung(en)`
                  : `${sessions.length} active connection(s)`
                : isDe
                ? "Aktuelles Gerät verbunden"
                : "Current device connected"}
            </span>
          </div>

          <div className="space-y-2.5">
            {sessions.length > 0 ? (
              sessions.map((sess) => {
                const parsed = parseDeviceFromUserAgent(sess.userAgent);
                const IconComponent = parsed.isMobile ? Smartphone : Laptop;
                const createdDate = new Date(sess.createdAt).toLocaleDateString(
                  isDe ? "de-DE" : "en-US",
                  {
                    day: "2-digit",
                    month: "2-digit",
                    year: "numeric",
                    hour: "2-digit",
                    minute: "2-digit",
                  }
                );

                return (
                  <div
                    key={sess.id}
                    className={`p-3.5 bg-[#F8FAFC] border flex items-center justify-between font-mono text-xs ${
                      sess.isCurrent ? "border-black bg-white" : "border-[#E2E8F0]"
                    }`}
                  >
                    <div className="flex items-center gap-3 min-w-0">
                      <IconComponent
                        className={`w-4 h-4 shrink-0 ${
                          sess.isCurrent ? "text-black" : "text-[#64748B]"
                        }`}
                      />
                      <div className="min-w-0">
                        <div className="text-black font-semibold truncate">
                          {parsed.deviceLabel}
                        </div>
                        <p className="text-[10px] text-[#64748B] flex items-center gap-1 mt-0.5">
                          <Clock className="w-3 h-3 shrink-0" />
                          <span>
                            {isDe
                              ? `Angemeldet seit: ${createdDate}`
                              : `Signed in: ${createdDate}`}
                          </span>
                        </p>
                      </div>
                    </div>
                    <div>
                      {sess.isCurrent ? (
                        <span className="text-[10px] bg-emerald-100 text-emerald-800 font-bold px-2 py-0.5 uppercase tracking-wider">
                          {isDe ? "DIESES GERÄT" : "CURRENT DEVICE"}
                        </span>
                      ) : (
                        <span className="text-[10px] text-[#64748B] font-medium uppercase tracking-wider">
                          {isDe ? "AKTIV" : "ACTIVE"}
                        </span>
                      )}
                    </div>
                  </div>
                );
              })
            ) : (
              /* Fallback if session API has single entry */
              <div className="p-3.5 bg-white border border-black flex items-center justify-between font-mono text-xs">
                <div className="flex items-center gap-3">
                  <Laptop className="w-4 h-4 text-black shrink-0" />
                  <div>
                    <span className="text-black font-semibold">
                      {typeof window !== "undefined"
                        ? parseDeviceFromUserAgent(navigator.userAgent).deviceLabel
                        : "Browser Session"}
                    </span>
                    <p className="text-[10px] text-[#64748B] mt-0.5">
                      {isDe ? "Aktuell autorisierte Websitzung" : "Authorized web session"}
                    </p>
                  </div>
                </div>
                <span className="text-[10px] bg-emerald-100 text-emerald-800 font-bold px-2 py-0.5 uppercase tracking-wider">
                  {isDe ? "DIESES GERÄT" : "CURRENT DEVICE"}
                </span>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Section 3: Subscription & Usage Quota */}
      <section className="bg-white border border-[#E2E8F0] p-6 sm:p-8 space-y-6">
        <div className="border-b border-[#E2E8F0] pb-4 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div>
            <div className="flex items-center gap-2">
              <Zap className="w-4 h-4 text-black" />
              <h2 className="font-display text-xl font-bold text-black tracking-tight">
                {isDe ? "Abonnement & Kontingent" : "Subscription & Usage Quota"}
              </h2>
            </div>
            <p className="text-xs text-[#64748B] mt-0.5 font-sans">
              {isDe
                ? "Echtzeit-Nutzungsdaten und Beleg-Kontingente deines Kontos."
                : "Real-time usage metrics and receipt quota for your account."}
            </p>
          </div>
          {!isPro ? (
            <button
              type="button"
              onClick={() => setIsPaywallOpen(true)}
              className="px-4 py-2 bg-black text-white font-mono text-xs uppercase tracking-caps hover:bg-[#334155] transition-colors flex items-center gap-1.5 font-bold shrink-0 self-start sm:self-auto"
            >
              <Sparkles className="w-3.5 h-3.5 text-yellow-400" />
              <span>{isDe ? "PLAN UPGRADEN" : "UPGRADE TIER"}</span>
            </button>
          ) : loadedUser?.cancelAtPeriodEnd ? (
            <span className="px-3.5 py-2 bg-amber-50 border border-amber-300 text-amber-800 font-mono text-xs uppercase tracking-caps font-semibold shrink-0 self-start sm:self-auto">
              {isDe ? "KÜNDIGUNG VORGEMERKT" : "CANCELLATION SCHEDULED"}
            </span>
          ) : (
            <div className="flex items-center gap-2 shrink-0 self-start sm:self-auto">
              {!showDowngradeConfirm ? (
                <button
                  type="button"
                  onClick={() => setShowDowngradeConfirm(true)}
                  className="px-3.5 py-2 bg-white border border-red-300 text-red-700 hover:bg-red-50 font-mono text-xs uppercase tracking-caps font-semibold transition-colors"
                >
                  {isDe ? "ABO KÜNDIGEN (FREE)" : "CANCEL PLAN (FREE)"}
                </button>
              ) : (
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => setShowDowngradeConfirm(false)}
                    disabled={isDowngrading}
                    className="px-3 py-1.5 bg-white border border-[#E2E8F0] text-[#475569] hover:text-black font-mono text-xs uppercase"
                  >
                    {isDe ? "ABBRECHEN" : "KEEP"}
                  </button>
                  <button
                    type="button"
                    onClick={handleDowngradeSubscription}
                    disabled={isDowngrading}
                    className="px-3.5 py-1.5 bg-red-600 hover:bg-red-700 text-white font-mono text-xs uppercase tracking-caps font-bold transition-colors disabled:opacity-50"
                  >
                    {isDowngrading ? (isDe ? "WIRD GEKÜNDIGT..." : "CANCELLING...") : (isDe ? "BESTÄTIGEN" : "CONFIRM")}
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {downgradeNotice && (
          <div className="p-3.5 bg-emerald-50 border border-emerald-300 font-mono text-xs text-emerald-900 flex items-center gap-2">
            <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0" />
            <span>{downgradeNotice}</span>
          </div>
        )}

        {downgradeError && (
          <div className="p-3.5 bg-red-50 border border-red-300 font-mono text-xs text-red-900 flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-600 shrink-0" />
            <span>{downgradeError}</span>
          </div>
        )}

        {/* Dynamic Plan Card */}
        <div className="p-6 bg-[#EEF4FC] border border-[#E2E8F0] space-y-5 font-mono">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
            <div>
              <span className="text-[10px] uppercase tracking-caps text-[#64748B] font-bold">
                {isDe ? "AKTUELLER PLAN" : "CURRENT PLAN"}
              </span>
              <div className="font-display text-2xl sm:text-3xl font-bold text-black tracking-tight">
                {planName}
              </div>
            </div>
            <div className="text-xs font-semibold text-[#475569] uppercase bg-white/70 border border-[#E2E8F0] px-3 py-1.5 self-start sm:self-auto">
              {formatRenewalText()}
            </div>
          </div>

          <div className="space-y-4 pt-2 border-t border-[#E2E8F0]">
            {/* Scan Quota Progress */}
            <div>
              <div className="flex items-center justify-between text-xs mb-1.5">
                <span className="text-[#475569] font-medium">
                  {isDe ? "Monatliche Beleg-Scans" : "Monthly Receipt Scans"}
                </span>
                <span className="text-black font-bold">
                  {isPro
                    ? `${scanCount} ${isDe ? "Scans (Unbegrenzt)" : "Scans (Unlimited)"}`
                    : `${scanCount} / ${scanLimit} ${isDe ? "Gratis-Scans" : "Free Scans"}`}
                </span>
              </div>
              <div className="w-full h-2.5 bg-[#E2E8F0] overflow-hidden">
                <div
                  className={`h-full transition-all duration-500 ${
                    isPro
                      ? "bg-emerald-600 w-full"
                      : scanPercentage >= 90
                      ? "bg-red-600"
                      : scanPercentage >= 70
                      ? "bg-amber-500"
                      : "bg-black"
                  }`}
                  style={{ width: isPro ? "100%" : `${scanPercentage}%` }}
                ></div>
              </div>
              {!isPro && loadedUser?.launchBonus && (
                <p className="text-[10px] text-[#475569] mt-1 flex items-center gap-1">
                  <Sparkles className="w-3 h-3 text-emerald-600 shrink-0" />
                  <span>{isDe ? "Launch-Bonus aktiv: 100 Scans Startguthaben" : "Launch Bonus Active: 100 Scans Allowance"}</span>
                </p>
              )}
            </div>

            {/* Document Archive & Export Features */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1">
              <div className="p-3 bg-white border border-[#E2E8F0]">
                <div className="text-[10px] text-[#64748B] uppercase tracking-caps">
                  {isDe ? "Gespeicherte Belege" : "Stored Receipts"}
                </div>
                <div className="text-lg font-display font-bold text-black mt-0.5">
                  {loadedUser?.receiptCount ?? 0} {isDe ? "Dokumente" : "Documents"}
                </div>
              </div>

              <div className="p-3 bg-white border border-[#E2E8F0]">
                <div className="text-[10px] text-[#64748B] uppercase tracking-caps">
                  {isDe ? "Export & OCR Engine" : "Export & OCR Engine"}
                </div>
                <div className="text-xs font-semibold text-black mt-1 flex items-center gap-1.5">
                  <Check className="w-3.5 h-3.5 text-emerald-600" />
                  <span>Excel Dual-Sheet, CSV, PDF</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Section 4: Danger Zone */}
      <section className="bg-white border border-red-300 p-6 sm:p-8 space-y-6">
        <div className="border-b border-red-200 pb-4">
          <div className="flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-red-600" />
            <h2 className="font-display text-xl font-bold text-red-700 tracking-tight">
              {isDe ? "Gefahrenzone" : "Danger Zone"}
            </h2>
          </div>
          <p className="text-xs text-[#64748B] mt-0.5 font-sans">
            {isDe
              ? "Diese Aktion ist endgültig und kann nicht rückgängig gemacht werden."
              : "This action is permanent and cannot be undone."}
          </p>
        </div>

        {!showDeleteConfirm ? (
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-5 bg-red-50 border border-red-200">
            <div>
              <div className="font-sans font-semibold text-sm text-black">
                {isDe ? "Konto löschen" : "Delete account"}
              </div>
              <p className="text-xs text-[#64748B] font-mono mt-1 max-w-xl">
                {isDe
                  ? "Löscht dein Konto, alle gescannten Belege, Projekte und Sitzungen unwiderruflich. Ein aktives Abonnement wird sofort gekündigt."
                  : "Permanently deletes your account, every scanned receipt, project, and session. An active subscription is cancelled immediately."}
              </p>
            </div>
            <button
              type="button"
              onClick={() => {
                setShowDeleteConfirm(true);
                setDeleteError(null);
                setDeletePassword("");
                setDeleteConfirmEmail("");
              }}
              className="px-4 py-2 bg-white border border-red-400 text-red-700 hover:bg-red-600 hover:text-white hover:border-red-600 transition-colors font-mono text-xs uppercase tracking-caps font-semibold flex items-center gap-1.5 shrink-0"
            >
              <Trash2 className="w-3.5 h-3.5" />
              <span>{isDe ? "KONTO LÖSCHEN" : "DELETE ACCOUNT"}</span>
            </button>
          </div>
        ) : (
          <form onSubmit={handleDeleteAccount} className="p-5 bg-red-50 border border-red-300 space-y-4">
            <p className="text-xs text-red-900 font-mono">
              {isDe
                ? "Das kann nicht rückgängig gemacht werden. Alle deine Daten werden dauerhaft gelöscht."
                : "This cannot be undone. All of your data will be permanently deleted."}
            </p>

            {loadedUser?.hasPassword && (
              <div>
                <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
                  {isDe ? "PASSWORT" : "PASSWORD"}
                </label>
                <input
                  type="password"
                  autoComplete="current-password"
                  value={deletePassword}
                  onChange={(e) => setDeletePassword(e.target.value)}
                  className="w-full bg-white border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-black focus:border-red-500 focus:outline-none"
                />
              </div>
            )}

            <div>
              <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] mb-1.5 font-medium">
                {isDe ? `TIPPE „${email}“ ZUR BESTÄTIGUNG` : `TYPE "${email}" TO CONFIRM`}
              </label>
              <input
                type="text"
                autoComplete="off"
                value={deleteConfirmEmail}
                onChange={(e) => setDeleteConfirmEmail(e.target.value)}
                className="w-full bg-white border border-[#E2E8F0] px-3.5 py-2 font-mono text-xs text-black focus:border-red-500 focus:outline-none"
              />
            </div>

            {deleteError && (
              <p className="text-[11px] font-mono text-red-700 flex items-center gap-1.5">
                <AlertTriangle className="w-3.5 h-3.5 shrink-0" />
                {deleteError}
              </p>
            )}

            <div className="flex items-center gap-3 flex-wrap pt-1">
              <button
                type="button"
                onClick={() => setShowDeleteConfirm(false)}
                disabled={isDeletingAccount}
                className="px-4 py-2 bg-white border border-[#E2E8F0] text-[#475569] hover:text-black font-mono text-xs uppercase tracking-caps disabled:opacity-50"
              >
                {isDe ? "ABBRECHEN" : "CANCEL"}
              </button>
              <button
                type="submit"
                disabled={Boolean(
                  isDeletingAccount ||
                    deleteConfirmEmail.trim().toLowerCase() !== (email || "").trim().toLowerCase() ||
                    (loadedUser?.hasPassword && !deletePassword)
                )}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-mono text-xs uppercase tracking-caps font-bold transition-colors disabled:opacity-50 flex items-center gap-1.5"
              >
                {isDeletingAccount ? (
                  <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                ) : (
                  <Trash2 className="w-3.5 h-3.5" />
                )}
                <span>
                  {isDeletingAccount
                    ? isDe
                      ? "WIRD GELÖSCHT…"
                      : "DELETING…"
                    : isDe
                    ? "ENDGÜLTIG LÖSCHEN"
                    : "PERMANENTLY DELETE"}
                </span>
              </button>
            </div>
          </form>
        )}
      </section>

      {/* Paywall Upgrade Modal */}
      <PaywallModal
        isOpen={isPaywallOpen}
        onClose={() => {
          setIsPaywallOpen(false);
          fetchProfile();
        }}
        onSuccessUpgrade={() => {
          setIsPaywallOpen(false);
          fetchProfile();
        }}
      />
    </div>
  );
}
