
import React, { useState, useEffect, useRef, useCallback } from 'react';

const App: React.FC = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [activeSection, setActiveSection] = useState(0);
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const sections = [
    { id: 'section1', label: 'الرئيسية' },
    { id: 'section2', label: 'لفيشطة' },
    { id: 'section3', label: 'أسايس' },
    { id: 'section4', label: 'لمعروف' },
    { id: 'section5', label: 'أمصري' },
    { id: 'section6', label: 'تواصل معنا' },
  ];

  const sliderImages = [
    "https://festivalinezgane.com/ismkan22.jpeg",
    "https://festivalinezgane.com/nasim.jpeg",
    "https://festivalinezgane.com/tachinwite.jpeg",
    "https://festivalinezgane.com/itran.webp",
    "https://festivalinezgane.com/affiche-amdokal.webp"
  ];

  // Duplicate for loop
  const displayImages = [...sliderImages, ...sliderImages];

  const handleScroll = useCallback(() => {
    if (!scrollContainerRef.current) return;
    const scrollContainer = scrollContainerRef.current;
    const sectionElements = scrollContainer.querySelectorAll('.section');
    
    let current = 0;
    sectionElements.forEach((section, index) => {
      const rect = section.getBoundingClientRect();
      if (rect.top >= -100 && rect.top <= 100) {
        current = index;
      }
    });
    setActiveSection(current);
  }, []);

  useEffect(() => {
    const container = scrollContainerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
    }
    return () => {
      if (container) {
        container.removeEventListener('scroll', handleScroll);
      }
    };
  }, [handleScroll]);

  const toggleMenu = () => setIsMenuOpen(!isMenuOpen);
  const closeMenu = () => setIsMenuOpen(false);

  const scrollToSection = (index: number) => {
    const sectionId = sections[index].id;
    const element = document.getElementById(sectionId);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' });
    }
    closeMenu();
  };

  const handleVideoPlay = () => {
    setIsVideoPlaying(true);
  };

  return (
    <div className="h-full relative">
      {/* Menu Overlay */}
      <div 
        className={`menu-overlay ${isMenuOpen ? 'active' : ''}`} 
        onClick={closeMenu}
      />

      {/* Mobile Side Menu */}
      <div className={`mobile-menu ${isMenuOpen ? 'active' : ''}`}>
        <nav>
          <ul className="nav-links flex flex-col gap-[25px]">
            {sections.slice(0, 5).map((section, idx) => (
              <li key={section.id}>
                <button 
                  onClick={() => scrollToSection(idx)}
                  className="mobile-nav-link text-[#2c3e50] text-[1.1rem] font-semibold"
                >
                  {section.label}
                </button>
              </li>
            ))}
          </ul>
        </nav>
        <button 
          onClick={() => scrollToSection(5)}
          className="cta-button mt-[30px] inline-block text-center"
        >
          المدونة
        </button>
      </div>

      {/* Floating Header */}
      <header className="floating-header">
        {/* 1. Logo (Right in RTL) */}
        <a href="https://festivalinezgane.com">
          <img 
            src="https://festivalinezgane.com/logo1.png" 
            alt="Festival Inezgane Logo" 
            className="header-logo" 
          />
        </a>

        {/* 2. Nav (Center) */}
        <nav>
          <ul className="nav-links">
            {sections.slice(0, 5).map((section, idx) => (
              <li key={section.id}>
                <button 
                  onClick={() => scrollToSection(idx)}
                  className="nav-link text-white font-semibold text-[0.9rem]"
                >
                  {section.label}
                </button>
              </li>
            ))}
          </ul>
        </nav>

        {/* 3. Button (Left in RTL) */}
        <button 
          onClick={() => scrollToSection(5)}
          className="cta-button"
        >
          المدونة
        </button>

        {/* 4. Hamburger (Mobile position) */}
        <div 
          className={`hamburger ${isMenuOpen ? 'active' : ''}`} 
          onClick={toggleMenu}
        >
          <span></span>
          <span></span>
          <span></span>
        </div>
      </header>

      {/* Social Media Icons */}
      <div className="social-icons">
        <SocialLink href="https://facebook.com/festivalinezgane" title="Facebook" icon={<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />} />
        <SocialLink href="https://instagram.com/festivalinezgane" title="Instagram" icon={<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0 3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z" />} />
        <SocialLink href="https://tiktok.com/@festivalinezgane" title="TikTok" icon={<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.64 2.93 2.93 0 0 1 .88.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5 20.1a6.34 6.34 0 0 0 10.86-4.43v-7a8.16 8.16 0 0 0 4.77 1.52v-3.4a4.85 4.85 0 0 1-1-.1z" />} />
        <SocialLink href="https://x.com/festivalinezgan" title="X" icon={<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />} />
        <SocialLink href="https://www.youtube.com/@festivalinezgane" title="YouTube" icon={<path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />} />
      </div>

      {/* Scroll Indicator */}
      <div className="scroll-indicator">
        {sections.map((_, idx) => (
          <div 
            key={idx} 
            className={`scroll-dot ${activeSection === idx ? 'active' : ''}`} 
            onClick={() => scrollToSection(idx)}
          />
        ))}
      </div>

      {/* Main Content Sections */}
      <div className="scroll-container" ref={scrollContainerRef}>
        
        {/* Section 1 - Festival Introduction */}
        <section className="section" id="section1">
          <div className="section-content">
            <div className="main-content-wrapper">
              <div className="split-left">
                <img src="https://festivalinezgane.com/logo-festival-inezgane2.png" alt="شعار مهرجان انزكان" className="festival-logo" />
                <h1 className="headline">مهرجان انزكان</h1>
                <h2 className="subheadline">فعاليات اسايس نايت لقايد</h2>
                <p className="description">مهرجان ثقافي يحتفي بالهوية، الذاكرة، والتراث الأمازيغي السوسي الأصيل</p>
              </div>
              <div className="split-right">
                <img src="https://festivalinezgane.com/logo-festival-inezgane2.png" alt="شعار المهرجان" className="mobile-logo-above" />
                <div 
                  className={`video-container ${isVideoPlaying ? 'playing' : ''}`} 
                  id="videoContainer"
                  onClick={handleVideoPlay}
                >
                  <div className="video-cover">
                    <div className="play-button"></div>
                  </div>
                  {isVideoPlaying && (
                    <iframe 
                      id="youtubeVideo" 
                      src="https://www.youtube.com/embed/I8u9y43xNAQ?autoplay=1&rel=0" 
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                      allowFullScreen
                    ></iframe>
                  )}
                </div>
              </div>
            </div>
            
            <div className="partners-row">
              <PartnerLogo src="https://festivalinezgane.com/inezgane-logo.png" alt="Prefecture Inezgane" />
              <PartnerLogo src="https://festivalinezgane.com/prefecture-inezgane.png" alt="Prefecture Inezgane" />
              <PartnerLogo src="https://festivalinezgane.com/FirstOneNews-Logo.png" alt="First One News" />
              <PartnerLogo 
                src="https://festivalinezgane.com/FirstOneMedia-Logo.png" 
                alt="First One Media" 
                className="w-[125px] h-auto"
              />
            </div>
          </div>
        </section>

        {/* Section 2 - Editorial Statement */}
        <section className="section" id="section2">
          <div className="section-content editorial-statement">
            <div className="editorial-container">
              <h1 className="editorial-headline">كلمة مدير مهرجان انزكان <br /> فعاليات أسايس نايت القايد</h1>
              <div className="editorial-divider"></div>
              <p className="editorial-text">
                يسعدني، وبكل فخر واعتزاز، أن أرحب بكم في فعاليات مهرجان إنزكان – ليالي أسايس نايت القايد، هذا الموعد الثقافي الذي يحتفي بالهوية الأمازيغية السوسية، ويستحضر الذاكرة التاريخية العميقة لمدينة إنزكان ومكانتها الرمزية في تاريخ سوس والمغرب. <br /><br />
                لقد ارتبط اسم إنزكان تاريخيًا بـ أسايس، ذلك الفضاء الذي لم يكن مجرد ساحة، بل مركزًا نبضًا بالحياة، وملتقى للتجارة والفن والحكي، ومرآةً لعلاقات المجتمع والذاكرة الجماعية. ومن هذا العمق، تنطلق ليالي أسايس نايت القايد كمبادرة ثقافية تسعى إلى إعادة إحياء هذا الإرث بأسلوب معاصر يحترم أصالته ويقرّبه من الأجيال الجديدة.<br /><br />
                ويقدّم المهرجان برمجة ثقافية وفنية متنوعة تشمل عروض الفنون الشعبية، خيام الحكي، فقرات تاريخية مفتوحة، واحتفالية رأس السنة الأمازيغية، إضافة إلى ندوات ولقاءات فكرية، تحتضنها فضاءات ذات حمولة رمزية قوية مثل قصبة القايد وساحات المدينة التاريخية. <br /><br />
                وإذ نطمح إلى جعل هذا الحدث موعدًا ثقافيًا سنويًا، فإننا نراهن على دوره في تعزيز الإشعاع الثقافي لإنزكان، وفتح حوار متجدد بين الماضي والحاضر، بين الذاكرة والإبداع، في إطار يحترم التنوع والانفتاح. <br /><br />
                <span className="signature-text">إبراهيم المرابط<br />مدير مهرجان إنزكان – ليالي أسايس نايت القايد</span>
              </p>
            </div>
          </div>
        </section>

        {/* Section 3 - First Major Amazigh Evening */}
        <section className="section" id="section3">
          <div className="section-content w-full h-full flex flex-col p-0 max-w-none justify-between overflow-hidden">
             {/* Top Container - 15% height */}
             <div className="h-[15%] flex items-center justify-center mt-12 md:mt-0">
                <h1 className="!text-3xl md:!text-5xl !font-bold !m-0 !text-white drop-shadow-lg">السهرة الأمازيغية الكبرى الأولى</h1>
             </div>

             {/* Bottom Container - 80% height */}
             <div className="h-[80%] flex flex-col md:flex-row w-full px-4 md:px-12 gap-4 md:gap-10 pb-6 items-center">
                {/* Right Column (65% width) - Slider Carousel - NOW FIRST IN DOM (Right in RTL) */}
                <div className="w-full md:w-[65%] h-[55%] md:h-full relative overflow-hidden flex items-center justify-center bg-black/10 rounded-[10px]">
                    <div className="carousel-track">
                        {displayImages.map((src, i) => (
                            <div key={i} className="w-[180px] md:w-[280px] h-full flex-shrink-0 py-4 flex items-center justify-center">
                                <img 
                                    src={src} 
                                    alt={`FESTIVAL-${i}`} 
                                    className="w-full h-full object-cover rounded-[10px] shadow-lg border border-white/20"
                                />
                            </div>
                        ))}
                        {/* Duplicate for seamless infinite loop */}
                        {displayImages.map((src, i) => (
                            <div key={`dup-${i}`} className="w-[180px] md:w-[280px] h-full flex-shrink-0 py-4 flex items-center justify-center">
                                <img 
                                    src={src} 
                                    alt={`FESTIVAL-DUP-${i}`} 
                                    className="w-full h-full object-cover rounded-[10px] shadow-lg border border-white/20"
                                />
                            </div>
                        ))}
                    </div>
                </div>

                {/* Left Column (35% width) - Vertical Image - NOW SECOND IN DOM (Left in RTL) */}
                <div className="w-full md:w-[35%] h-[45%] md:h-full flex items-center justify-center">
                    <img 
                      src="https://festivalinezgane.com/fechta1.jpeg" 
                      alt="السهرة الأمازيغية" 
                      className="w-full h-full object-cover rounded-[10px] shadow-2xl transition-transform duration-500 hover:scale-[1.02]"
                    />
                </div>
             </div>
          </div>
        </section>

        {/* Placeholders for sections 4-6 to maintain snap functionality */}
        <section className="section bg-[#2d6a4f] bg-opacity-70" id="section4">
          <div className="section-content">
            <h1>لمعروف</h1>
            <h2>قريباً</h2>
          </div>
        </section>
        <section className="section bg-[#c1121f] bg-opacity-70" id="section5">
          <div className="section-content">
            <h1>أمصري</h1>
            <h2>قريباً</h2>
          </div>
        </section>

        {/* Section 6 - News & Updates */}
        <section className="section" id="section6">
          <div className="section-content w-full h-full flex flex-col p-0 max-w-none justify-between overflow-hidden">
            {/* Zone 1 - 15% height */}
            <div className="h-[15%] flex flex-col justify-center items-center">
              <h1 className="!text-3xl md:!text-4xl !font-bold !m-0 !mb-2">آخر مستجدات المهرجان</h1>
              <h2 className="!text-lg md:!text-xl !font-light !opacity-90 !m-0">أخبار، بلاغات، وتحديثات مهرجان إنزكان</h2>
            </div>

            {/* Zone 2 - 70% height */}
            <div className="h-[70%] flex items-center justify-center py-4 px-6 md:px-16">
              <div className="grid grid-cols-2 md:grid-cols-3 grid-rows-2 gap-6 md:gap-10 h-full w-full max-w-7xl">
                {[...Array(6)].map((_, i) => (
                  <div key={i} className="relative aspect-video overflow-hidden rounded-xl shadow-lg transition-transform hover:scale-[1.02] cursor-pointer group">
                    <img 
                      src="https://festivalinezgane.com/post-cards.webp" 
                      alt="Festival Post" 
                      className="absolute inset-0 w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                    />
                    {/* Overlay Gradient: 95% top (0.05 visible), 50% bottom (0.5 visible) */}
                    <div 
                      className="absolute inset-0 flex flex-col justify-end p-4 md:p-6 text-right"
                      style={{
                        background: 'linear-gradient(to bottom, rgba(30, 60, 114, 0.05) 0%, rgba(30, 60, 114, 0.5) 100%)'
                      }}
                    >
                      <h3 className="text-white font-bold text-sm md:text-xl leading-tight mb-3 drop-shadow-lg">
                        دور الإعلام في نجاح مهرجان إنزكان أسايس نايت القايد
                      </h3>
                      <div className="flex justify-start">
                        <button className="bg-[#f47e20] hover:bg-[#ff9a56] text-white px-5 md:px-8 py-1.5 md:py-2 rounded-lg text-xs md:text-sm font-bold transition-all shadow-md">
                          المزيد
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Zone 3 - 15% height */}
            <div className="h-[15%] flex items-center justify-center">
              <p className="text-white text-sm md:text-base opacity-75 text-center">
                2026 © Festival Inezgane - فعاليات أسايس ،ايت القايد
              </p>
            </div>
          </div>
        </section>
      </div>
    </div>
  );
};

interface SocialLinkProps {
  href: string;
  title: string;
  icon: React.ReactNode;
}

const SocialLink: React.FC<SocialLinkProps> = ({ href, title, icon }) => (
  <a 
    href={href} 
    target="_blank" 
    rel="noopener noreferrer" 
    className="social-icon" 
    title={title}
  >
    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
      {icon}
    </svg>
  </a>
);

interface PartnerLogoProps {
  src: string;
  alt: string;
  className?: string;
}

const PartnerLogo: React.FC<PartnerLogoProps> = ({ src, alt, className }) => (
  <img 
    src={src} 
    alt={alt} 
    className={`partner-logo ${className || ''}`} 
    loading="lazy" 
    onError={(e) => {
      const target = e.target as HTMLImageElement;
      target.style.background = '#e5e7eb';
      target.alt = 'Image unavailable';
    }}
  />
);

export default App;
