"use client";

import { useState } from "react";
import {
  Star,
  Zap,
  Clock,
  Calendar,
  Globe,
  Award,
  ArrowRight,
  MessageCircle,
  Shield,
  Play,
  CircleCheck,
  Target,
} from "lucide-react";

import RollingCourseDate from "@/components/courses/RollingCourseDate";

const iconMap = {
  clock: Clock,
  calendar: Calendar,
  globe: Globe,
  award: Award,
};

function getYouTubeEmbedUrl(value) {
  const rawUrl = typeof value === "string" ? value.trim() : "";
  if (!rawUrl) return "";

  try {
    const url = new URL(rawUrl);
    const hostname = url.hostname.toLowerCase().replace(/^www\./, "");
    let videoId = "";

    if (hostname === "youtu.be") {
      videoId = url.pathname.split("/").filter(Boolean)[0] || "";
    } else if (hostname === "youtube.com" || hostname === "m.youtube.com") {
      if (url.pathname.startsWith("/embed/")) {
        videoId = url.pathname.split("/").filter(Boolean)[1] || "";
      } else if (url.pathname.startsWith("/shorts/")) {
        videoId = url.pathname.split("/").filter(Boolean)[1] || "";
      } else {
        videoId = url.searchParams.get("v") || "";
      }
    }

    return videoId
      ? `https://www.youtube.com/embed/${encodeURIComponent(videoId)}`
      : "";
  } catch {
    return "";
  }
}

