"use client";

import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';
import HeroBillboardCarousel from '@/components/sections/hero/HeroBillboardCarousel';
import TestimonialAboutCard from '@/components/sections/about/TestimonialAboutCard';
import FeatureCardNineteen from '@/components/sections/feature/FeatureCardNineteen';
import MetricCardEleven from '@/components/sections/metrics/MetricCardEleven';
import PricingCardNine from '@/components/sections/pricing/PricingCardNine';
import TestimonialCardFifteen from '@/components/sections/testimonial/TestimonialCardFifteen';
import FaqSplitMedia from '@/components/sections/faq/FaqSplitMedia';
import ContactFaq from '@/components/sections/contact/ContactFaq';
import FooterMedia from '@/components/sections/footer/FooterMedia';
import { Award, Dumbbell, Phone, Trophy, Zap, Clock } from "lucide-react";
import { useEffect, useRef, useState } from "react";

export default function LandingPage() {
  const brandListRef = useRef<HTMLDivElement>(null);
  const [timeLeft, setTimeLeft] = useState<string>("5:00");

  useEffect(() => {
    if (!brandListRef.current) return;

    const scrollContainer = brandListRef.current.querySelector('.brand-scroll-container') as HTMLElement;
    if (!scrollContainer) return;

    const items = scrollContainer.querySelectorAll('.brand-item');
    const itemCount = items.length;
    if (itemCount === 0) return;

    let scrollPosition = 0;
    const itemWidth = (items[0] as HTMLElement).offsetWidth + 32; // includes gap
    const containerWidth = scrollContainer.offsetWidth;
    const totalWidth = itemWidth * itemCount;

    const animateScroll = () => {
      scrollPosition += 0.5;
      if (scrollPosition >= totalWidth / 2) {
        scrollPosition = 0;
      }
      scrollContainer.scrollLeft = scrollPosition;
      requestAnimationFrame(animateScroll);
    };

    animateScroll();
  }, []);

  useEffect(() => {
    const startTime = Date.now();
    const durationMs = 5 * 60 * 1000; // 5 minutes

    const updateTimer = () => {
      const elapsed = Date.now() - startTime;
      const remaining = Math.max(0, durationMs - elapsed);
      const minutes = Math.floor(remaining / 60000);
      const seconds = Math.floor((remaining % 60000) / 1000);
      setTimeLeft(`${minutes}:${seconds.toString().padStart(2, '0')}`);

      if (remaining > 0) {
        requestAnimationFrame(updateTimer);
      }
    };

    updateTimer();
  }, []);

  const brands = [
    "Gold's Gym Partners",    "Fitness Canada Certified",    "NASM Certified",    "ACE Certified",    "ISSA Certified",    "IIFYM Certified",    "PN Level 1 Certified",    "TRX Certified",    "CrossFit Level 1",    "NCCPT Certified"
  ];

  return (
    <ThemeProvider
      defaultButtonVariant="directional-hover"
      defaultTextAnimation="entrance-slide"
      borderRadius="pill"
      contentWidth="compact"
      sizing="large"
      background="none"
      cardStyle="glass-depth"
      primaryButtonStyle="radial-glow"
      secondaryButtonStyle="radial-glow"
      headingFontWeight="bold"
    >
      <div id="nav" data-section="nav">
        <NavbarLayoutFloatingOverlay
          brandName="FitPro Toronto"
          navItems={[
            { name: "About", id: "about" },
            { name: "Services", id: "services" },
            { name: "Results", id: "results" },
            { name: "Pricing", id: "pricing" },
            { name: "Testimonials", id: "testimonials" }
          ]}
          button={{ text: "Book Free Consultation", href: "contact" }}
        />
      </div>

      <div id="hero" data-section="hero">
        <HeroBillboardCarousel
          title="Transform Your Body, Transform Your Life"
          description="Professional personal training in Toronto tailored to your unique goals. Expert coaching for strength, fitness, and lasting results. Trusted by over 100 clients."
          tag="Personal Training"
          tagIcon={Zap}
          background={{ variant: "sparkles-gradient" }}
          mediaItems={[
            {
              imageSrc: "https://img.b2bpic.net/free-photo/woman-gym-with-coach_1303-5545.jpg",              imageAlt: "Professional personal trainer in action"
            },
            {
              imageSrc: "https://img.b2bpic.net/free-photo/two-hardworking-men-training-with-weights_651396-1080.jpg",              imageAlt: "Client receiving one-on-one training instruction"
            },
            {
              imageSrc: "https://img.b2bpic.net/free-photo/male-personal-trainer-helping-woman-working-with-heavy-dumbbells-gym_651396-1074.jpg",              imageAlt: "Fitness transformation results"
            },
            {
              imageSrc: "https://img.b2bpic.net/free-photo/fit-couple-sitting-floor-gym_23-2147949622.jpg",              imageAlt: "Healthy active lifestyle focus"
            },
            {
              imageSrc: "https://img.b2bpic.net/free-photo/smiling-black-man-lifting-barbell-with-personal-trainer_1262-16411.jpg",              imageAlt: "Professional gym equipment setup"
            }
          ]}
          buttons={[
            { text: "Start Your Journey", href: "contact" },
            { text: "Learn More", href: "about" }
          ]}
        />
      </div>

      <div id="logo-ribbon" data-section="logo-ribbon" className="py-8 px-4 bg-background" ref={brandListRef}>
        <div className="w-content-width mx-auto">
          <div className="flex flex-col items-center justify-center gap-8">
            <h3 className="text-center text-lg font-semibold text-foreground">Trusted by Leading Fitness Brands</h3>
            <div className="brand-scroll-container w-full overflow-x-hidden">
              <div className="flex gap-8 md:gap-12 whitespace-nowrap">
                {brands.map((brand, index) => (
                  <div key={`${index}-1`} className="brand-item flex items-center justify-center h-12 min-w-max px-4 py-2 text-foreground/60 font-medium text-sm flex-shrink-0 rounded-theme border border-card bg-card/40 backdrop-blur-sm">
                    {brand}
                  </div>
                ))}
                {brands.map((brand, index) => (
                  <div key={`${index}-2`} className="brand-item flex items-center justify-center h-12 min-w-max px-4 py-2 text-foreground/60 font-medium text-sm flex-shrink-0 rounded-theme border border-card bg-card/40 backdrop-blur-sm">
                    {brand}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div id="about" data-section="about" className="py-8">
        <TestimonialAboutCard
          tag="Meet Your Coach"
          tagIcon={Award}
          title="Certified Personal Trainer with 8+ Years of Experience"
          description="Sarah Mitchell"
          subdescription="Certified in Strength & Conditioning, Nutrition Coaching, and Sports Performance"
          icon={Trophy}
          imageSrc="https://img.b2bpic.net/free-photo/beautiful-sportive-girl-posing-with-crossed-arms-dark-wall_176420-620.jpg"
          imageAlt="Portrait of certified personal trainer Sarah Mitchell"
          useInvertedBackground="invertDefault"
        />
      </div>

      <div id="services" data-section="services">
        <FeatureCardNineteen
          title="Comprehensive Training Services"
          description="From strength building to cardio conditioning, we offer personalized services designed around your unique goals and fitness level."
          tag="Services"
          tagIcon={Dumbbell}
          textboxLayout="default"
          useInvertedBackground="noInvert"
          features={[
            {
              id: 1,
              tag: "Power Building",              title: "Strength Training",              subtitle: "Build muscle and increase strength safely",              description: "Customized strength training programs using proper form and progressive overload principles. Perfect for muscle building and injury prevention with personalized technique coaching.",              imageSrc: "https://img.b2bpic.net/free-photo/two-internationals-friends-is-engaged-gym_1157-32112.jpg",              imageAlt: "Strength training session with dumbbells",              buttons: [{ text: "Learn More", href: "services" }]
            },
            {
              id: 2,
              tag: "Endurance",              title: "Cardio & Conditioning",              subtitle: "Boost heart health and stamina",              description: "High-intensity interval training and steady-state cardio programs designed to improve cardiovascular health and build lasting endurance for daily activities.",              imageSrc: "https://img.b2bpic.net/free-photo/two-internationals-friends-is-engaged-gym_1157-32114.jpg",              imageAlt: "Cardiovascular fitness training"
            },
            {
              id: 3,
              tag: "Nutrition",              title: "Nutrition Planning",              subtitle: "Fuel your body for optimal results",              description: "Science-backed nutrition guidance and meal planning tailored to your fitness goals. Learn sustainable eating habits that complement your training program.",              imageSrc: "https://img.b2bpic.net/free-photo/healthy-menu-recipe-food-diet_53876-122837.jpg",              imageAlt: "Healthy nutrition meal planning consultation"
            }
          ]}
        />
      </div>

      <div id="results" data-section="results">
        <MetricCardEleven
          title="Proven Results That Speak"
          description="Track record of transforming lives through personalized fitness coaching and professional guidance."
          tag="Impact"
          textboxLayout="default"
          useInvertedBackground="invertDefault"
          animationType="slide-up"
          buttons={[
            { text: "Book Your Free Consultation", href: "contact" }
          ]}
          metrics={[
            {
              id: "1",              value: "500+",              title: "Clients Trained",              description: "Successful transformations across Toronto",              imageSrc: "https://img.b2bpic.net/free-photo/closeup-businessman-using-laptop-lunch-break_637285-8692.jpg",              imageAlt: "Community of trained fitness clients"
            },
            {
              id: "2",              value: "95%",              title: "Goal Achievement Rate",              description: "Clients reaching their fitness targets",              imageSrc: "https://img.b2bpic.net/free-photo/two-internationals-friends-is-engaged-gym_1157-32155.jpg",              imageAlt: "Fitness transformation success results"
            },
            {
              id: "3",              value: "8+",              title: "Years Experience",              description: "Dedicated to fitness excellence",              imageSrc: "https://img.b2bpic.net/free-photo/executives-sharing-ideas-before-meeting_1098-1273.jpg",              imageAlt: "Professional certified trainer credentials"
            },
            {
              id: "4",              value: "100%",              title: "Toronto Based",              description: "Local training expertise you can trust",              imageSrc: "https://img.b2bpic.net/free-photo/woman-stretching-quadriceps_1262-421.jpg",              imageAlt: "Toronto fitness training location"
            }
          ]}
        />
      </div>

      <div id="pricing" data-section="pricing">
        <PricingCardNine
          title="Training Plans for Every Goal"
          description="Choose the plan that best fits your fitness journey. All plans include personalized programming and ongoing support."
          tag="Pricing"
          textboxLayout="default"
          useInvertedBackground="noInvert"
          animationType="slide-up"
          plans={[
            {
              id: "starter",              title: "Starter",              price: "$199",              period: "/month",              imageSrc: "https://img.b2bpic.net/free-photo/beautiful-sports-couple-is-engaged-gym_1157-21910.jpg",              imageAlt: "Starter fitness plan",              features: [
                "2 in-person sessions per week",                "Form correction and technique coaching",                "Email support",                "Basic workout programming",                "Progress tracking"
              ],
              button: { text: "Get Started", href: "contact" }
            },
            {
              id: "standard",              title: "Standard",              price: "$349",              period: "/month",              imageSrc: "https://img.b2bpic.net/free-photo/handsome-man-is-engaged-gym_1157-29458.jpg",              imageAlt: "Standard fitness plan",              features: [
                "4 in-person sessions per week",                "Personalized nutrition planning",                "Phone & email support",                "Advanced workout programming",                "Body composition tracking",                "Monthly progress assessments"
              ],
              button: { text: "Get Started", href: "contact" }
            },
            {
              id: "premium",              title: "Premium",              price: "$599",              period: "/month",              imageSrc: "https://img.b2bpic.net/free-photo/sports-couple-sportswear-training-gym_1157-30392.jpg",              imageAlt: "Premium fitness plan",              features: [
                "Unlimited in-person sessions",                "Comprehensive nutrition coaching",                "Priority support (24/7)",                "Elite performance programming",                "Advanced body metrics analysis",                "Weekly 1-on-1 nutrition consultations",                "Custom supplement recommendations"
              ],
              button: { text: "Get Started", href: "contact" }
            }
          ]}
        />
      </div>

      <style jsx>{`
        @keyframes countdown-pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.7; }
        }
        .limited-offer-tag {
          position: absolute;
          top: 12px;
          right: 12px;
          background: linear-gradient(135deg, #ff3d4a 0%, #e63946 100%);
          color: white;
          padding: 6px 12px;
          border-radius: 6px;
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 12px;
          font-weight: 600;
          z-index: 10;
          animation: countdown-pulse 1s ease-in-out infinite;
          box-shadow: 0 4px 12px rgba(230, 57, 70, 0.4);
        }
        .timer-text {
          font-family: 'Courier New', monospace;
          letter-spacing: 0.5px;
        }
      `}</style>

      <div id="testimonials" data-section="testimonials">
        <TestimonialCardFifteen
          testimonial="Working with this trainer completely changed my life. I went from zero fitness experience to running a 5K and feeling stronger than ever. The personalized approach and constant encouragement made all the difference."
          rating={5}
          author="Marcus Johnson"
          avatars={[
            {
              src: "https://img.b2bpic.net/free-photo/confident-sportsman-with-headphones-jumping-rope_1098-21632.jpg",              alt: "Marcus Johnson client testimonial"
            },
            {
              src: "https://img.b2bpic.net/free-photo/smiling-athletic-man-black-background_613910-9870.jpg",              alt: "Sarah Chen client testimonial"
            },
            {
              src: "https://img.b2bpic.net/free-photo/portrait-smiling-afro-american-sports-man-with-arms-folded-looking-camera_171337-8263.jpg",              alt: "David Williams client testimonial"
            },
            {
              src: "https://img.b2bpic.net/free-photo/beautiful-sportive-girl-posing-with-crossed-arms-dark-wall_176420-618.jpg",              alt: "Emma Rodriguez client testimonial"
            }
          ]}
          useInvertedBackground="invertDefault"
        />
      </div>

      <div id="faq" data-section="faq">
        <FaqSplitMedia
          title="Your Training Questions Answered"
          description="Get clarity on pricing, programs, and what to expect from your fitness journey with us."
          tag="FAQ"
          textboxLayout="default"
          useInvertedBackground="noInvert"
          mediaPosition="left"
          imageSrc="https://img.b2bpic.net/free-photo/two-internationals-friends-is-engaged-gym_1157-32156.jpg"
          imageAlt="Fitness training guidance and support"
          faqs={[
            {
              id: "1",              title: "What if I'm a complete beginner?",              content: "Perfect! We specialize in working with beginners. Every program is tailored to your current fitness level. We'll start with foundational movements, proper form coaching, and gradually progress as you build strength and confidence. No judgment, just results."
            },
            {
              id: "2",              title: "How often do I need to train?",              content: "That depends on your goals and schedule. Our Starter plan includes 2 sessions per week (great for maintenance), Standard plan has 4 sessions (ideal for transformation), and Premium offers unlimited access. Most clients see results with 3-4 sessions weekly plus proper nutrition."
            },
            {
              id: "3",              title: "Can I do online training instead?",              content: "Absolutely! We offer complete online training programs for busy professionals. You'll receive customized workouts, form correction via video, nutrition guidance, and ongoing support. Online training is perfect if your schedule is unpredictable or you prefer training from home."
            },
            {
              id: "4",              title: "What about nutrition? Do you help with meal planning?",              content: "Yes! Nutrition is crucial for results. Our Standard and Premium plans include personalized nutrition guidance. We don't do restrictive diets—instead, we teach sustainable eating habits that fit your lifestyle and complement your training."
            },
            {
              id: "5",              title: "How long before I see results?",              content: "You'll feel stronger within 2-3 weeks. Visible physical changes typically appear within 4-6 weeks with consistent training and proper nutrition. More dramatic transformations take 12-16 weeks. Remember: we focus on sustainable progress, not quick fixes."
            },
            {
              id: "6",              title: "Do you offer a free consultation?",              content: "Yes! We offer a free 30-minute consultation where we discuss your goals, assess your current fitness level, and create a custom training plan. This is your chance to ask questions and see if we're the right fit for you."
            }
          ]}
        />
      </div>

      <div id="contact" data-section="contact">
        <ContactFaq
          ctaTitle="Ready to Transform?"
          ctaDescription="Book your free 30-minute consultation today and let's discuss your fitness goals."
          ctaIcon={Phone}
          ctaButton={{ text: "Book Free Consultation", href: "https://calendly.com/fitpro-toronto" }}
          useInvertedBackground="invertDefault"
          animationType="slide-up"
          faqs={[
            {
              id: "1",              title: "How do I book my first session?",              content: "Click the booking button to schedule your free consultation. We'll discuss your fitness goals, current challenges, and create a personalized training plan during this call. After that, we'll get you scheduled for your first training session."
            },
            {
              id: "2",              title: "What should I bring to my first session?",              content: "Wear comfortable workout clothes and bring water. We provide all necessary equipment. If you have any injuries or health concerns, please mention them beforehand so we can modify the workout accordingly."
            },
            {
              id: "3",              title: "Do you offer trial sessions?",              content: "Yes! Your free consultation includes a 15-minute sample training session so you can experience our coaching style. This helps us ensure we're a good fit for your needs."
            },
            {
              id: "4",              title: "What is your cancellation policy?",              content: "We require 24 hours notice for cancellations. This allows us to offer the slot to other clients. Last-minute cancellations may result in a session charge."
            }
          ]}
        />
      </div>

      <div id="footer" data-section="footer">
        <FooterMedia
          logoText="FitPro Toronto"
          imageSrc="https://img.b2bpic.net/free-photo/happy-man-sitting-floor-looking-woman-gym_23-2147949623.jpg"
          imageAlt="Professional training gym atmosphere"
          copyrightText="© 2025 FitPro Toronto. All rights reserved. Certified Personal Training Services."
          columns={[
            {
              title: "Services",              items: [
                { label: "Strength Training", href: "services" },
                { label: "Cardio Programs", href: "services" },
                { label: "Nutrition Coaching", href: "services" },
                { label: "Online Training", href: "services" }
              ]
            },
            {
              title: "Resources",              items: [
                { label: "About", href: "about" },
                { label: "Pricing", href: "pricing" },
                { label: "FAQ", href: "faq" },
                { label: "Contact", href: "contact" }
              ]
            },
            {
              title: "Contact",              items: [
                { label: "Toronto, ON", href: "#" },
                { label: "Email Support", href: "mailto:info@fitpro-toronto.com" },
                { label: "Phone: (416) 555-0123", href: "tel:+14165550123" }
              ]
            }
          ]}
        />
      </div>
    </ThemeProvider>
  );
}
