"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Settings, LogOut, User, Save, Sun, Moon, Monitor, Bot, KeyRound, Sparkles, CreditCard, ChevronRight, Tag, CheckCircle2, AlertCircle, Loader2, PanelLeft, RotateCcw, Star, Smartphone, Eye, EyeOff, ArrowUp, ArrowDown, type LucideIcon } from "lucide-react";
import { createClient, getBrowserUser } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useThemeStore } from "@/stores/theme-store";
import { useUIStore } from "@/stores/ui-store";
import { cn } from "@/lib/utils";
import { AI_MODEL_OPTIONS, AI_PROVIDER_OPTIONS, getDefaultModel } from "@/lib/ai/catalog";
import type { AIProvider } from "@/lib/ai/types";
import { navigationPresets, orderSidebarItems, sidebarNavGroups, sidebarNavItems, sidebarTopNav } from "@/lib/sidebar-navigation";

const THEMES = [
  { value: "light" as const, label: "Light", icon: Sun },
  { value: "dark" as const, label: "Dark", icon: Moon },
  { value: "system" as const, label: "System", icon: Monitor },
];

type SettingsSectionId = "profile" | "appearance" | "sidebar" | "ai" | "billing" | "promo" | "account";

const SETTINGS_SECTIONS: Array<{
  id: SettingsSectionId;
  label: string;
  description: string;
  icon: LucideIcon;
}> = [
  { id: "profile", label: "Profile", description: "Identity and account basics", icon: User },
  { id: "appearance", label: "Appearance", description: "Theme and interface feel", icon: Sun },
  { id: "sidebar", label: "Sidebar", description: "Visible navigation shortcuts", icon: PanelLeft },
  { id: "ai", label: "Mindavio AI", description: "Provider, keys and behavior", icon: Bot },
  { id: "billing", label: "Billing", description: "Subscription and plan", icon: CreditCard },
  { id: "promo", label: "Promo Code", description: "Redeem access codes", icon: Tag },
  { id: "account", label: "Account", description: "Session controls", icon: LogOut },
];

