"use client";

import darkLogo from "@/assets/logos/dark.svg";
// import logo from "@/assets/logos/main.svg";
import Image from "next/image";
import { useEffect, useState } from "react";

interface GeneralSettings {
  logo?: string;
}

export function Logo() {
  const [settings, setSettings] = useState<GeneralSettings | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await fetch('/api/general-settings');
        const result = await response.json();
        if (result.success && result.data) {
          setSettings(result.data);
        }
      } catch (error) {
        console.error('Failed to fetch settings:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchSettings();

    const refreshLogo = () => fetchSettings()

    window.addEventListener('logo-updated', refreshLogo)

    return () => window.removeEventListener('logo-updated', refreshLogo)
  }, []);


  // Use uploaded logo if available, otherwise use default logo
  if (!loading && settings?.logo) {
    console.log(settings?.logo);
    
    return (
      <div className="relative h-14 flex justify-center max-w-[100%]">
        <img
          src={settings?.logo}
          // fill
          className="object-contain max-w-[100%] max-h-[100%]"
          alt="Logo"
          role="presentation"
          // quality={100}
        />
      </div>
    );
  }

  // Fallback to default logo
  return (
    <div className="relative h-8 max-w-[10.847rem]">
      <img
        src={"logo"}
        // fill
        className="dark:hidden"
        alt=" "
        role="presentation"
        // quality={100}
      />

      <img
        src={darkLogo}
        // fill
        className="hidden dark:block"
        alt=" "
        role="presentation"
        // quality={100}
      />
    </div>
  );
}
