'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge, Phone, MessageCircle, FileText, Car, Shield, Home, ChevronLeft, ChevronRight } from 'lucide-react';

interface SystemSettings {
  siteName: string;
  address: string;
  contactPhone: string;
  contactWhatsApp: string;
  siteLogo?: string;
  polresLogo?: string;
  polresLogo2?: string;
  runningText?: string;
}

interface Slider {
  id: string;
  title?: string;
  subtitle?: string;
  description?: string;
  imageFile?: string;  // Uploaded image file path
  imageUrl?: string;   // External image URL (fallback)
  linkUrl?: string;    // Optional link when slider is clicked
  displayType: string; // WITH_TEXT or BACKGROUND_ONLY
  isActive: boolean;
  order: number;
}

interface ServiceLink {
  id: string;
  title: string;
  subtitle?: string;
  description?: string;
  linkType: 'INTERNAL' | 'EXTERNAL' | 'SUBMENU';
  linkUrl?: string;
  linkPage?: string;
  iconFile?: string;
  iconUrl?: string;
  order: number;
  isActive: boolean;
  parentId?: string;
  children?: ServiceLink[];
}

export default function MinimalLandingPage() {
  const [activeService, setActiveService] = useState<string | null>(null);
  const [currentSlide, setCurrentSlide] = useState(0);
  const [settings, setSettings] = useState<SystemSettings | null>(null);
  const [sliders, setSliders] = useState<Slider[]>([]);
  const [services, setServices] = useState<ServiceLink[]>([]);
  const [servicesWithChildren, setServicesWithChildren] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [touchStart, setTouchStart] = useState<number | null>(null);
  const [touchEnd, setTouchEnd] = useState<number | null>(null);
  const [isPaused, setIsPaused] = useState(false);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      // Fetch system settings
      const settingsResponse = await fetch('/api/settings');
      if (settingsResponse.ok) {
        const settingsData = await settingsResponse.json();
        setSettings(settingsData.settings);
      }

      // Fetch sliders
      const slidersResponse = await fetch('/api/sliders');
      if (slidersResponse.ok) {
        const slidersData = await slidersResponse.json();
        const activeSliders = slidersData.data
          .filter((slider: Slider) => slider.isActive)
          .sort((a: Slider, b: Slider) => a.order - b.order);
        setSliders(activeSliders);
      }

      // Fetch services
      const servicesResponse = await fetch('/api/service-links');
      if (servicesResponse.ok) {
        const servicesData = await servicesResponse.json();
        const activeServices = servicesData.data
          .filter((service: ServiceLink) => service.isActive && !service.parentId)
          .sort((a: ServiceLink, b: ServiceLink) => a.order - b.order);
        setServices(activeServices);
        
        // Set services with children based on linkType
        const servicesWithChildrenSet = new Set(
          activeServices.filter((service: ServiceLink) => service.linkType === 'SUBMENU').map((service: ServiceLink) => service.id)
        );
        setServicesWithChildren(servicesWithChildrenSet);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (sliders.length > 0 && !isPaused) {
      const interval = setInterval(() => {
        setCurrentSlide((prev) => (prev + 1) % sliders.length);
      }, 5000);
      return () => clearInterval(interval);
    }
  }, [sliders.length, isPaused]);

  const nextSlide = () => {
    setCurrentSlide((prev) => (prev + 1) % sliders.length);
  };

  const prevSlide = () => {
    setCurrentSlide((prev) => (prev - 1 + sliders.length) % sliders.length);
  };

  // Touch gesture handlers
  const handleTouchStart = (e: React.TouchEvent) => {
    setTouchEnd(null);
    setTouchStart(e.targetTouches[0].clientX);
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    setTouchEnd(e.targetTouches[0].clientX);
  };

  const handleTouchEnd = () => {
    if (!touchStart || !touchEnd) return;
    
    const distance = touchStart - touchEnd;
    const isLeftSwipe = distance > 50;
    const isRightSwipe = distance < -50;

    if (isLeftSwipe) {
      nextSlide();
    }
    if (isRightSwipe) {
      prevSlide();
    }
  };

  const handleServiceClick = async (service: ServiceLink) => {
    // Check link type first
    if (service.linkType === 'SUBMENU') {
      // For SUBMENU type, check if it has children or direct action
      try {
        const response = await fetch(`/api/service-links?parentId=${service.id}`);
        const data = await response.json();
        const hasChildren = data.data && data.data.length > 0;
        
        if (hasChildren) {
          // Toggle submenu display
          if (activeService === service.id) {
            setActiveService(null);
          } else {
            setActiveService(service.id);
            const submenuItems = data.data || [];
            const updatedServices = services.map(s => 
              s.id === service.id 
                ? { ...s, children: submenuItems }
                : s
            );
            setServices(updatedServices);
          }
        } else if (service.linkUrl) {
          // Submenu with direct action (no children)
          if (service.linkUrl.startsWith('http')) {
            window.open(service.linkUrl, '_blank');
          } else {
            window.location.href = service.linkUrl;
          }
        }
      } catch (error) {
        console.error('Error fetching submenu items:', error);
      }
    } else if (service.linkType === 'EXTERNAL' && service.linkUrl) {
      // Direct external redirect
      window.open(service.linkUrl, '_blank');
    } else if (service.linkType === 'INTERNAL' && service.linkUrl) {
      // Direct internal redirect
      window.location.href = service.linkUrl;
    }
  };

  const handlePhoneCall = (phoneNumber: string) => {
    // Clean phone number and create tel link
    const cleanNumber = phoneNumber.replace(/[^\d+]/g, '');
    const telLink = `tel:${cleanNumber}`;
    
    // Try to open phone app
    window.location.href = telLink;
  };

  const handleChildServiceClick = (childService: ServiceLink) => {
    if (childService.linkType === 'EXTERNAL' && childService.linkUrl) {
      // Open external links in new tab
      window.open(childService.linkUrl, '_blank');
    } else if (childService.linkType === 'INTERNAL' && childService.linkUrl) {
      // Navigate to internal page
      window.location.href = childService.linkUrl;
    } else if (childService.linkType === 'SUBMENU' && childService.linkUrl) {
      // Handle submenu with action (could be internal or external)
      if (childService.linkUrl.startsWith('http')) {
        window.open(childService.linkUrl, '_blank');
      } else {
        window.location.href = childService.linkUrl;
      }
    } else if (childService.linkUrl) {
      // Fallback for any service with linkUrl
      if (childService.linkUrl.startsWith('http')) {
        window.open(childService.linkUrl, '_blank');
      } else {
        window.location.href = childService.linkUrl;
      }
    } else {
      // No link available - just show feedback or do nothing
      console.log('No action available for:', childService.title);
      return; // Don't close modal if no action
    }
    // Close modal after action (only if action was taken)
    setActiveService(null);
  };

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowLeft') {
        prevSlide();
      } else if (e.key === 'ArrowRight') {
        nextSlide();
      } else if (e.key === 'Escape' && activeService) {
        setActiveService(null);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [sliders.length, activeService]);

  // Close modal when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (activeService && (e.target as Element).classList.contains('fixed')) {
        setActiveService(null);
      }
    };

    if (activeService) {
      document.addEventListener('click', handleClickOutside);
      return () => document.removeEventListener('click', handleClickOutside);
    }
  }, [activeService]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Memuat...</p>
        </div>
      </div>
    );
  }

  // Use database values or fallbacks
  const siteName = settings?.siteName || 'POLRES WONOSOBO';
  const address = settings?.address || 'JL. BHAYANGKARA NO.18 WONOSOBO';
  const contactPhone = settings?.contactPhone || '110';
  const contactWhatsApp = settings?.contactWhatsApp || '+62 812-3456-7890';
  const siteLogo = settings?.siteLogo;
  const polresLogo = settings?.polresLogo;
  const polresLogo2 = settings?.polresLogo2;
  const runningText = settings?.runningText || "🚨 SELAMAT DATANG DI PORTAL RESMI POLRES WONOSOBO | 📞 LAYANAN DARURAT: 110 | 💬 LIVE CHAT 24/7 | 📋 SKCK ONLINE | 🛡️ SPKT TERPADU | 🚗 SIM & LALU LINTAS | ";

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Header with Dark Background and Orange Gradient */}
      <header className="relative bg-gradient-to-r from-[#3e2226] to-[#24252e] text-white">
        <div className="relative container mx-auto px-4 py-6">
          <div className="flex items-center space-x-4">
            <div className="flex items-center justify-center">
              {siteLogo ? (
                <img src={siteLogo} alt="Site Logo" className="w-16 h-16 object-contain" />
              ) : (
                <Shield className="w-16 h-16 text-white" />
              )}
            </div>
            <div>
              <h1 className="text-2xl font-bold" style={{ color: '#ffc209' }}>{siteName}</h1>
              <p className="text-sm text-gray-300">{address}</p>
            </div>
          </div>
        </div>
      </header>

      {/* Slider Banner */}
      <section 
        className="relative h-96 md:h-[500px] text-white overflow-hidden select-none"
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
        onMouseEnter={() => setIsPaused(true)}
        onMouseLeave={() => setIsPaused(false)}
      >
        {sliders.length > 0 ? (
          sliders.map((slider, index) => (
            <div
              key={slider.id}
              className={`absolute inset-0 transition-opacity duration-1000 ${
                index === currentSlide ? 'opacity-100' : 'opacity-0'
              }`}
            >
              {/* Background Image with Overlay */}
              <div className="absolute inset-0">
                {(slider.imageFile || slider.imageUrl) ? (
                  <>
                    <img 
                      src={slider.imageFile || slider.imageUrl} 
                      alt={slider.title || 'Slider'}
                      className="w-full h-full object-cover"
                    />
                    {/* Different overlay intensity based on display type */}
                    <div className={`absolute inset-0 ${
                      slider.displayType === 'BACKGROUND_ONLY' 
                        ? 'bg-gradient-to-b from-black/20 via-black/10 to-black/30' 
                        : 'bg-gradient-to-b from-blue-600/40 via-blue-500/30 to-blue-600/50'
                    }`}></div>
                  </>
                ) : (
                  <div className="absolute inset-0 bg-gradient-to-br from-orange-700 to-orange-900"></div>
                )}
              </div>
              
              {/* Content Overlay - Only show if displayType is WITH_TEXT */}
              {slider.displayType === 'WITH_TEXT' && (
                <div className="relative h-full flex items-center justify-center text-center">
                  <div className="max-w-4xl mx-auto px-6">
                    <div className={`space-y-4 transition-all duration-700 transform ${
                      index === currentSlide 
                        ? 'translate-y-0 opacity-100' 
                        : 'translate-y-4 opacity-0'
                    }`}>
                      {slider.title ? (
                        <h2 className="text-4xl md:text-6xl font-bold mb-4 text-white drop-shadow-lg animate-in fade-in slide-in-from-bottom-4 duration-1000">
                          {slider.title}
                        </h2>
                      ) : null}
                      {slider.subtitle ? (
                        <p className="text-xl md:text-2xl text-white/90 drop-shadow-md animate-in fade-in slide-in-from-bottom-3 duration-1000 delay-150">
                          {slider.subtitle}
                        </p>
                      ) : null}
                      {slider.description && (
                        <p className="text-lg text-white/80 drop-shadow-md mt-4 max-w-2xl mx-auto animate-in fade-in slide-in-from-bottom-2 duration-1000 delay-300">
                          {slider.description}
                        </p>
                      )}
                      {!slider.title && !slider.subtitle && !slider.description && (
                        <div className="text-white/80 text-xl animate-in fade-in duration-1000">Slider Image</div>
                      )}
                    </div>
                  </div>
                </div>
              )}

              {/* Clickable Link Overlay */}
              {slider.linkUrl && (
                <a 
                  href={slider.linkUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="absolute inset-0 z-10 cursor-pointer"
                  aria-label={`Link to ${slider.linkUrl}`}
                />
              )}
            </div>
          ))
        ) : (
          // Fallback slider if no data from database
          <div className="absolute inset-0">
            <div className="absolute inset-0 bg-gradient-to-br from-orange-700 to-orange-900"></div>
            <div className="relative h-full flex items-center justify-center text-center">
              <div className="max-w-4xl mx-auto px-6">
                <div className="mb-6">
                  <div className="w-20 h-20 mx-auto bg-white/10 rounded-full flex items-center justify-center backdrop-blur-sm">
                    <Shield className="w-10 h-10 text-white" />
                  </div>
                </div>
                <h2 className="text-4xl md:text-6xl font-bold mb-4 text-white drop-shadow-lg">TULUS DAN RELIGIUS</h2>
                <p className="text-xl md:text-2xl text-white/90 drop-shadow-md">Melayani dengan sepenuh hati</p>
              </div>
            </div>
          </div>
        )}
        
        {sliders.length > 1 && (
          <>
            {/* Slider Controls */}
            <button
              onClick={prevSlide}
              className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-white/20 hover:bg-white/30 backdrop-blur-sm rounded-full p-3 transition-all duration-300 hover:scale-110 z-20 group"
              aria-label="Previous slide"
            >
              <ChevronLeft className="w-6 h-6 text-white group-hover:scale-110 transition-transform" />
            </button>
            <button
              onClick={nextSlide}
              className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-white/20 hover:bg-white/30 backdrop-blur-sm rounded-full p-3 transition-all duration-300 hover:scale-110 z-20 group"
              aria-label="Next slide"
            >
              <ChevronRight className="w-6 h-6 text-white group-hover:scale-110 transition-transform" />
            </button>
            
            {/* Slider Indicators */}
            <div className="absolute bottom-6 left-1/2 transform -translate-x-1/2 flex space-x-2 z-20">
              {sliders.map((_, index) => (
                <button
                  key={index}
                  onClick={() => setCurrentSlide(index)}
                  className={`w-3 h-3 rounded-full transition-all duration-300 hover:scale-125 ${
                    index === currentSlide 
                      ? 'bg-white w-8' 
                      : 'bg-white/50 hover:bg-white/70'
                  }`}
                  aria-label={`Go to slide ${index + 1}`}
                />
              ))}
            </div>

            {/* Slide Counter */}
            <div className="absolute top-4 right-4 bg-white/20 backdrop-blur-sm rounded-full px-3 py-1 text-sm text-white z-20">
              {currentSlide + 1} / {sliders.length}
            </div>
          </>
        )}
      </section>

      {/* Running Text */}
      <section className="bg-gradient-to-r from-[#3e2226] to-[#24252e] text-white py-2 overflow-hidden">
        <div className="relative">
          <div className="animate-marquee whitespace-nowrap">
            <span className="inline-block px-4">{runningText}</span>
            <span className="inline-block px-4">{runningText}</span>
            <span className="inline-block px-4">{runningText}</span>
          </div>
        </div>
      </section>

      {/* Services Section - Custom Design Based on Image */}
      <section className="bg-gradient-to-br from-[#99d7f3] to-[#323558] py-0 md:py-8">
        <div className="container mx-auto px-2 md:px-4 pt-5 md:pt-0 pb-5 md:pb-0">
          <div className="flex justify-center items-center space-x-2 md:space-x-12">
            {services.map((service) => (
              <div 
                key={service.id}
                className="flex flex-col items-center cursor-pointer transition-all duration-300 hover:scale-110"
                onClick={() => handleServiceClick(service)}
              >
                {/* Service Icon - Use uploaded icon or fallback */}
                <div className="w-16 h-16 md:w-16 md:h-16 mb-0 md:mb-2 flex items-center justify-center relative">
                  {service.iconFile || service.iconUrl ? (
                    <img 
                      src={service.iconFile || service.iconUrl} 
                      alt={service.title}
                      className="w-full h-full object-contain"
                      style={{ 
                        background: 'transparent',
                        padding: '0',
                        margin: '0'
                      }}
                    />
                  ) : (
                    // Fallback icon based on service title
                    <div className={`w-full h-full flex items-center justify-center ${
                      service.title?.toLowerCase().includes('spkt') 
                        ? 'bg-red-600 border-2 border-red-800 rounded-lg' 
                        : service.title?.toLowerCase().includes('lalu lintas')
                        ? 'bg-blue-600 rounded-full border-2 border-white'
                        : service.title?.toLowerCase().includes('skck')
                        ? 'bg-gradient-to-br from-red-700 to-black rounded-lg'
                        : service.title?.toLowerCase().includes('live chat')
                        ? 'bg-[#25D366] rounded-full'
                        : 'bg-green-600 rounded-full'
                    }`}>
                      {service.title?.toLowerCase().includes('lalu lintas') ? (
                        // White cross for traffic service
                        <div className="relative w-6 h-6">
                          <div className="w-full h-1 bg-white absolute top-1/2 -translate-y-1/2"></div>
                          <div className="h-full w-1 bg-white absolute left-1/2 -translate-x-1/2"></div>
                        </div>
                      ) : service.title?.toLowerCase().includes('spkt') ? (
                        // Pattern for SPKT
                        <div className="grid grid-cols-2 gap-1 p-2">
                          <div className="w-2 h-2 bg-white/40 rounded-sm"></div>
                          <div className="w-2 h-2 bg-white/60 rounded-sm"></div>
                          <div className="w-2 h-2 bg-white/60 rounded-sm"></div>
                          <div className="w-2 h-2 bg-white/40 rounded-sm"></div>
                        </div>
                      ) : service.title?.toLowerCase().includes('skck') ? (
                        // Document icon for SKCK
                        <div className="text-white text-xs font-bold">SKCK</div>
                      ) : service.title?.toLowerCase().includes('live chat') ? (
                        // WhatsApp icon for live chat - updated to match real WhatsApp
                        <div className="relative w-8 h-8 flex items-center justify-center">
                          {/* WhatsApp green circle background */}
                          <div className="w-8 h-8 bg-[#25D366] rounded-full flex items-center justify-center shadow-lg">
                            {/* White phone icon inside */}
                            <svg 
                              className="w-5 h-5 text-white" 
                              fill="currentColor" 
                              viewBox="0 0 24 24" 
                              aria-hidden="true"
                            >
                              <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.149-.67.149-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414-.074-.123-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
                            </svg>
                          </div>
                          {/* Small notification dot */}
                          <div className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full border-2 border-white"></div>
                        </div>
                      ) : (
                        // Default chat bubble
                        <div className="relative">
                          <div className="w-8 h-6 bg-white rounded-lg"></div>
                          <div className="absolute -bottom-1 left-2 w-2 h-2 bg-white rounded-sm transform rotate-45"></div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
                
                {/* Service Name */}
                <h3 className="text-white text-xs md:text-sm font-bold text-center">
                  {service.title}
                </h3>
              </div>
            ))}
          </div>

          {/* Submenu Display - Integrated Design */}
          {activeService && (
            <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-2 md:p-4">
              <div className="bg-gradient-to-br from-[#99d7f3] to-[#323558] rounded-2xl p-3 md:p-6 max-w-4xl w-full max-h-[80vh] overflow-y-auto shadow-2xl border border-white/20">
                {/* Header */}
                <div className="flex justify-between items-center mb-6 pb-4 border-b border-white/20">
                  <div className="flex items-center gap-4">
                    {/* Service Icon */}
                    <div className="w-12 h-12 flex items-center justify-center">
                      {(() => {
                        const service = services.find(s => s.id === activeService);
                        if (service?.iconFile || service?.iconUrl) {
                          return (
                            <img 
                              src={service.iconFile || service.iconUrl} 
                              alt={service.title}
                              className="w-full h-full object-contain"
                            />
                          );
                        } else {
                          return (
                            <div className={`w-full h-full flex items-center justify-center ${
                              service?.title?.toLowerCase().includes('spkt') 
                                ? 'bg-red-600 border-2 border-red-800 rounded-lg' 
                                : service?.title?.toLowerCase().includes('lalu lintas')
                                ? 'bg-blue-600 rounded-full border-2 border-white'
                                : service?.title?.toLowerCase().includes('skck')
                                ? 'bg-gradient-to-br from-red-700 to-black rounded-lg'
                                : 'bg-green-600 rounded-full'
                            }`}>
                              {service?.title?.toLowerCase().includes('lalu lintas') ? (
                                <div className="relative w-6 h-6">
                                  <div className="w-full h-1 bg-white absolute top-1/2 -translate-y-1/2"></div>
                                  <div className="h-full w-1 bg-white absolute left-1/2 -translate-x-1/2"></div>
                                </div>
                              ) : service?.title?.toLowerCase().includes('spkt') ? (
                                <div className="grid grid-cols-2 gap-1 p-2">
                                  <div className="w-2 h-2 bg-white/40 rounded-sm"></div>
                                  <div className="w-2 h-2 bg-white/60 rounded-sm"></div>
                                  <div className="w-2 h-2 bg-white/60 rounded-sm"></div>
                                  <div className="w-2 h-2 bg-white/40 rounded-sm"></div>
                                </div>
                              ) : service?.title?.toLowerCase().includes('skck') ? (
                                <div className="text-white text-xs font-bold">SKCK</div>
                              ) : (
                                <Shield className="w-6 h-6 text-white" />
                              )}
                            </div>
                          );
                        }
                      })()}
                    </div>
                    <div>
                      <h4 className="text-white text-xl font-bold">
                        {services.find(s => s.id === activeService)?.title}
                      </h4>
                      {services.find(s => s.id === activeService)?.subtitle && (
                        <p className="text-white/70 text-sm">
                          {services.find(s => s.id === activeService)?.subtitle}
                        </p>
                      )}
                    </div>
                  </div>
                  <button
                    onClick={() => setActiveService(null)}
                    className="text-white/70 hover:text-white text-3xl leading-none transition-colors hover:scale-110"
                  >
                    ×
                  </button>
                </div>
                
                {/* Submenu Content */}
                {(() => {
                  const service = services.find(s => s.id === activeService);
                  if (service?.children && service.children.length > 0) {
                    return (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {service.children.map((child) => (
                          <div
                            key={child.id}
                            onClick={() => handleChildServiceClick(child)}
                            className={`rounded-xl p-6 transition-all duration-300 border border-white/20 group relative ${
                              child.linkUrl 
                                ? 'bg-white/10 hover:bg-white/20 cursor-pointer hover:scale-105' 
                                : 'bg-white/5 cursor-default opacity-75'
                            }`}
                          >
                            {/* Hover indicator for clickable items */}
                            {child.linkUrl ? (
                              <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                <div className="bg-orange-500 text-white text-xs px-2 py-1 rounded-full flex items-center gap-1">
                                  {child.linkUrl.startsWith('http') ? (
                                    <>
                                      <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                      </svg>
                                      <span>Klik</span>
                                    </>
                                  ) : (
                                    <>
                                      <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
                                      </svg>
                                      <span>Buka</span>
                                    </>
                                  )}
                                </div>
                              </div>
                            ) : (
                              <div className="absolute top-2 right-2 opacity-50">
                                <div className="bg-gray-500 text-white text-xs px-2 py-1 rounded-full">
                                  <span>Info</span>
                                </div>
                              </div>
                            )}
                            <div className="flex items-start gap-4">
                              {/* Child Icon */}
                              <div className={`w-10 h-10 flex-shrink-0 flex items-center justify-center rounded-lg transition-colors ${
                                child.linkUrl 
                                  ? 'bg-white/10 group-hover:bg-white/20' 
                                  : 'bg-white/5'
                              }`}>
                                {child.linkType === 'EXTERNAL' ? (
                                  <div className="text-blue-300">
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                    </svg>
                                  </div>
                                ) : child.linkType === 'SUBMENU' ? (
                                  <div className="text-purple-300">
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                                    </svg>
                                  </div>
                                ) : child.linkUrl ? (
                                  <div className="text-green-300">
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                    </svg>
                                  </div>
                                ) : (
                                  <div className="text-gray-400">
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                  </div>
                                )}
                              </div>
                              
                              <div className="flex-1">
                                <h5 className="text-white font-semibold mb-2 text-lg group-hover:text-orange-300 transition-colors">
                                  {child.title}
                                </h5>
                                {child.description && (
                                  <p className="text-white/70 text-sm leading-relaxed">
                                    {child.description}
                                  </p>
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    );
                  } else if (service?.description) {
                    return (
                      <div className="bg-white/5 rounded-lg p-6 text-center">
                        <p className="text-white/80 text-lg">{service.description}</p>
                      </div>
                    );
                  } else {
                    return (
                      <div className="bg-white/5 rounded-lg p-6 text-center">
                        <p className="text-white/60 text-lg">Tidak ada submenu tersedia</p>
                      </div>
                    );
                  }
                })()}
              </div>
            </div>
          )}
        </div>
      </section>

      {/* Bottom Navigation with Dark Yellow Background */}
      <nav className="bg-gradient-to-r from-[#c49337] to-[#c59336] text-white">
        <div className="px-0">
          {/* Desktop Layout */}
          <div className="hidden md:flex justify-between items-center px-0">
            <button className="flex-1 flex flex-col items-center gap-0 py-0.5 text-white hover:text-gray-200 transition-all duration-300 hover:scale-105 rounded-lg mx-0">
              <Home className="w-10 h-10 lg:w-12 lg:h-12" />
              <span className="text-sm lg:text-base font-semibold">HOME</span>
            </button>
            <button className="flex-1 flex flex-col items-center gap-0 py-0.5 text-white hover:text-gray-200 transition-all duration-300 hover:scale-105 rounded-lg mx-0">
              {polresLogo2 ? (
                <img src={polresLogo2} alt="Logo Polres" className="w-28 h-28 lg:w-32 lg:h-32 object-contain" />
              ) : polresLogo ? (
                <img src={polresLogo} alt="Logo Polres" className="w-28 h-28 lg:w-32 lg:h-32 object-contain" />
              ) : (
                <Shield className="w-28 h-28 lg:w-32 lg:h-32" />
              )}
            </button>
            <button 
              className="flex-1 flex flex-col items-center gap-0 py-0.5 text-white hover:text-orange-200 transition-all duration-300 hover:scale-105 rounded-lg mx-0"
              onClick={() => handlePhoneCall(contactPhone)}
            >
              <Phone className="w-10 h-10 lg:w-12 lg:h-12" />
              <span className="text-sm lg:text-base font-bold text-white text-center">CALL CENTER {contactPhone}</span>
            </button>
          </div>

          {/* Mobile Layout */}
          <div className="md:hidden">
            {/* Compact layout with larger icons */}
            <div className="flex justify-between items-center px-0">
              <button className="flex-1 flex flex-col items-center gap-0 py-1 text-white hover:text-gray-200 transition-all duration-300 hover:scale-105 rounded-lg mx-0">
                <Home className="w-6 h-6" />
                <span className="text-xs font-semibold">HOME</span>
              </button>
              
              <button className="flex-1 flex flex-col items-center gap-0 py-1 text-white hover:text-gray-200 transition-all duration-300 hover:scale-105 rounded-lg mx-0">
                {polresLogo2 ? (
                  <img src={polresLogo2} alt="Logo Polres" className="w-24 h-24 object-contain" />
                ) : polresLogo ? (
                  <img src={polresLogo} alt="Logo Polres" className="w-24 h-24 object-contain" />
                ) : (
                  <Shield className="w-24 h-24" />
                )}
              </button>
              
              <button 
                className="flex-1 flex flex-col items-center gap-0 py-1 text-white hover:text-orange-200 transition-all duration-300 hover:scale-105 rounded-lg mx-0"
                onClick={() => handlePhoneCall(contactPhone)}
              >
                <Phone className="w-6 h-6" />
                <span className="text-xs font-normal text-white text-center leading-tight">{contactPhone.replace(/[^\d]/g, '')}</span>
              </button>
            </div>
          </div>
        </div>
      </nav>

  

      <style jsx>{`
        @keyframes marquee {
          0% {
            transform: translateX(0%);
          }
          100% {
            transform: translateX(-33.333%);
          }
        }
        .animate-marquee {
          display: inline-block;
          animation: marquee 20s linear infinite;
        }
      `}</style>
    </div>
  );
}