"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import NewsletterForm from "./NewsletterForm";
import { useSettings } from "@/providers/SettingsProvider";
import Swal from "sweetalert2";

interface Category {
  id: string;
  name: string;
  slug: string;
}

interface FooterProps {
  categories?: Category[];
}

export default function Footer({ categories: initialCategories }: FooterProps) {
  const { storeName, settings } = useSettings();
  const [categories, setCategories] = useState<Category[]>(initialCategories || []);
  const [brandLogoUrl, setBrandLogoUrl] = useState("");

  useEffect(() => {
    if (initialCategories && initialCategories.length > 0) {
      setCategories(initialCategories);
      return;
    }

    const fetchCategories = async () => {
      try {
        const res = await fetch("/api/categories");
        if (res.ok) {
          const data = await res.json();
          setCategories(data);
        }
      } catch (err) {
        console.error("Failed to fetch footer categories:", err);
      }
    };
    fetchCategories();
  }, [initialCategories]);

  // Fetch brand settings
  useEffect(() => {
    const fetchBrandSettings = async () => {
      try {
        const res = await fetch("/api/admin/settings");
        if (res.ok) {
          const data = await res.json();
          if (data.brand_logo_url) setBrandLogoUrl(data.brand_logo_url);
        }
      } catch (err) {
        console.error("Failed to fetch brand settings:", err);
      }
    };
    fetchBrandSettings();

    // Listen for real-time updates when saving from admin
    const handleUpdate = () => fetchBrandSettings();
    window.addEventListener("brand-settings-updated", handleUpdate);
    return () => window.removeEventListener("brand-settings-updated", handleUpdate);
  }, []);

  return (
    <>
      {/* PREMIUM FOOTER */}
      <footer className="w-full bg-white text-zinc-900 border-t border-zinc-150 pt-16 pb-12 z-10 relative">
        <div className="max-w-7xl mx-auto px-6">
          <div className="grid grid-cols-2 md:grid-cols-5 gap-8 mb-12">
            
            {/* Brand column */}
            <div className="col-span-2 flex flex-col pr-0 md:pr-12">
              {brandLogoUrl ? (
                <div className="relative h-8 w-32 mb-4 self-start">
                  <Image src={brandLogoUrl} alt={storeName} fill className="object-contain" />
                </div>
              ) : (
                <span className="text-lg font-black tracking-widest uppercase mb-4">{storeName}</span>
              )}
              <p className="text-zinc-500 text-xs font-light leading-relaxed mb-6">
                Premium modern apparel carefully crafted with exquisite structural design and dynamic fabrics to outlast transient fashion trends.
              </p>
                <Link href="https://facebook.com" target="_blank" rel="noopener noreferrer" className="p-2 text-zinc-600 hover:text-zinc-950 hover:bg-zinc-50 transition-all rounded-full" aria-label="Facebook">
                  <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"></path></svg>
                </Link>
                <Link href="https://twitter.com" target="_blank" rel="noopener noreferrer" className="p-2 text-zinc-600 hover:text-zinc-950 hover:bg-zinc-50 transition-all rounded-full" aria-label="Twitter">
                  <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z"></path></svg>
                </Link>
              </div>

            {/* Shop Links */}
            <div>
              <h4 className="text-xs font-bold tracking-widest uppercase mb-4 text-zinc-955">Shop Catalog</h4>
              <ul className="space-y-2.5 text-xs text-zinc-500 font-light">
                {categories.slice(0, 4).map(c => (
                  <li key={c.id}>
                    <Link href={`/category/${c.slug}`} className="hover:text-zinc-900 transition-colors uppercase">{c.name}</Link>
                  </li>
                ))}
                <li>
                  <Link href="/shop" className="hover:text-zinc-900 transition-colors uppercase">All Products</Link>
                </li>
              </ul>
            </div>

            {/* Support Links */}
            <div>
              <h4 className="text-xs font-bold tracking-widest uppercase mb-4 text-zinc-955">Customer Help</h4>
              <ul className="space-y-2.5 text-xs text-zinc-500 font-light">
                <li><Link href="/pages/shipping-policy" className="hover:text-zinc-900 transition-colors">Shipping & Delivery</Link></li>
                <li><Link href="/pages/returns-exchanges" className="hover:text-zinc-900 transition-colors">Returns & Exchanges</Link></li>
                <li><Link href="/pages/size-charts" className="hover:text-zinc-900 transition-colors">Size Charts</Link></li>
                <li><Link href="/pages/contact-support" className="hover:text-zinc-900 transition-colors">Contact Support</Link></li>
              </ul>
            </div>

            {/* About Links */}
            <div>
              <h4 className="text-xs font-bold tracking-widest uppercase mb-4 text-zinc-955">Our Company</h4>
              <ul className="space-y-2.5 text-xs text-zinc-500 font-light">
                <li><Link href="/about" className="hover:text-zinc-900 transition-colors">About Our Brand</Link></li>
                {/* 
                <li><Link href="#" className="hover:text-zinc-900 transition-colors">Sustainability Commitments</Link></li>
                <li><Link href="#" className="hover:text-zinc-900 transition-colors">Careers at {storeName}</Link></li>
                <li><Link href="#" className="hover:text-zinc-900 transition-colors">Store Locations</Link></li>
                */}
                <li><Link href="/admin" className="hover:text-zinc-900 font-semibold text-zinc-950 transition-colors">Admin Dashboard</Link></li>
              </ul>
            </div>

          </div>

          {/* Copyright section */}
          <div className="border-t border-zinc-100 pt-8 flex flex-col sm:flex-row justify-between items-center text-xs text-zinc-400 gap-4">
            <span>&copy; {new Date().getFullYear()} ALL RIGHTS RESERVED.</span>
            <div className="flex space-x-6">
              <Link href="/pages/privacy-policy" className="hover:text-zinc-900 transition-colors">Privacy Policy</Link>
              <Link href="/pages/terms-of-use" className="hover:text-zinc-900 transition-colors">Terms of Use</Link>
              <Link href="/pages/accessibility-statement" className="hover:text-zinc-900 transition-colors">Accessibility Statement</Link>
            </div>
          </div>

        </div>
      </footer>



      {/* Floating Support Chat Bubble */}
      <div 
        onClick={() => Swal.fire({ text: `Our team is currently offline. Please drop us an email at ${settings["contact_email"] || "support@store.local"}`, confirmButtonColor: "#18181b" })}
        className="fixed bottom-6 right-6 z-50 w-14 h-14 bg-black rounded-full flex items-center justify-center shadow-2xl hover:scale-105 hover:bg-zinc-800 transition-all cursor-pointer group text-white"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 24 24"
          fill="currentColor"
          className="w-6 h-6 text-white group-hover:rotate-6 transition-transform duration-300"
        >
          <path
            fillRule="evenodd"
            d="M4.848 2.771A49.144 49.144 0 0 1 12 2.25c2.43 0 4.817.178 7.152.52 1.237.18 2.228 1.13 2.378 2.378.342 2.835.52 5.727.52 8.66 0 2.932-.178 5.823-.52 8.66-.15 1.247-1.14 2.197-2.378 2.378a47.6 47.6 0 0 1-5.112.399c-1.077.05-2.061-.318-2.776-1.107l-3.51-3.893a.75.75 0 0 0-1.11 0l-3.51 3.893c-.715.789-1.7 1.157-2.776 1.107a47.578 47.578 0 0 1-5.112-.399C1.666 19.807.676 18.857.526 17.61A49.03 49.03 0 0 1 0 13.808c0-3.66.27-7.25.792-10.758a.75.75 0 0 1 .741-.639h3.315Z"
            clipRule="evenodd"
          />
        </svg>
      </div>
    </>
  );
}
