"use client";

import { AnimatePresence, motion, useScroll, useTransform } from "framer-motion";
import Image from "next/image";
import { useEffect, useState } from "react";

export default function WattsLightsPage() {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showContent, setShowContent] = useState(false);

  useEffect(() => {
    const startTime = Date.now();

    fetch("/api/watts-lights")
      .then((res) => res.json())
      .then((json) => {
        const elapsedTime = Date.now() - startTime;
        const remainingTime = Math.max(0, 1000 - elapsedTime);

        setTimeout(() => {
          setData(json);
          setLoading(false);
          setShowContent(true);
        }, remainingTime);
      })
      .catch(() => {
        setError("Failed to load content.");
        setLoading(false);
      });
  }, []);

  if (loading)
    return (
      <div className="min-h-screen bg-[#020c13] flex items-center justify-center">
        <div className="text-center">
          <div className="w-32 h-32 mx-auto mb-8 relative">
            <div className="absolute inset-0 border-4 border-[#B87333] rounded-full animate-spin border-t-transparent"></div>
            <div className="absolute inset-0 flex items-center justify-center">
              <span className="text-4xl">💡</span>
            </div>
          </div>
          <h2 className="text-2xl font-bold text-[#B87333] mb-2">Loading Watts Lights</h2>
          <p className="text-gray-400">Preparing your lighting experience...</p>
        </div>
      </div>
    );
  if (error) return <div className="text-red-500 p-10">{error}</div>;
  if (!data) return null;

  const { hero, features, infoSection, ctaSection, appStores, tutorialVideo } = data;

  return (
    <AnimatePresence>
      {showContent && (
        <motion.main
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
          className="min-h-screen bg-[#020c13] text-white flex flex-col justify-between"
        >
          {/* Hero Section */}
          <section className="flex flex-col md:flex-row items-center justify-between max-w-6xl mx-auto pt-20 pb-12 px-4 gap-12 w-full">
            {/* Left: Headline & CTA */}
            <div className="flex-1 max-w-xl">
              <h1 className="text-5xl md:text-6xl font-extrabold mb-4 leading-tight">
                <span className="text-[#B87333]">{hero.title?.split("by")[0]}</span>
                {hero.title?.includes("by") && (
                  <span className="text-white"> by{hero.title.split("by")[1]}</span>
                )}
              </h1>
              <p className="text-lg md:text-xl text-gray-300 mb-8">{hero.subtitle}</p>
              <a
                href={hero.buttonLink}
                className="inline-block px-7 py-4 rounded-full bg-[#B87333] text-white font-semibold text-lg shadow-lg hover:bg-[#ff914d] transition-colors focus:outline-none focus:ring-2 focus:ring-[#B87333] focus:ring-offset-2 focus:ring-offset-[#020c13]"
              >
                {hero.buttonText}
              </a>
            </div>
            {/* Right: YouTube Video */}
            <div className="flex-1 flex justify-center items-center min-w-[300px]">
              <div className="w-full max-w-[600px] aspect-[16/9] rounded-md overflow-hidden border-2 border-[#B87333]/30 shadow-md group">
                <iframe
                  src={`https://www.youtube.com/embed/${hero.youtubeVideoId}?autoplay=1&mute=1&loop=1&playlist=${hero.youtubeVideoId}&controls=0&showinfo=0&rel=0&modestbranding=1`}
                  title="Watts Lights Technology Showcase"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowFullScreen
                  className="w-full h-full group-hover:opacity-100 opacity-90 transition-opacity duration-300"
                />
              </div>
            </div>
          </section>

          {/* Features Section */}
          <section className="max-w-6xl mx-auto w-full px-4 mb-24">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
              {features.map((feature: any, idx: number) => (
                <motion.div
                  key={idx}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: idx * 0.1 }}
                  className="flex-1 min-w-[260px] bg-[#181c20] rounded-md shadow-md p-8 flex flex-col items-center text-center border border-[#B87333]/20 hover:border-[#B87333]/60 hover:shadow-lg transition-all"
                >
                  <div className="text-4xl mb-3">{feature.icon}</div>
                  <h3 className="font-bold text-lg mb-2 text-[#B87333]">{feature.title}</h3>
                  <p className="text-gray-300 text-base">{feature.description}</p>
                </motion.div>
              ))}
            </div>
          </section>

          {/* Tutorial Video Section */}
          {tutorialVideo?.youtubeVideoId && (
            <motion.section
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              className="max-w-6xl mx-auto w-full px-4 mb-24"
            >
              <div className="bg-[#181c20] rounded-md shadow-md p-10 border border-[#B87333]/30">
                <div className="text-center mb-8">
                  <h2 className="text-3xl md:text-4xl font-bold text-white mb-4">{tutorialVideo.title}</h2>
                  <p className="text-lg text-gray-300">{tutorialVideo.description}</p>
                </div>
                <div className="w-full max-w-[800px] mx-auto aspect-[16/9] rounded-md overflow-hidden border-2 border-[#B87333]/30 shadow-md group">
                  <iframe
                    src={`https://www.youtube.com/embed/${tutorialVideo.youtubeVideoId}?autoplay=1&mute=1&loop=1&playlist=${tutorialVideo.youtubeVideoId}&controls=0&showinfo=0&rel=0&modestbranding=1`}
                    title={tutorialVideo.title}
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                    className="w-full h-full group-hover:opacity-100 opacity-90 transition-opacity duration-300"
                  />
                </div>
              </div>
            </motion.section>
          )}

          {/* App Stores Section */}
          {(appStores?.appleStoreLink || appStores?.googlePlayLink) && (
            <motion.section
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.3 }}
              className="max-w-6xl mx-auto w-full px-4 mb-16"
            >
              <div className="bg-[#181c20] rounded-md shadow-md p-2 border border-[#B87333]/30">
                <div className="text-center mb-8">
                  <h2 className="text-3xl md:text-4xl font-bold text-white mb-4 mt-6">
                    Download Watts Lights App
                  </h2>
                  <p className="text-lg text-gray-300">
                    Control your Watts Lights system from anywhere with our mobile app
                  </p>
                </div>
                <div className="flex flex-col md:flex-row items-center justify-center gap-6">
                  {appStores.appleStoreLink && (
                    <a
                      href={appStores.appleStoreLink}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="transition-transform hover:scale-105"
                    >
                      <Image
                        src="/images/apple.svg"
                        alt="Download on the App Store"
                        width={120}
                        height={40}
                        className="h-44 w-auto"
                      />
                    </a>
                  )}
                  {appStores.googlePlayLink && (
                    <a
                      href={appStores.googlePlayLink}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="transition-transform hover:scale-105"
                    >
                      <Image
                        src="/images/google.svg"
                        alt="Get it on Google Play"
                        width={120}
                        height={40}
                        className="h-44 w-auto"
                      />
                    </a>
                  )}
                </div>
              </div>
            </motion.section>
          )}

          {/* Fading Divider */}
          <div className="max-w-6xl mx-auto w-full flex items-center justify-center mb-20 px-4">
            <div className="w-full h-1 rounded-full bg-gradient-to-r from-transparent via-[#B87333] to-transparent opacity-70" />
          </div>

          {/* Informational Section */}
          <motion.section
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.4 }}
            className="max-w-6xl mx-auto w-full bg-[#181c20] rounded-md shadow-md p-10 mb-24 flex flex-col items-center border border-[#B87333]/30"
          >
            <div className="flex items-center mb-4">
              <span className="text-2xl mr-2">💡</span>
              <h2 className="text-2xl md:text-3xl font-bold text-white">{infoSection.title}</h2>
            </div>
            <p className="text-gray-300 text-lg text-center">{infoSection.content}</p>
          </motion.section>

          {/* CTA Section */}
          <motion.section
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, delay: 0.5 }}
            className="max-w-6xl mx-auto w-full px-4 mb-24"
          >
            <div className="w-full bg-[#181c20] border-2 border-[#B87333] rounded-md shadow-md p-12 flex flex-col items-center">
              <h3 className="text-3xl md:text-4xl font-extrabold text-white mb-4">{ctaSection.headline}</h3>
              <p className="text-lg text-gray-300 mb-8 max-w-2xl">{ctaSection.text}</p>
              <a
                href={ctaSection.buttonLink}
                className="inline-block px-10 py-5 rounded-full bg-[#B87333] text-white font-bold text-xl shadow-lg hover:bg-[#181c20] hover:text-[#B87333] border-2 border-[#B87333] transition-colors focus:outline-none focus:ring-2 focus:ring-[#B87333] focus:ring-offset-2 focus:ring-offset-[#020c13]"
              >
                {ctaSection.buttonText}
              </a>
            </div>
          </motion.section>
        </motion.main>
      )}
    </AnimatePresence>
  );
}
