'use client';
import { useEffect, useState, useRef } from 'react';
import Container from "../atoms/Container";
import FooterMolecule from "../molecules/FooterMolecule";
import { SocialIcons } from "../molecules/SocialIcons";
import Link from 'next/link';
import Image from 'next/image';
import Button from '../atoms/Button';
import Swal from 'sweetalert2';
import FreeConsultationModal from '../organisms/FreeConsultationModal';
import { FiMapPin, FiPhone, FiMail, FiClock } from 'react-icons/fi';
import { useModal } from '../../../app/hooks/useModal';
import { consultationStorage } from '../../../lib/consultationStorage';

const FooterOrganism = () => {
  const addresses = [
    {
      city: 'Lahore',
      address: 'Universities Page, 2nd Floor Faysal bank, Raja Market, Garden town, Lahore, Pakistan',
      map: '<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3401.491970140618!2d74.3230701!3d31.510645200000003!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x391903a687766e03%3A0xb3d2577d5a2fe6ce!2sUniversities%20Page%20%7C%20Italy%2C%20Germany%20%2CChina%2C%20UK%2C%20Poland%2C%20Europe%20best%20Study%20Abroad%20Education%20Visa%20Consultant!5e0!3m2!1sen!2s!4v1759831643225!5m2!1sen!2s" style="border:0;" width="750" height="450" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>',
      phones: ['+92 333 0033235', '+92 311 4998280', '+92 310 3162004'],
      emails: []
    },
    {
      city: 'Islamabad',
      address: 'Universities Page, Punjab market, Venus Plaza, 1st Floor, Office No. 1, Sector G13/4, Islamabad',
      map: '<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3321.2590897682767!2d72.9716407!3d33.650448!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x38dfbf4b4a8e73d7%3A0x8c11ea1b2c8571f9!2sUniversities%20Page%20%7C%20Italy%2C%20Germany%2C%20China%2C%20UK%2C%20Austria%2C%20Poland%2C%20Europe%20best%20Study%20Abroad%20Education%20Visa%20Consultant!5e0!3m2!1sen!2s!4v1759833695982!5m2!1sen!2s" width="750" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>',
      phones: ['+92 317 0174573', '+92 310 3172004', '+92 334 9990308'],
      emails: []
    },
    {
      city: 'Karachi',
      address: 'Office # 401, 4th floor of Bank Islami, 98C, street number 11, DHA Phase 2 EXT, KARACHI, Sindh',
      map: '<iframe src="https://www.google.com/maps/embed?pb=!1m17!1m12!1m3!1d3620.9241303678978!2d67.07092987536998!3d24.83226807794766!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m2!1m1!2zMjTCsDQ5JzU2LjIiTiA2N8KwMDQnMjQuNiJF!5e0!3m2!1sen!2s!4v1770878105260!5m2!1sen!2s" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>',
      phones: ['+92 310 6225408', '+92 310 6225430', '+92 310 6225410' ],
      emails: []
    },
    {
      city: 'Faisalabad',
      address: 'Universities Page, 1st Floor of, Sehgal Motors, Block C People Colony No 1, Faisalabad, 38000, Pakistan',
      map: '<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3405.0891999101514!2d73.10782038703933!3d31.41166838615958!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x392269b931288103%3A0xfdaf5d1913f76984!2sUniversities%20Page%20%7C%20Italy%2C%20Germany%20%2CChina%2C%20UK%2C%20Poland%2C%20Europe%20best%20Study%20Abroad%20Education%20Visa%20Consultant!5e0!3m2!1sen!2suk!4v1761055911160!5m2!1sen!2suk" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>',
      phones: ['+92 310 6225428', '+92 310 4262934', '+92 310 6225412'],
      emails: []
    },
    {
      city: 'Thailand',
      address: '70 Young Pl Alley, Khwaeng Khlong Toei Nuea, Watthana, Krung Thep Maha Nakhon, Thailand',
      map: '',
      phones: [],
      emails: ['Thailand@universitiespage.com']
    },
    {
      city: 'China',
      address: 'Universities Page, East road of Madian plaza, Hai Dian District, Beijing, China',
      map: '',
      phones: [],
      emails: []
    }
  ];

  type Address = {
    city: string;
    address: string;
    phones: string[];
    emails: string[];
    map: string;
  };

  const [selectedCity, setSelectedCity] = useState<Address | null>(null);
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const consultationModal = useModal();
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const hasShownFirstModalRef = useRef(false);

  useEffect(() => {
    // Simple check using window.location
    const isResumePage = 
      window.location.pathname === '/resume' || 
      window.location.search.includes('stId=');
    
    if (!loading && !isResumePage && !consultationStorage.hasRecentSubmission() && !hasShownFirstModalRef.current) {
      // Clear any existing timeout
      if (timeoutRef.current) clearTimeout(timeoutRef.current);

      // First modal after 15 seconds
      timeoutRef.current = setTimeout(() => {
        consultationModal.open();
        hasShownFirstModalRef.current = true;
      }, 15000);

      return () => {
        if (timeoutRef.current) clearTimeout(timeoutRef.current);
      };
    }
  }, [loading, consultationModal]);

  const handleModalClose = () => {
    consultationModal.close();
    
    // Clear any existing interval first
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    
    // Start 30-second intervals after user closes the modal
    if (!consultationStorage.hasRecentSubmission()) {
      intervalRef.current = setInterval(() => {
        consultationModal.open();
      }, 30000);
    }
  };

  const handleSubmitSuccess = () => {
    // Clear all timers when user submits
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    hasShownFirstModalRef.current = false;
  };

  // Cleanup on component unmount
  useEffect(() => {
    return () => {
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, []);

  const handleSubscribe = async () => {
    if (!email.trim()) {
      Swal.fire("Error", "Please enter a valid email.", "error");
      return;
    }

    try {
      setLoading(true);
      const res = await fetch("/api/frontend/subscribers", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });

      const data = await res.json();
      if (res.ok && data.success) {
        Swal.fire("Subscribed!", "You have successfully subscribed.", "success");
        setEmail("");
      } else {
        Swal.fire("Error", data.error || "Something went wrong.", "error");
      }
    } catch (err) {
      Swal.fire("Error", "Unable to subscribe. Please try again.", "error");
    } finally {
      setLoading(false);
    }
  };

  return (
    <footer className="relative bg-gradient-to-b from-[#E7F1F2] to-[#d0e5e7] pt-[160px] mt-50">
      {/* Newsletter Card - Overlapping */}
      <div className="absolute -top-24 left-1/2 transform -translate-x-1/2 w-[90%] md:w-[80%] lg:w-[70%] mb-16">
        <div className="bg-white rounded-2xl shadow-xl p-6 md:p-8 flex flex-col md:flex-row items-center justify-between gap-6">
          {/* Left Side */}
          <div className="flex-1">
            <p className="text-s uppercase tracking-wider text-[#0a306b] font-semibold mb-2">Stay Updated</p>
       
            <div className="flex flex-col sm:flex-row items-center gap-3">
              <div className="relative flex-1 w-full">
                <input
                  type="email"
                  placeholder="Enter your email address"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className="w-full px-4 py-3 pl-10 rounded-lg border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent"
                />
                <FiMail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
              </div>
              <Button
                onClick={handleSubscribe}
                disabled={loading}
                className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] hover:from-[#0a306b] hover:to-[#0B6F78] text-white px-6 py-3 rounded-lg font-medium transition-all duration-300 shadow-md hover:shadow-lg w-full sm:w-auto"
              >
                {loading ? "Subscribing..." : "Subscribe Now"}
              </Button>
            </div>
            <p className="text-xs text-gray-500 mt-3">We respect your privacy. Unsubscribe at any time.</p>
          </div>
          {/* Right Side Image */}
          <div className="hidden md:block flex-shrink-0">
            <div className="rounded-xl overflow-hidden p-4 flex items-center justify-center bg-gradient-to-r from-[#0B6F78] to-[#0a306b]">
              <Image
                src="/assets/newsletter_img.png"
                alt="Newsletter illustration"
                width={160}
                height={160}
                className="object-contain"
              />
            </div>
          </div>
        </div>
      </div>

      {/* Footer Main Content */}
      <Container>
        <div className="text-gray-800 px-4 sm:px-6 py-10 space-y-12">
          {/* Top Section */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            {/* Company Info */}
            <div className="space-y-4">
              <div className="text-2xl font-bold text-[#0a306b]">

               <Link href="/" className="flex-shrink-0">
  <div className="flex items-center">
    {/* Logo Image */}
    <div className="w-10 h-10 relative">
      <Image
        src="/assets/logo.png"   // make sure logo.png is inside the public/assets folder
        alt="UniversitiesPage Logo"
        fill
        className="object-contain rounded-xl"
      />
    </div>

    {/* Site Name */}
    
        <div className="text-xl font-bold bg-gradient-to-r from-[#0B6F78] to-[#0a306b] bg-clip-text text-transparent">
          Universities Page
        </div>
  </div>
</Link>

              </div>
              <p className="text-gray-600 text-sm leading-relaxed">
                UNI PAGE Education Consultant (Private) Limited has developed the Universities Page application as a free service. This application is provided by UNI PAGE Education Consultant (Private) Limited at no cost and is intended for use as-is.<br/>
                Our goal is to provide students and users with an accessible, reliable, and user-friendly platform to explore study abroad opportunities and university options worldwide.
              </p>
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <FiMail className="text-[#0B6F78]" />
                <span>info@universitiespage.com</span>
              </div>
              <div className="flex items-center gap-2 text-sm text-gray-600">
                <FiClock className="text-[#0B6F78]" />
                <span>Mon-Fri: 9AM - 6PM</span>
              </div>
            </div>

            {/* Quick Links */}
            <div>
              <p className="font-semibold text-lg mb-5 text-[#0a306b] border-b pb-2">Quick Links</p>
              <div className="grid grid-cols-2 gap-4">
                <ul className="space-y-3">
                  <li><Link href="/study-abroad-destinations" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Destinations</Link></li>
                  <li><Link href="/student-visa-services" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Student Visa</Link></li>
                  <li><Link href="/visit-visa-consultants" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Visit Visa</Link></li>
                  <li><Link href="/study-abroad" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Study Abroad</Link></li>
                  <li><Link href="/scholarships-abroad" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Scholarships</Link></li>
                </ul>
                <ul className="space-y-3">
                  <li><Link href="/universities-abroad" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Universities</Link></li>
                  <li><Link href="/study-abroad-courses" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Courses</Link></li>
                  <li><Link href="/career-counseling" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Counseling</Link></li>
                  <li><Link href="/test-preparation" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Test Prep</Link></li>
                  <li><Link href="/study-abroad-consultants" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Consultants</Link></li>
                </ul>
              </div>
            </div>

            {/* Services */}
            <div>
              <p className="font-semibold text-lg mb-5 text-[#0a306b] border-b pb-2">Locations</p>
              <ul className="space-y-3">
                <li><Link href="/study-abroad-consultants-in-lahore" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Lahore</Link></li>
                <li><Link href="/study-abroad-consultants-in-islamabad" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Islamabad</Link></li>
                <li><Link href="/study-abroad-consultants-in-karachi" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Karachi</Link></li>
                <li><Link href="/study-abroad-consultants-in-faisalabad" className="text-gray-600 hover:text-[#0B6F78] transition-colors text-sm">Faisalabad</Link></li>
              </ul>
            </div>

            {/* Follow Us */}
            <div>
              <p className="font-semibold text-lg mb-5 text-[#0a306b] border-b pb-2">Follow Us</p>
              <p className="text-gray-600 text-sm mb-4">Stay connected with us on social media for the latest updates.</p>
              <div className="mb-6">
                <SocialIcons />
              </div>
            </div>
          </div>

          {/* Address Cards Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4 mb-8">
            {addresses.map((address, index) => (
              <div
                key={index}
                className="bg-white rounded-lg p-4 shadow-md border border-gray-200 hover:shadow-lg transition-all duration-300 cursor-pointer transform hover:-translate-y-1"
                onClick={() => setSelectedCity(address)}
              >
                <div className="flex flex-col items-center text-center">
                  <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] p-3 rounded-full mb-3">
                    <FiMapPin className="text-white text-xl" />
                  </div>
                  <p className="font-semibold text-gray-800 mb-2">{address.city}</p>
                  <p className="text-sm text-gray-600 line-clamp-2">{address.address}</p>
                  <button className="mt-3 text-[#0B6F78] text-sm font-medium hover:text-[#0a306b]">
                    View Details
                  </button>
                </div>
              </div>
            ))}
          </div>

          {/* Communities Section */}
            <div className="bg-white rounded-2xl p-6 shadow-lg border border-gray-100 mb-8">
              <div className="text-center mb-6">
                <p className="text-2xl font-bold text-[#0a306b]">
                  Our Communities
                </p>
              </div>
              
             <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Facebook Community */}
              <div className="job_col">
                <div className="flex flex-col md:flex-row md:justify-between md:items-center">
                  <div className="md:flex-1 mb-4 md:mb-0">
                    <div className="job-listing-title">
                      <a 
                        href="https://www.facebook.com/groups/universitiespage" 
                        className="flex items-center" 
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <span className="social-icon-span">
                          <Image 
                            src={"/assets/facebook.webp"}
                            alt="Facebook Community" 
                            width={40}
                            height={40}
                            className="social-icons-image"
                          />
                        </span>
                        <span className="ml-4">
                          <span className="community-title block font-semibold text-gray-800">
                            FaceBook Community
                          </span>
                          <p className="community-description text-gray-600 mt-1">
                            Stay informed and inspired with our Facebook community.
                          </p>
                        </span>
                      </a>
                    </div>
                  </div>
                  <div className="view_job_btn">
                    <a 
                      href="https://www.facebook.com/groups/universitiespage" 
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-block border border-gray-800 rounded px-4 py-2 text-sm font-semibold text-gray-800 hover:border-[#0B6F78] hover:bg-[#0B6F78] hover:text-white transition-all duration-300"
                    >
                      Join
                    </a>
                  </div>
                </div>
              </div>

              {/* WhatsApp Community */}
              <div className="job_col">
                <div className="flex flex-col md:flex-row md:justify-between md:items-center">
                  <div className="md:flex-1 mb-4 md:mb-0">
                    <div className="job-listing-title">
                      <a 
                        href="https://www.whatsapp.com/channel/0029Va7vJOYJkK79737At844" 
                        className="flex items-center" 
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <span className="social-icon-span">
                          <Image 
                            src={"/assets/whatsapp.webp"} 
                            alt="WhatsApp Community" 
                            width={40}
                            height={40}
                            className="social-icons-image"
                          />
                        </span>
                        <span className="ml-4">
                          <span className="community-title block font-semibold text-gray-800">
                            WhatsApp Community
                          </span>
                          <p className="community-description text-gray-600 mt-1">
                            Join our WhatsApp group for instant updates and quick interaction
                          </p>
                        </span>
                      </a>
                    </div>
                  </div>
                  <div className="view_job_btn">
                    <a 
                      href="https://www.whatsapp.com/channel/0029Va7vJOYJkK79737At844" 
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-block border border-gray-800 rounded px-4 py-2 text-sm font-semibold text-gray-800 hover:border-[#0B6F78] hover:bg-[#0B6F78] hover:text-white transition-all duration-300"
                    >
                      Join
                    </a>
                  </div>
                </div>
              </div>
            </div>

            </div>




         {/* Modal */}
{selectedCity && (
  <div
    className="fixed inset-0 flex items-center justify-center z-50 bg-black/50 p-4 overflow-y-auto"
    onClick={() => setSelectedCity(null)}
  >
    <div
      className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full my-6 animate-fadeIn"
      onClick={(e) => e.stopPropagation()}
    >
      {/* Header */}
      <div className="sticky top-0 bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white p-6 rounded-t-2xl">
        <p className="text-2xl font-bold">
          {selectedCity.city} Office
        </p>
      </div>

      {/* Content */}
      <div className="p-6 space-y-6 overflow-y-auto hide-scrollbar max-h-[80vh]">

        {/* Address */}
        <div className="flex items-start gap-4">
          <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] p-3 rounded-full flex-shrink-0 shadow-md">
            <FiMapPin className="text-white text-xl" />
          </div>
          <div>
            <p className="font-semibold text-gray-800 mb-1 text-lg">Address</p>
            <p className="text-gray-600 leading-relaxed">{selectedCity.address}</p>
          </div>
        </div>

        {/* Phones */}
        {selectedCity.phones?.length > 0 && (
          <div className="flex items-start gap-4">
            <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] p-3 rounded-full flex-shrink-0 shadow-md">
              <FiPhone className="text-white text-xl" />
            </div>
            <div>
              <p className="font-semibold text-gray-800 mb-1 text-lg">Phone Numbers</p>
              {selectedCity.phones.map((phone, index) => (
                <p key={index} className="text-gray-600">{phone}</p>
              ))}
            </div>
          </div>
        )}

        <div className="w-full rounded-xl overflow-hidden shadow-md border border-gray-200">
          <div
            className="map-container w-full"
            dangerouslySetInnerHTML={{ __html: selectedCity.map }}
          ></div>
        </div>

        {/* Emails */}
        {selectedCity.emails?.length > 0 && (
          <div className="flex items-start gap-4">
            <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] p-3 rounded-full flex-shrink-0 shadow-md">
              <FiMail className="text-white text-xl" />
            </div>
            <div>
              <p className="font-semibold text-gray-800 mb-1 text-lg">Email</p>
              {selectedCity.emails.map((email, index) => (
                <p key={index} className="text-gray-600">{email}</p>
              ))}
            </div>
          </div>
        )}

        {/* Footer */}
        <div className="pt-6 border-t border-gray-200 flex justify-end">
          <button
            onClick={() => setSelectedCity(null)}
            className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white px-6 py-2.5 rounded-lg font-medium hover:from-[#0a306b] hover:to-[#0B6F78] transition-all duration-300 shadow-md"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  </div>
)}
</div>
      </Container>

      {/* Bottom Bar */}
      <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] mt-10">
        <Container>
          <div className="text-white py-5 px-4 text-sm flex flex-col md:flex-row justify-between items-center gap-3">
            <div className="flex items-center gap-2">
              <span>© {new Date().getFullYear()} Universities Page. All rights reserved.</span>
            </div>
            <div className="flex flex-wrap gap-5 justify-center">
              <Link href="/terms-and-condition" className="hover:text-[#E7F1F2] transition-colors">Terms & Conditions</Link>
              <Link href="/privacy-policy" className="hover:text-[#E7F1F2] transition-colors">Privacy Policy</Link>
              <Link href="/feedback" className="hover:text-[#E7F1F2] transition-colors">Feedback</Link>
              <Link href="/jobs" className="hover:text-[#E7F1F2] transition-colors">Careers</Link>
            </div>
          </div>
        </Container>
      </div>
        {/* Add the Free Consultation Modal */}
        <FreeConsultationModal 
          isOpen={consultationModal.isOpen}
          onClose={handleModalClose}
          onSubmitSuccess={handleSubmitSuccess}
          title=""
          description={`Get expert guidance for studying abroad — completely free of charge! Our consultants will help you choose the right program and guide you through every step of the admission process.`}
        />
    </footer>
  );
};

export default FooterOrganism;