function getInlinePreviewSource(preview = {}) {
  const video = typeof preview.video === "string" ? preview.video.trim() : "";
  const link = typeof preview.link === "string" ? preview.link.trim() : "";
  const source = video || link;
  const youtubeEmbedUrl = getYouTubeEmbedUrl(source);

  if (youtubeEmbedUrl) return youtubeEmbedUrl;
  if (video) return video;
  return /\.(mp4|webm|ogg)(?:$|[?#])/i.test(link) ? link : "";
}

export default function HeroSection({ data }) {
  const [isPreviewPlaying, setIsPreviewPlaying] = useState(false);
  const isTesol = data.layout === "tesol";
  const isClassicTitle = data.titleSize === "classic";
  const hasThreeButtons = data.buttons.length === 3;
  const previewVideoSrc = getInlinePreviewSource(data.preview);
  const playsInline = Boolean(previewVideoSrc);
  const isDirectVideo = /\.(mp4|webm|ogg)(?:$|[?#])/i.test(previewVideoSrc);
  const previewImageSrc =
    typeof data?.preview?.image === "string"
      ? data.preview.image.trim()
      : "";
  const previewClassName = isTesol
    ? "relative aspect-video rounded-2xl overflow-hidden mb-6 flex items-center justify-center group cursor-pointer block"
    : "relative aspect-video rounded-2xl overflow-hidden bg-gradient-to-br from-[#4A141E] to-[#3B0F18] mb-6 flex items-center justify-center group cursor-pointer";
  const inlineVideoSrc = playsInline && !isDirectVideo
    ? `${previewVideoSrc}${
        previewVideoSrc.includes("?") ? "&" : "?"
      }autoplay=1&rel=0`
    : "";
  const previewArtwork = (
    <>
      {isDirectVideo ? (
        <video
          className="absolute inset-0 z-0 hidden w-full h-full object-cover"
          poster={previewImageSrc || undefined}
          preload="metadata"
          playsInline
          muted
        >
          <source src={previewVideoSrc} />
        </video>
      ) : null}
      {previewImageSrc ? (
        <img
          src={previewImageSrc}
          alt={data.preview.alt || "Course preview image"}
          className={
            isTesol
              ? "w-full h-full object-cover"
              : "absolute inset-0 z-10 w-full h-full object-cover opacity-75"
          }
        />
      ) : null}

      {isTesol ? (
        <>
          <div className="absolute inset-0 bg-black/30 group-hover:bg-black/20 transition-all" />
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-20 h-20 rounded-full bg-gradient-to-r from-[#8B1C1C] to-[#D4AF37] flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform duration-300 border-4 border-white">
              <Play className="w-8 h-8 text-white fill-white ml-1" />
            </div>
          </div>
          <div className="absolute top-3 right-3 bg-[#D4AF37] px-2 py-0.5 rounded-full text-xs font-black text-[#4A141E]">
            {data.preview.label}
          </div>
        </>
      ) : (
        <>
          <span className="relative z-30 w-20 h-20 rounded-full bg-gradient-to-r from-[#8B1C1C] to-[#D4AF37] flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform duration-300 border-4 border-white">
            <Play className="w-8 h-8 text-white fill-white ml-1" />
          </span>
          <div className="absolute bottom-4 left-4 z-20 bg-black/70 px-3 py-1 rounded-full text-white text-sm font-semibold">
            {data.preview.label}
          </div>
        </>
      )}
    </>
  );

  return (
    <section className="relative overflow-hidden bg-gradient-to-br from-[#4A141E] via-[#3B0F18] to-[#2B0A11] border-b-4 border-[#D4AF37]">
      {isTesol ? (
        <div className="absolute inset-0">
          <div className="absolute top-20 left-10 w-96 h-96 bg-[#D4AF37]/10 rounded-full blur-3xl animate-pulse" />
          <div className="absolute bottom-20 right-10 w-[600px] h-[600px] bg-[#8B1C1C]/20 rounded-full blur-3xl animate-pulse delay-1000" />
        </div>
      ) : null}
      <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 md:py-24">
        <div
          className={`grid lg:grid-cols-2 items-center ${
            isTesol ? "gap-12" : "gap-10"
          }`}
        >
          <div>
            <div
              className={`inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#D4AF37]/20 border border-[#D4AF37]/40 mb-4 ${
                isTesol ? "" : "text-[#E6D3B1] text-sm font-bold"
              }`}
            >
              <Star className="w-4 h-4 text-[#D4AF37] fill-[#D4AF37]" />
              {isTesol ? (
                <span className="text-sm font-bold text-[#E6D3B1]">
                  {data.topBadge}
                </span>
              ) : (
                data.topBadge
              )}
            </div>

            {data.liveBadge ? (
              <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/8 border border-white/15 mb-5">
                <span
                  className={`w-2 h-2 rounded-full bg-green-400 ${
                    isTesol ? "animate-pulse" : ""
                  }`}
                />
                <span className="text-xs font-semibold text-[#E6D3B1]/80 uppercase tracking-wider">
                  {data.liveBadge}
                </span>
              </div>
            ) : null}

            <h1
              className={
                isTesol
                  ? "text-4xl md:text-5xl lg:text-6xl font-black text-[#F6EFE9] mb-6 leading-[60px]"
                  : isClassicTitle
                    ? "text-4xl md:text-5xl lg:text-6xl font-black text-[#F6EFE9] mb-6 leading-[60px]"
                  : "text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-black text-[#F6EFE9] mb-6 leading-[60px]"
              }
            >
              {data.title.before}{" "}
              <span className="text-transparent bg-clip-text bg-gradient-to-r from-[#D4AF37] to-[#E6D3B1]">
                {data.title.highlight}
              </span>
            </h1>

            <div
              className={
                isTesol
                  ? "space-y-4 mb-7"
                  : "space-y-3 mb-6 text-[#E6D3B1]"
              }
            >
              {data.points.map((point) => (
                <div key={point} className="flex items-start gap-3">
                  <Zap className="w-6 h-6 text-[#D4AF37] flex-shrink-0 mt-1" />
                  <p
                    className={
                      isTesol ? "text-xl text-[#E6D3B1]" : "text-lg"
                    }
                  >
                    {point}
                  </p>
                </div>
              ))}
            </div>

            <p
              className={`text-sm text-[#E6D3B1]/70 italic ${
                isTesol ? "mb-7" : "mb-8"
              }`}
            >
              {data.note}
            </p>

            <div
              className={`flex flex-wrap ${
                isTesol ? "gap-5 mb-7" : "gap-6 mb-8"
              }`}
            >
              {data.meta.map((item) => {
                const Icon = iconMap[item.type];

                return (
                  <div key={item.text} className="flex items-center gap-2">
                    <Icon className="w-5 h-5 text-[#D4AF37]" />
                    <span className="text-[#F6EFE9]">
                      <strong className="text-[#D4AF37]">{item.label}</strong>{" "}
                      <RollingCourseDate
                        rolloverDay={item.rolloverDay}
                        courseDay={item.courseDay}
                      >
                        {item.text}
                      </RollingCourseDate>
                    </span>
                  </div>
                );
              })}
            </div>

            <div
              className={
                hasThreeButtons
                  ? `grid w-full grid-cols-3 gap-2 sm:gap-3 ${isTesol ? "" : "mb-8"}`
                  : `flex flex-wrap gap-4 ${isTesol ? "" : "mb-8"}`
              }
            >
              {data.buttons.map((button) => {
                const isPrimary = button.variant === "primary";
                const isTest = button.variant === "test";

                return (
                  <a
                    key={button.label}
                    href={button.href}
                    target={button.href.startsWith("http") ? "_blank" : undefined}
                    rel={
                      button.href.startsWith("http")
                        ? "noopener noreferrer"
                        : undefined
                    }
                    className={
                      isPrimary && isTesol
                        ? "group px-8 py-4 rounded-2xl font-black text-lg bg-[#8B1C1C] text-white shadow-xl hover:shadow-2xl hover:scale-105 transition-all duration-300 flex items-center gap-2 border-2 border-[#8B1C1C] hover:border-[#D4AF37]"
                        : isPrimary
                          ? `inline-flex min-w-0 items-center justify-center gap-1.5 rounded-2xl font-black transition-all duration-300 hover:scale-105 bg-[#8B1C1C] text-white border-2 border-[#8B1C1C] hover:border-[#D4AF37] shadow-xl hover:shadow-2xl ${
                              hasThreeButtons
                                ? "w-full px-1.5 py-3 text-[10px] sm:px-3 sm:text-xs xl:px-4 xl:text-sm"
                                : "px-6 sm:px-8 py-4 text-base sm:text-lg"
                            }`
                        : isTest
                          ? `inline-flex min-w-0 items-center justify-center gap-1.5 rounded-2xl font-black transition-all duration-300 hover:scale-105 bg-[#D4AF37] text-[#4A141E] border-2 border-[#D4AF37] hover:bg-[#E6D3B1] shadow-xl ${
                              hasThreeButtons
                                ? "w-full px-1.5 py-3 text-[10px] sm:px-3 sm:text-xs xl:px-4 xl:text-sm"
                                : "px-6 sm:px-8 py-4 text-base sm:text-lg"
                            }`
                        : isTesol
                          ? "group px-8 py-4 rounded-2xl font-bold text-lg bg-white/10 text-[#F6EFE9] hover:bg-white/20 border-2 border-[#E6D3B1]/30 flex items-center gap-2 backdrop-blur-sm transition-all duration-300"
                          : `inline-flex min-w-0 items-center justify-center gap-1.5 rounded-2xl font-black transition-all duration-300 hover:scale-105 bg-white/10 text-[#F6EFE9] hover:bg-white/20 border-2 border-[#E6D3B1]/30 backdrop-blur-sm ${
                              hasThreeButtons
                                ? "w-full px-1.5 py-3 text-[10px] sm:px-3 sm:text-xs xl:px-4 xl:text-sm"
                                : "px-6 sm:px-8 py-4 text-base sm:text-lg"
                            }`
                    }
                  >
                    {isTest && (
                      <Target
                        className={
                          hasThreeButtons
                            ? "h-4 w-4 shrink-0"
                            : "h-5 w-5"
                        }
                      />
                    )}
                    {!isPrimary && !isTest && (
                      <MessageCircle
                        className={
                          hasThreeButtons
                            ? "h-4 w-4 shrink-0"
                            : "h-5 w-5"
                        }
                      />
                    )}
                    <span className="min-w-0 text-center">{button.label}</span>
                    {isPrimary && (
                      <ArrowRight
                        className={`shrink-0 group-hover:translate-x-1 transition-transform ${
                          hasThreeButtons ? "h-4 w-4" : "h-5 w-5"
                        }`}
                      />
                    )}
                  </a>
                );
              })}
            </div>

            <div
              className={`flex items-center gap-3 text-sm text-[#E6D3B1] ${
                isTesol ? "mt-5" : "mt-6"
              }`}
            >
              <Shield className="w-4 h-4 text-[#D4AF37]" />
              <span>{data.guarantee}</span>
            </div>
          </div>

          <div data-static-border="true" data-hero-preview-card="true" className="p-8 rounded-3xl bg-white border-2 border-[#D4AF37]/50 shadow-2xl">
            {playsInline && isPreviewPlaying ? (
              <div className={previewClassName}>
                {isDirectVideo ? (
                  <video
                    src={previewVideoSrc}
                    poster={previewImageSrc || undefined}
                    className="absolute inset-0 h-full w-full object-cover"
                    controls
                    autoPlay
                    playsInline
                  />
                ) : (
                  <iframe
                    src={inlineVideoSrc}
                    title={data.preview.alt || "Course preview video"}
                    className="absolute inset-0 h-full w-full"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                    referrerPolicy="strict-origin-when-cross-origin"
                    allowFullScreen
                  />
                )}
              </div>
            ) : playsInline ? (
              <button
                type="button"
                onClick={() => setIsPreviewPlaying(true)}
                className={`${previewClassName} w-full`}
                aria-label="Play course preview video"
              >
                {previewArtwork}
              </button>
            ) : (
              <a
                href={data.preview.link}
                target="_blank"
                rel="noopener noreferrer"
                className={previewClassName}
                aria-label="Play course preview video"
              >
                {previewArtwork}
              </a>
            )}

            <div
              className={`grid grid-cols-2 gap-4 ${
                isTesol ? "mb-5" : "mb-6"
              }`}
            >
              {data.stats.map((stat) => (
                <div
                  key={stat.label}
                  className="p-4 rounded-xl bg-[#F6EFE9] border border-[#E6D3B1]/40"
                >
                  <div
                    className={`font-black text-[#4A141E] ${
                      isTesol ? "text-xl" : "text-2xl"
                    }`}
                  >
                    {stat.value}
                  </div>
                  <div
                    className={`text-[#4A141E]/70 ${
                      isTesol ? "text-xs" : "text-sm"
                    }`}
                  >
                    {stat.label}
                  </div>
                </div>
              ))}
            </div>

            <div
              className={
                isTesol ? "space-y-3" : "space-y-4 text-[#4A141E]/80"
              }
            >
              {data.features.map((feature) => (
                <div
                  key={feature}
                  className={isTesol ? "flex items-center gap-3" : "flex gap-2"}
                >
                  <CircleCheck className="w-5 h-5 text-[#8B1C1C] flex-shrink-0" />
                  <span className={isTesol ? "text-[#4A141E]/80" : ""}>
                    {feature}
                  </span>
                </div>
              ))}
            </div>

            <div className="mt-6 pt-6 border-t-2 border-[#E6D3B1]/30">
              <div className="flex items-center justify-between text-sm text-[#4A141E]/70">
                <span>{data.footer.lastUpdated}</span>

                <div className="flex items-center gap-1">
                  <Shield className="w-4 h-4 text-[#D4AF37]" />
                  <span className="font-semibold text-[#4A141E]">
                    {data.footer.accreditation}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
