"use client";

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

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;

  // Browser Client inline erstellen
  const supabase = createBrowserClient(
    resolveSupabaseUrl(supabaseUrl)!,
    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>
  );
}
