"use client";

import React, { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Phone, MapPin, Send, Sparkles, Clock, ArrowUpRight } from "lucide-react";
import { useSiteSettings } from "@/components/SettingsProvider";
import { BUSINESS_CONFIG, getWhatsAppUrl } from "@/config/business";

export default function Footer() {
  const pathname = usePathname();
  const { enable_promotions, enable_promocard } = useSiteSettings();
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [subMessage, setSubMessage] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  // Do not show public footer in admin backoffice
  if (pathname.startsWith("/admin")) {
    return null;
  }

  const handleSubscribe = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setSubMessage(null);
    try {
      const res = await fetch("/api/promocard/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, phone })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "Error al suscribir");
      setSubMessage("✅ ¡Registrado en PromoCard! Tus pedidos acumulan puntos.");
      setName("");
      setPhone("");
    } catch (err: any) {
      setSubMessage(`❌ ${err.message}`);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <footer className="bg-[#083F78] text-[#F7F5F0] pt-20 pb-12 border-t-2 border-[#ffc324]/30">
      <div className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12 grid grid-cols-1 md:grid-cols-3 gap-14 mb-16">
        {/* Brand & Artisan Sourdough Info */}
        <div className="space-y-5">
          <Link href="/" className="inline-block py-1">
            <img
              src="/assets/LogoSanlore_White.png"
              alt="Sanlore Pizza - Pizzería Artesanal al Horno Tipo Siciliano"
              className="h-11 w-auto object-contain"
            />
          </Link>
          <p className="text-xs text-[#a1a39e] leading-relaxed font-artisan-sans max-w-sm">
            Pizzería artesanal con horno tipo siciliano en Pereira (Sector Galicia).
            Masa madurada con paciencia por 48 horas, ingredientes frescos de primera calidad y auténtico sabor tradicional.
          </p>

          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-[6px] text-[11px] font-black uppercase tracking-wider bg-[#67d2f2]/15 text-[#67d2f2] border border-[#67d2f2]/25">
            <Sparkles size={12} />
            <span>Pizzería 100% Artesanal</span>
          </div>

          <div className="space-y-2.5 text-xs text-[#F7F5F0]/90 pt-2 font-artisan-sans">
            <div className="flex items-center gap-2.5">
              <MapPin size={15} className="text-[#67d2f2] shrink-0" />
              <span>{BUSINESS_CONFIG.location.fullAddress}</span>
            </div>
            <div className="flex items-center gap-2.5">
              <Phone size={15} className="text-[#67d2f2] shrink-0" />
              <a
                href={`tel:${BUSINESS_CONFIG.whatsapp.callNumber}`}
                className="hover:text-[#67d2f2] transition font-mono"
              >
                {BUSINESS_CONFIG.whatsapp.formattedNumber}
              </a>
            </div>
          </div>
        </div>

        {/* Quick Links & Minimal Directory */}
        <div className="space-y-5">
          <h4
            className="text-xs font-bold text-[#ffc324] !text-[#ffc324] tracking-widest uppercase border-b border-white/10 pb-3"
            style={{ color: "#ffc324" }}
          >
            Navegación & Carta
          </h4>
          <ul className="space-y-3 text-xs font-artisan-sans">
            <li>
              <Link href="/menu" className="text-[#a1a39e] hover:text-[#67d2f2] transition">
                Carta & Pizzas Artesanales
              </Link>
            </li>
            {enable_promotions && (
              <li>
                <Link href="/promos" className="text-[#a1a39e] hover:text-[#67d2f2] transition">
                  Combos & Promociones
                </Link>
              </li>
            )}
            {enable_promocard && (
              <li>
                <Link href="/promocard" className="text-[#a1a39e] hover:text-[#67d2f2] transition">
                  PromoCard (Tu 10ma Pizza Gratis)
                </Link>
              </li>
            )}
            <li>
              <Link href="/contacto" className="text-[#a1a39e] hover:text-[#67d2f2] transition">
                Zona de Cobertura Galicia & Pereira
              </Link>
            </li>
          </ul>

          <div className="flex items-center gap-3 pt-3">
            {BUSINESS_CONFIG.social.instagram.enabled && (
              <a
                href={BUSINESS_CONFIG.social.instagram.url}
                target="_blank"
                rel="noopener noreferrer"
                className="p-2.5 bg-white/5 hover:bg-[#67d2f2] hover:text-[#083F78] text-white rounded-[8px] transition border border-white/10"
                aria-label="Instagram Sanlore Pizza"
                title={BUSINESS_CONFIG.social.instagram.handle}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
                  <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
                  <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
                </svg>
              </a>
            )}
            {BUSINESS_CONFIG.social.facebook.enabled && (
              <a
                href={BUSINESS_CONFIG.social.facebook.url}
                target="_blank"
                rel="noopener noreferrer"
                className="p-2.5 bg-white/5 hover:bg-[#67d2f2] hover:text-[#083F78] text-white rounded-[8px] transition border border-white/10"
                aria-label="Facebook Sanlore Pizza"
                title={BUSINESS_CONFIG.social.facebook.handle}
              >
                <svg width="15" height="15" 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>
              </a>
            )}
            {BUSINESS_CONFIG.social.tiktok.enabled && (
              <a
                href={BUSINESS_CONFIG.social.tiktok.url}
                target="_blank"
                rel="noopener noreferrer"
                className="p-2.5 bg-white/5 hover:bg-[#67d2f2] hover:text-[#083F78] text-white rounded-[8px] transition border border-white/10"
                aria-label="TikTok Sanlore Pizza"
                title={BUSINESS_CONFIG.social.tiktok.handle}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64c.29 0 .58.04.85.12V9.4a6.33 6.33 0 0 0-.85-.06A6.34 6.34 0 0 0 3.15 15.7a6.34 6.34 0 0 0 10.82 4.48c.34-.34.62-.72.84-1.14.07-.15.14-.31.2-.47V9.08c1.5 1.07 3.32 1.7 5.28 1.74v-3.46a4.82 4.82 0 0 1-.7-.67z"/>
                </svg>
              </a>
            )}
          </div>
        </div>

        {/* 3rd Column: PromoCard Signup Form OR Domicilios Card */}
        {enable_promocard ? (
          <div className="bg-white/5 border border-white/10 rounded-[8px] p-7 space-y-4">
            <div className="space-y-1.5 border-b border-white/10 pb-3">
              <div className="flex items-center gap-2">
                <Sparkles size={16} className="text-[#ffc324]" />
                <h4
                  className="text-xs font-bold text-[#ffc324] !text-[#ffc324] tracking-widest uppercase font-artisan-sans"
                  style={{ color: "#ffc324" }}
                >
                  Fidelidad PromoCard
                </h4>
              </div>
              <p className="text-xs text-[#F7F5F0]/80 leading-relaxed font-artisan-sans pt-1">
                Registra tu WhatsApp y acumula pedidos sin cupones físicos. Tu décima pizza artesanal es por la casa.
              </p>
            </div>

            <form onSubmit={handleSubscribe} className="space-y-3 font-artisan-sans">
              <input
                type="text"
                placeholder="Tu Nombre Completo"
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full bg-[#F7F5F0] border border-[#a1a39e]/30 rounded-[8px] px-3.5 py-2.5 text-xs text-[#083F78] placeholder-slate-400 focus:outline-none focus:border-[#67d2f2]"
                required
              />
              <input
                type="tel"
                placeholder="Celular (ej. 3001526282)"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="w-full bg-[#F7F5F0] border border-[#a1a39e]/30 rounded-[8px] px-3.5 py-2.5 text-xs text-[#083F78] placeholder-slate-400 focus:outline-none focus:border-[#67d2f2] font-mono"
                required
              />
              <button
                type="submit"
                disabled={submitting}
                className="w-full bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black py-3 rounded-[8px] text-xs uppercase tracking-wider transition flex items-center justify-center gap-2 disabled:opacity-50 shadow-sm shadow-[#ffc324]/20"
              >
                <Send size={13} />
                <span>{submitting ? "Registrando..." : "Activar Mi PromoCard"}</span>
              </button>
            </form>

            {subMessage && (
              <p className="text-[11px] font-semibold text-center text-[#ffc324] mt-1">{subMessage}</p>
            )}
          </div>
        ) : (
          <div className="bg-white/5 border border-white/10 rounded-[8px] p-7 space-y-4">
            <div className="space-y-1.5 border-b border-white/10 pb-3">
              <div className="flex items-center gap-2">
                <Clock size={16} className="text-[#ffc324]" />
                <h4
                  className="text-xs font-bold text-[#ffc324] !text-[#ffc324] tracking-widest uppercase font-artisan-sans"
                  style={{ color: "#ffc324" }}
                >
                  Horarios & Domicilios
                </h4>
              </div>
              <div className="space-y-1.5 pt-1 text-xs text-[#F7F5F0]/90 font-artisan-sans">
                {BUSINESS_CONFIG.schedule.shifts.map((shift, idx) => (
                  <div key={idx} className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-0.5 sm:gap-2">
                    <span className="text-white font-bold">{shift.days}:</span>
                    <span className="text-[#ffc324] font-semibold">{shift.hours}</span>
                  </div>
                ))}
                {BUSINESS_CONFIG.schedule.deliveryNotice && (
                  <p className="text-[11px] text-[#a1a39e] pt-1 leading-relaxed">
                    {BUSINESS_CONFIG.schedule.deliveryNotice}
                  </p>
                )}
              </div>
            </div>
            <div className="pt-2">
              <a
                href={getWhatsAppUrl("¡Hola Sanlore Pizza! Deseo hacer un pedido a domicilio en Pereira / Galicia 🍕")}
                target="_blank"
                rel="noopener noreferrer"
                className="w-full bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black py-3 rounded-[8px] text-xs uppercase tracking-wider transition flex items-center justify-center gap-2 shadow-sm shadow-[#ffc324]/20"
              >
                <span>Pedir a Domicilio</span>
                <ArrowUpRight size={14} />
              </a>
            </div>
          </div>
        )}
      </div>

      <div className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12 border-t border-white/10 pt-8 flex flex-col sm:flex-row items-center justify-between text-xs text-[#a1a39e] gap-3">
        <p>© 2026 Sanlore Pizza. Pizzería Artesanal al Horno Tipo Siciliano.</p>
        <div className="flex items-center gap-4">
          <p>Sector Galicia, Pereira, Risaralda • Colombia</p>
          <span className="text-white/20">•</span>
          <Link
            href="/admin"
            className="text-[#a1a39e]/70 hover:text-[#ffc324] transition text-xs font-medium"
          >
            Acceso Admin
          </Link>
        </div>
      </div>
    </footer>
  );
}
