"use client";

import { signOut } from "@/lib/actions/auth";
import { useRouter } from "next/navigation";
import { LogOut } from "lucide-react";
import { createBrowserClient } from "@supabase/ssr";

export function AdminLogoutButton() {
  const router = useRouter();

  // Supabase URL & Anon Key auslesen (für Browser-Client)
  const supabaseUrl = process.env.SUPABASE_URL || process.env.NEXT_PUBLIC_SUPABASE_URL;
  const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

  // Supabase URL Auflösung inline
  let resolvedUrl = supabaseUrl;
  if (resolvedUrl && typeof window !== "undefined") {
    try {
      const parsed = new URL(resolvedUrl);
      if (parsed.hostname === "supabase-kong" || parsed.hostname === "kong") {
        parsed.hostname = window.location.hostname;
        resolvedUrl = parsed.toString().replace(/\/$/, "");
      }
    } catch {
      resolvedUrl = resolvedUrl
        .replace("//supabase-kong", `//${window.location.hostname}`)
        .replace("//kong", `//${window.location.hostname}`);
    }
  }

  // Browser Client inline erstellen
  const supabase = createBrowserClient(
    resolvedUrl!,
    supabaseAnonKey!,
    {
      cookieOptions: {
        name: "webshop-auth-token",
      },
    }
  );

  const handleLogout = async () => {
    try {
      await signOut();
    } catch (error) {
      console.error("Fehler beim Abmelden:", error);
    }
    await supabase.auth.signOut();
    router.push("/");
    router.refresh();
  };

  return (
    <button
      onClick={handleLogout}
      className="flex w-full items-center gap-3 px-3 py-2 rounded-lg text-slate-400 hover:text-white hover:bg-white/5 transition-all text-left"
    >
      <LogOut className="w-5 h-5" />
      Abmelden
    </button>
  );
}