export default function SettingsPage() {
  const router = useRouter();
  const supabase = createClient();
  const { theme, setTheme } = useThemeStore();
  const {
    applyNavigationPreset,
    favoriteSidebarItemIds,
    hiddenSidebarItemIds,
    initSidebarPreferences,
    mobileDockItemIds,
    moveSidebarItem,
    sidebarCustomOrderIds,
    showAllSidebarItems,
    toggleFavoriteSidebarItem,
    toggleMobileDockItem,
    toggleSidebarItem,
  } = useUIStore();

  const [fullName, setFullName] = useState("");
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [signingOut, setSigningOut] = useState(false);
  const [promoCode, setPromoCode] = useState("");
  const [promoLoading, setPromoLoading] = useState(false);
  const [promoSuccess, setPromoSuccess] = useState<{ plan: string; duration_months: number; granted_until: string } | null>(null);
  const [promoError, setPromoError] = useState<string | null>(null);
  const [aiProvider, setAiProvider] = useState<AIProvider>("mindavio_core");
  const [aiModel, setAiModel] = useState(getDefaultModel("mindavio_core"));
  const [openaiApiKey, setOpenaiApiKey] = useState("");
  const [anthropicApiKey, setAnthropicApiKey] = useState("");
  const [openaiApiKeyHint, setOpenaiApiKeyHint] = useState<string | null>(null);
  const [anthropicApiKeyHint, setAnthropicApiKeyHint] = useState<string | null>(null);
  const [openaiConnected, setOpenaiConnected] = useState(false);
  const [anthropicConnected, setAnthropicConnected] = useState(false);
  const [aiInstructions, setAiInstructions] = useState("");
  const [aiSaving, setAiSaving] = useState(false);
  const [aiSaved, setAiSaved] = useState(false);
  const [coreOnline, setCoreOnline] = useState<boolean | null>(null);
  const [coreUrl, setCoreUrl] = useState("");
  const [activeSection, setActiveSection] = useState<SettingsSectionId>("profile");
  const hiddenSidebarCount = hiddenSidebarItemIds.length;

  useEffect(() => {
    initSidebarPreferences();

    async function loadProfile() {
      const user = await getBrowserUser();
      if (user) {
        setEmail(user.email || "");
        setFullName(user.user_metadata?.full_name || "");
      }

      const aiRes = await fetch("/api/ai/settings");
      if (aiRes.ok) {
        const aiData = await aiRes.json();
        setAiProvider(aiData.provider);
        setAiModel(aiData.model);
        setOpenaiConnected(aiData.openaiConnected);
        setAnthropicConnected(aiData.anthropicConnected);
        setOpenaiApiKeyHint(aiData.openaiApiKeyHint);
        setAnthropicApiKeyHint(aiData.anthropicApiKeyHint);
        setAiInstructions(aiData.customInstructions || "");
      }

      const statusRes = await fetch("/api/ai/status");
      if (statusRes.ok) {
        const statusData = await statusRes.json();
        setCoreOnline(statusData.coreOnline);
        setCoreUrl(statusData.coreUrl || "");
      }
      setLoading(false);
    }
    void loadProfile();
  }, [initSidebarPreferences, supabase]);

  async function handleSave() {
    setSaving(true);
    setSaved(false);

    const { data: authData, error: authError } = await supabase.auth.updateUser({
      data: { full_name: fullName },
    });

    if (!authError && authData.user?.id) {
      await supabase
        .from("profiles")
        .update({ full_name: fullName })
        .eq("id", authData.user.id);
    }

    setSaving(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  async function handleSignOut() {
    setSigningOut(true);
    await supabase.auth.signOut();
    router.push("/login");
    router.refresh();
  }

  async function handleSaveAISettings(options?: {
    clearOpenAIKey?: boolean;
    clearAnthropicKey?: boolean;
  }) {
    setAiSaving(true);
    setAiSaved(false);

    const res = await fetch("/api/ai/settings", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        provider: aiProvider,
        model: aiModel,
        openaiApiKey: openaiApiKey.trim() || undefined,
        anthropicApiKey: anthropicApiKey.trim() || undefined,
        clearOpenAIKey: Boolean(options?.clearOpenAIKey),
        clearAnthropicKey: Boolean(options?.clearAnthropicKey),
        customInstructions: aiInstructions,
      }),
    });

    if (res.ok) {
      const data = await res.json();
      setOpenaiConnected(data.openaiConnected);
      setAnthropicConnected(data.anthropicConnected);
      setOpenaiApiKeyHint(data.openaiApiKeyHint);
      setAnthropicApiKeyHint(data.anthropicApiKeyHint);
      setOpenaiApiKey("");
      setAnthropicApiKey("");
      setAiSaved(true);
      setTimeout(() => setAiSaved(false), 2000);
    }

    const statusRes = await fetch("/api/ai/status");
    if (statusRes.ok) {
      const statusData = await statusRes.json();
      setCoreOnline(statusData.coreOnline);
      setCoreUrl(statusData.coreUrl || "");
    }

    setAiSaving(false);
  }

  async function handleRedeemCode() {
    if (!promoCode.trim()) return;
    setPromoLoading(true);
    setPromoError(null);
    setPromoSuccess(null);

    try {
      const res = await fetch("/api/codes/redeem", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code: promoCode.trim() }),
      });

      const data = await res.json().catch(() => null) as {
        ok?: boolean;
        plan?: string;
        duration_months?: number;
        granted_until?: string;
        error?: string;
      } | null;

      if (res.ok && data?.ok) {
        setPromoSuccess({
          plan: data.plan!,
          duration_months: data.duration_months!,
          granted_until: data.granted_until!,
        });
        setPromoCode("");
      } else {
        setPromoError(data?.error ?? "Unbekannter Fehler");
      }
    } catch {
      setPromoError("Code konnte nicht eingelöst werden.");
    } finally {
      setPromoLoading(false);
    }
  }

  function handleProviderChange(value: AIProvider) {
    setAiProvider(value);
    setAiModel(getDefaultModel(value));
  }

  const activeSectionMeta = SETTINGS_SECTIONS.find((section) => section.id === activeSection) ?? SETTINGS_SECTIONS[0];
  const ActiveSectionIcon = activeSectionMeta.icon;
  const visibleSidebarCount = sidebarNavItems.length - hiddenSidebarCount;

  function renderFeatureControl(item: (typeof sidebarNavItems)[number], index: number, total: number) {
    const visible = !hiddenSidebarItemIds.includes(item.id);
    const favorite = favoriteSidebarItemIds.includes(item.id);
    const inMobileDock = mobileDockItemIds.includes(item.id);
    const mobileDockFull = mobileDockItemIds.length >= 5 && !inMobileDock;

    return (
      <div
        key={item.id}
        className={cn(
          "flex min-h-12 items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors",
          visible
            ? "border-foreground/10 bg-background text-foreground hover:bg-accent/60"
            : "border-border bg-muted/30 text-muted-foreground hover:bg-muted/50"
        )}
      >
        <button
          type="button"
          onClick={() => toggleSidebarItem(item.id)}
          className={cn(
            "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition-colors",
            visible
              ? "border-primary/30 bg-primary/10 text-primary hover:bg-primary/15"
              : "border-muted-foreground/20 bg-muted/40 text-muted-foreground hover:bg-muted/60"
          )}
          title={visible ? "Feature ausblenden" : "Feature einblenden"}
        >
          {visible ? <Eye className="h-4 w-4" /> : <EyeOff className="h-4 w-4" />}
        </button>
        <item.icon className="h-4 w-4 shrink-0 text-muted-foreground" />
        <span className="min-w-0 flex-1 font-medium">{item.name}</span>
        <button
          type="button"
          onClick={() => toggleFavoriteSidebarItem(item.id)}
          disabled={!visible}
          className={cn(
            "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-colors disabled:opacity-30",
            favorite ? "bg-amber-500/15 text-amber-500" : "text-muted-foreground hover:bg-muted hover:text-foreground"
          )}
          title={favorite ? "Aus Desktop-Dock entfernen" : "In Desktop-Dock pinnen"}
        >
          <Star className={cn("h-4 w-4", favorite && "fill-current")} />
        </button>
        <button
          type="button"
          onClick={() => toggleMobileDockItem(item.id)}
          disabled={!visible || mobileDockFull}
          className={cn(
            "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-colors disabled:opacity-30",
            inMobileDock ? "bg-sky-500/15 text-sky-500" : "text-muted-foreground hover:bg-muted hover:text-foreground"
          )}
          title={inMobileDock ? "Aus Mobile-Dock entfernen" : mobileDockFull ? "Mobile-Dock ist voll" : "In Mobile-Dock legen"}
        >
          <Smartphone className="h-4 w-4" />
        </button>
        <div className="flex shrink-0 items-center gap-1">
          <button
            type="button"
            onClick={() => moveSidebarItem(item.id, "up")}
            disabled={index === 0}
            className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-25"
            title="Nach oben"
          >
            <ArrowUp className="h-4 w-4" />
          </button>
          <button
            type="button"
            onClick={() => moveSidebarItem(item.id, "down")}
            disabled={index === total - 1}
            className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-25"
            title="Nach unten"
          >
            <ArrowDown className="h-4 w-4" />
          </button>
        </div>
      </div>
    );
  }

  function renderLegendPill(icon: LucideIcon, label: string) {
    const Icon = icon;
    return (
      <span className="inline-flex items-center gap-1.5 rounded-full border border-border bg-background px-2.5 py-1 text-xs text-muted-foreground">
        <Icon className="h-3.5 w-3.5" />
        {label}
      </span>
    );
  }

  function renderPresetCard(preset: (typeof navigationPresets)[number]) {
    return (
      <button
        key={preset.id}
        type="button"
        onClick={() => applyNavigationPreset(preset.id)}
        className="rounded-xl border border-border bg-background/70 p-4 text-left transition-colors hover:border-primary/30 hover:bg-accent/40"
      >
        <div className="flex items-center gap-2">
          <Sparkles className="h-4 w-4 text-primary" />
          <p className="text-sm font-semibold">{preset.name}</p>
        </div>
        <p className="mt-1 text-xs leading-relaxed text-muted-foreground">{preset.description}</p>
      </button>
    );
  }

  function renderFeatureGroup(label: string, items: typeof sidebarNavItems) {
    const orderedItems = orderSidebarItems(items, sidebarCustomOrderIds);

    return (
      <div>
        <p className="mb-2 text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground">
          {label}
        </p>
        <div className="grid gap-2">
          {orderedItems.map((item, index) => renderFeatureControl(item, index, orderedItems.length))}
        </div>
      </div>
    );
  }

  function renderMobileDockPreview() {
    const dockItems = mobileDockItemIds
      .map((id) => sidebarNavItems.find((item) => item.id === id))
      .filter((item): item is (typeof sidebarNavItems)[number] => Boolean(item));

    return (
      <div className="rounded-xl border border-border bg-background/70 px-4 py-3">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-sm font-medium">Mobile Dock</p>
            <p className="text-xs text-muted-foreground">{dockItems.length}/5 Slots belegt</p>
          </div>
          <div className="flex flex-wrap gap-2">
            {dockItems.length > 0 ? dockItems.map((item) => (
              <span key={item.id} className="inline-flex items-center gap-1.5 rounded-full border border-sky-500/20 bg-sky-500/10 px-2.5 py-1 text-xs text-sky-600 dark:text-sky-300">
                <item.icon className="h-3.5 w-3.5" />
                {item.name}
              </span>
            )) : (
              <span className="text-xs text-muted-foreground">Keine Mobile-Favoriten gesetzt.</span>
            )}
          </div>
        </div>
      </div>
    );
  }

  function renderSectionContent() {
    if (activeSection === "profile") {
      return (
        <div className="space-y-6">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" value={email} disabled className="opacity-60" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="name">Display name</Label>
              <Input
                id="name"
                value={fullName}
                onChange={(e) => setFullName(e.target.value)}
                placeholder="Your name"
                disabled={loading}
              />
            </div>
          </div>
          <div className="flex flex-wrap items-center gap-3 border-t border-border pt-5">
            <Button onClick={handleSave} disabled={saving || loading} size="sm">
              <Save className="h-4 w-4" />
              {saving ? "Saving..." : "Save profile"}
            </Button>
            {saved && <span className="text-sm text-green-600">Saved</span>}
          </div>
        </div>
      );
    }

    if (activeSection === "appearance") {
      return (
        <div className="space-y-5">
          <div className="grid rounded-xl border border-border bg-muted/30 p-1 sm:grid-cols-3">
            {THEMES.map((t) => (
              <button
                key={t.value}
                type="button"
                onClick={() => setTheme(t.value)}
                className={cn(
                  "flex min-h-12 items-center justify-center gap-2 rounded-lg px-3 text-sm font-medium transition-colors",
                  theme === t.value
                    ? "bg-background text-foreground shadow-sm"
                    : "text-muted-foreground hover:text-foreground"
                )}
              >
                <t.icon className="h-4 w-4" />
                {t.label}
              </button>
            ))}
          </div>
          <div className="rounded-xl border border-border bg-background/60 px-4 py-3">
            <p className="text-sm font-medium">Current theme</p>
            <p className="text-sm capitalize text-muted-foreground">{theme}</p>
          </div>
        </div>
      );
    }

    if (activeSection === "sidebar") {
      return (
        <div className="space-y-6">
          <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-muted/30 px-4 py-3">
            <div>
              <p className="text-sm font-medium">
                {visibleSidebarCount} of {sidebarNavItems.length} items visible
              </p>
              <p className="text-xs text-muted-foreground">
                Hidden items still work through search, direct links, and Settings.
              </p>
            </div>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={showAllSidebarItems}
              disabled={hiddenSidebarCount === 0}
            >
              <RotateCcw className="h-4 w-4" />
              Show all
            </Button>
          </div>

          <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
            {navigationPresets.map(renderPresetCard)}
          </div>

          <div className="flex flex-wrap gap-2">
            {renderLegendPill(Eye, "sichtbar")}
            {renderLegendPill(Star, "Desktop-Dock")}
            {renderLegendPill(Smartphone, "Mobile-Dock")}
            {renderLegendPill(ArrowUp, "Reihenfolge")}
          </div>

          {renderMobileDockPreview()}

          <div className="space-y-5">
            {renderFeatureGroup("Main", sidebarTopNav)}

            {sidebarNavGroups.map((group) => (
              <div key={group.id}>{renderFeatureGroup(group.label, group.items)}</div>
            ))}
          </div>
        </div>
      );
    }

    if (activeSection === "ai") {
      return (
        <div className="space-y-6">
          <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-muted/30 px-4 py-3">
            <div className="flex items-center gap-3">
              <span
                className={cn(
                  "h-2.5 w-2.5 rounded-full",
                  coreOnline ? "bg-green-500" : "bg-amber-500"
                )}
              />
              <div>
                <p className="text-sm font-medium">Mindavio Core</p>
                <p className="text-xs text-muted-foreground">
                  {coreOnline ? "Online" : "Offline"}{coreUrl ? ` · ${coreUrl}` : ""}
                </p>
              </div>
            </div>
            <span
              className={cn(
                "rounded-full px-2 py-0.5 text-xs font-medium",
                coreOnline ? "bg-green-500/15 text-green-600" : "bg-amber-500/15 text-amber-600"
              )}
            >
              {coreOnline ? "Ready" : "Fallback needed"}
            </span>
          </div>

          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="ai-provider">Provider</Label>
              <Select
                id="ai-provider"
                value={aiProvider}
                onChange={(e) => handleProviderChange(e.target.value as AIProvider)}
                disabled={loading || aiSaving}
              >
                {AI_PROVIDER_OPTIONS.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </Select>
              <p className="text-xs text-muted-foreground">
                {AI_PROVIDER_OPTIONS.find((option) => option.value === aiProvider)?.description}
              </p>
            </div>

            <div className="space-y-2">
              <Label htmlFor="ai-model">Model</Label>
              <Select
                id="ai-model"
                value={aiModel}
                onChange={(e) => setAiModel(e.target.value)}
                disabled={loading || aiSaving}
              >
                {AI_MODEL_OPTIONS[aiProvider].map((model) => (
                  <option key={model} value={model}>
                    {model}
                  </option>
                ))}
              </Select>
            </div>
          </div>

          <div className="grid gap-3">
            <div className="rounded-xl border border-border bg-background/60 p-4">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <Label htmlFor="openai-key" className="flex items-center gap-2">
                  <KeyRound className="h-4 w-4" />
                  OpenAI
                </Label>
                <span className={cn("rounded-full px-2 py-0.5 text-xs font-medium", openaiConnected ? "bg-green-500/15 text-green-600" : "bg-muted text-muted-foreground")}>
                  {openaiConnected ? `Connected ${openaiApiKeyHint || ""}` : "Not connected"}
                </span>
              </div>
              <Input
                id="openai-key"
                type="password"
                value={openaiApiKey}
                onChange={(e) => setOpenaiApiKey(e.target.value)}
                placeholder={openaiConnected ? "Paste a new key to replace it" : "Paste your OpenAI API key"}
                disabled={loading || aiSaving}
                className="mt-3"
              />
            </div>

            <div className="rounded-xl border border-border bg-background/60 p-4">
              <div className="flex flex-wrap items-center justify-between gap-2">
                <Label htmlFor="anthropic-key" className="flex items-center gap-2">
                  <KeyRound className="h-4 w-4" />
                  Claude
                </Label>
                <span className={cn("rounded-full px-2 py-0.5 text-xs font-medium", anthropicConnected ? "bg-green-500/15 text-green-600" : "bg-muted text-muted-foreground")}>
                  {anthropicConnected ? `Connected ${anthropicApiKeyHint || ""}` : "Not connected"}
                </span>
              </div>
              <Input
                id="anthropic-key"
                type="password"
                value={anthropicApiKey}
                onChange={(e) => setAnthropicApiKey(e.target.value)}
                placeholder={anthropicConnected ? "Paste a new key to replace it" : "Paste your Anthropic API key"}
                disabled={loading || aiSaving}
                className="mt-3"
              />
            </div>
          </div>

          {(aiProvider === "openai" && !openaiConnected) ||
          (aiProvider === "anthropic" && !anthropicConnected) ? (
            <div className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-700 dark:text-amber-300">
              This provider has no saved key yet. Mindavio will automatically fall back to Mindavio Core.
            </div>
          ) : null}

          <div className="space-y-2">
            <Label htmlFor="ai-instructions" className="flex items-center gap-2">
              <Sparkles className="h-4 w-4" />
              Custom AI instructions
            </Label>
            <Textarea
              id="ai-instructions"
              value={aiInstructions}
              onChange={(e) => setAiInstructions(e.target.value)}
              placeholder="Example: Be direct, answer in German, and prefer short action plans."
              disabled={loading || aiSaving}
              className="min-h-32"
            />
          </div>

          <div className="flex flex-wrap items-center gap-3 border-t border-border pt-5">
            <Button onClick={() => handleSaveAISettings()} disabled={aiSaving || loading} size="sm">
              <Save className="h-4 w-4" />
              {aiSaving ? "Saving..." : "Save AI settings"}
            </Button>
            {openaiConnected && (
              <Button variant="outline" onClick={() => handleSaveAISettings({ clearOpenAIKey: true })} disabled={aiSaving || loading} size="sm">
                Remove OpenAI key
              </Button>
            )}
            {anthropicConnected && (
              <Button variant="outline" onClick={() => handleSaveAISettings({ clearAnthropicKey: true })} disabled={aiSaving || loading} size="sm">
                Remove Claude key
              </Button>
            )}
            {aiSaved && <span className="text-sm text-green-600">Saved</span>}
          </div>
        </div>
      );
    }

    if (activeSection === "billing") {
      return (
        <div className="space-y-4">
          <button
            onClick={() => router.push("/settings/billing")}
            className="flex w-full items-center justify-between rounded-xl border border-border bg-background/60 px-4 py-4 text-left transition-colors hover:bg-accent"
          >
            <div>
              <p className="text-sm font-semibold">Abonnement verwalten</p>
              <p className="text-sm text-muted-foreground">Plan upgraden, Rechnungseinstellungen öffnen und Billing verwalten.</p>
            </div>
            <ChevronRight className="h-4 w-4 text-muted-foreground" />
          </button>
        </div>
      );
    }

    if (activeSection === "promo") {
      return (
        <div className="space-y-4">
          {promoSuccess ? (
            <div className="flex items-start gap-3 rounded-xl border border-green-500/30 bg-green-500/10 p-4">
              <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-green-500" />
              <div className="space-y-1">
                <p className="text-sm font-semibold text-green-600">Code erfolgreich eingelöst!</p>
                <p className="text-sm text-muted-foreground">
                  Plan <span className="font-medium capitalize text-foreground">{promoSuccess.plan.replace("_", " ")}</span> für{" "}
                  <span className="font-medium text-foreground">{promoSuccess.duration_months} Monat{promoSuccess.duration_months !== 1 ? "e" : ""}</span> aktiviert.
                </p>
                <p className="text-xs text-muted-foreground">
                  Gültig bis {new Date(promoSuccess.granted_until).toLocaleDateString("de-DE", { day: "2-digit", month: "long", year: "numeric" })}
                </p>
                <button
                  onClick={() => setPromoSuccess(null)}
                  className="mt-1 text-xs text-green-600 underline underline-offset-2 hover:text-green-500"
                >
                  Weiteren Code einlösen
                </button>
              </div>
            </div>
          ) : (
            <>
              <div className="flex gap-2">
                <Input
                  value={promoCode}
                  onChange={(e) => {
                    setPromoCode(e.target.value.toUpperCase());
                    setPromoError(null);
                  }}
                  onKeyDown={(e) => { if (e.key === "Enter") void handleRedeemCode(); }}
                  placeholder="z. B. WELCOME3M"
                  className="font-mono uppercase tracking-widest"
                  disabled={promoLoading}
                  maxLength={32}
                />
                <Button onClick={() => void handleRedeemCode()} disabled={promoLoading || !promoCode.trim()} className="shrink-0">
                  {promoLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : "Einlösen"}
                </Button>
              </div>
              {promoError && (
                <div className="flex items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2.5">
                  <AlertCircle className="h-4 w-4 shrink-0 text-destructive" />
                  <p className="text-sm text-destructive">{promoError}</p>
                </div>
              )}
            </>
          )}
        </div>
      );
    }

    return (
      <div className="space-y-4">
        <div className="rounded-xl border border-destructive/20 bg-destructive/5 p-4">
          <p className="text-sm font-semibold">Sign out</p>
          <p className="mt-1 text-sm text-muted-foreground">
            End the current session on this device.
          </p>
          <Button
            variant="destructive"
            onClick={handleSignOut}
            disabled={signingOut}
            size="sm"
            className="mt-4"
          >
            <LogOut className="h-4 w-4" />
            {signingOut ? "Signing out..." : "Sign out"}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto flex w-full max-w-6xl flex-col gap-6">
      <div className="flex flex-wrap items-end justify-between gap-4 border-b border-border pb-6">
        <div>
          <div className="mb-2 flex items-center gap-2 text-sm font-medium text-muted-foreground">
            <Settings className="h-4 w-4" />
            Mindavio Console
          </div>
          <h1 className="text-3xl font-bold tracking-tight">Settings</h1>
          <p className="mt-2 max-w-2xl text-sm text-muted-foreground">
            Keep the workspace quiet, personal, and fast to navigate.
          </p>
        </div>

        <div className="grid grid-cols-1 gap-2 text-right sm:grid-cols-2 lg:grid-cols-3">
          <div className="rounded-lg border border-border bg-muted/30 px-3 py-2">
            <p className="text-lg font-semibold">{visibleSidebarCount}</p>
            <p className="text-[11px] uppercase tracking-[0.14em] text-muted-foreground">Visible</p>
          </div>
          <div className="rounded-lg border border-border bg-muted/30 px-3 py-2">
            <p className="text-lg font-semibold">{theme}</p>
            <p className="text-[11px] uppercase tracking-[0.14em] text-muted-foreground">Theme</p>
          </div>
          <div className="rounded-lg border border-border bg-muted/30 px-3 py-2">
            <p className={cn("text-lg font-semibold", coreOnline ? "text-green-600" : "text-amber-600")}>
              {coreOnline ? "On" : "Off"}
            </p>
            <p className="text-[11px] uppercase tracking-[0.14em] text-muted-foreground">Core</p>
          </div>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-[260px_minmax(0,1fr)]">
        <aside className="lg:sticky lg:top-20 lg:self-start">
          <div className="overflow-hidden rounded-xl border border-border bg-card">
            <div className="border-b border-border px-4 py-3">
              <p className="text-xs font-semibold uppercase tracking-[0.16em] text-muted-foreground">
                Sections
              </p>
            </div>
            <nav className="p-2">
              {SETTINGS_SECTIONS.map((section) => {
                const Icon = section.icon;
                const active = activeSection === section.id;

                return (
                  <button
                    key={section.id}
                    type="button"
                    onClick={() => setActiveSection(section.id)}
                    className={cn(
                      "flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors",
                      active ? "bg-accent text-foreground" : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
                    )}
                  >
                    <Icon className={cn("h-4 w-4 shrink-0", active ? "text-primary" : "text-muted-foreground")} />
                    <span className="min-w-0">
                      <span className="block text-sm font-medium leading-tight">{section.label}</span>
                      <span className="block truncate text-xs text-muted-foreground">{section.description}</span>
                    </span>
                  </button>
                );
              })}
            </nav>
          </div>
        </aside>

        <section className="min-w-0 overflow-hidden rounded-xl border border-border bg-card">
          <div className="flex items-start gap-3 border-b border-border px-5 py-5">
            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-border bg-muted/40">
              <ActiveSectionIcon className="h-5 w-5 text-primary" />
            </div>
            <div>
              <h2 className="text-xl font-semibold tracking-tight">{activeSectionMeta.label}</h2>
              <p className="mt-1 text-sm text-muted-foreground">{activeSectionMeta.description}</p>
            </div>
          </div>
          <div className="p-5">
            {renderSectionContent()}
          </div>
        </section>
      </div>
    </div>
  );
}
