import { Badge } from "@/components/ui/badge";
import AccordionCommon from "@/components/common-accordion/common-accordion";
import { KnowmoreCommonButtons } from "@/components/common-knowbuild-knowmore/knowmore-buttons";
import { TextComponent } from "@/components/custom-components/TextComponent/TextComponent";
import { notFound } from "next/navigation";
import {
  chapterDataFive,
  chapterDataFour,
  chapterDataOne,
  chapterDataThree,
  chapterDataTwo,
} from "@/staticData/narrative-chapter-1-mock-data";
import { getMetadata } from "@/lib/metadata";

const mindsetChapterCollections = [
  {
    id: 1,
    chapter_content: chapterDataOne,
  },
  {
    id: 2,
    chapter_content: chapterDataTwo,
  },
  {
    id: 3,
    chapter_content: chapterDataThree,
  },
  {
    id: 4,
    chapter_content: chapterDataFour,
  },
  {
    id: 5,
    chapter_content: chapterDataFive,
  },
];

function getYouTubeEmbedUrl(url: string) {
  if (!url) return null;
  try {
    const u = new URL(url);
    let videoId = null;

    if (u.hostname.includes("youtube.com")) {
      videoId = u.searchParams.get("v");
      if (!videoId && u.pathname.startsWith("/embed/")) {
        videoId = u.pathname.split("/")[2];
      }
    } else if (u.hostname.includes("youtu.be")) {
      videoId = u.pathname.slice(1);
    }

    return videoId ? `https://www.youtube-nocookie.com/embed/${videoId}?modestbranding=1&rel=0` : null;
  } catch {
    return null;
  }
}

function VideoEmbed({ url, title }: { url: string; title: string }) {
  const embedUrl = getYouTubeEmbedUrl(url);

  return (
    <div className="w-full relative group">
      {/* Glow Effect */}
      <div className="absolute -inset-1 bg-gradient-to-r from-brand-blue via-brand-teal to-brand-orange rounded-2xl blur opacity-25 group-hover:opacity-50 transition duration-1000 group-hover:duration-200" />
      
      <div className="relative w-full aspect-video rounded-2xl overflow-hidden bg-brand-navy ring-1 ring-white/10 shadow-2xl">
        {embedUrl ? (
          <iframe
            src={embedUrl}
            width="100%"
            height="100%"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowFullScreen
            loading="lazy"
            title={title}
            className="w-full h-full"
          />
        ) : (
          <video 
            src={url} 
            controls 
            playsInline 
            preload="metadata" 
            className="w-full h-full object-contain bg-black"
          >
            Your browser does not support the video tag.
          </video>
        )}
      </div>
    </div>
  );
}

export default function MindsetChapterDetail({
  params,
}: {
  params: { mindsetid: string };
}) {
  const chapterId = Number.parseInt(params.mindsetid, 10);
  const chapterData = mindsetChapterCollections.find((chapter) => chapter.id === chapterId)?.chapter_content;

  if (!chapterData) notFound();

  return (
    <section className="relative pt-40 pb-20 md:pt-48 md:pb-32 bg-slate-50 dark:bg-[#0B1220] min-h-screen">
      <div className="md:container mx-auto mt-8 relative px-4 sm:px-6 lg:px-8">
        <div className="space-y-7 mb-10 md:mb-16">
          <div className="w-full h-fit flex justify-center">
            <Badge className="uppercase">The knowbuild mindset</Badge>
          </div>
          <div className="space-y-6 mx-auto lg:w-full">
            <TextComponent className="text-center">{chapterData.title}</TextComponent>
          </div>
        </div>

        <div className="max-w-5xl mx-auto space-y-8">
          <VideoEmbed url={chapterData.videoUrl} title={chapterData.title} />

          {chapterData.content?.length > 0 && (
            <section className="space-y-6 text-slate-600 dark:text-slate-300">
              {chapterData.content.map((paragraph, index) => (
                <p key={index} className="leading-relaxed">
                  {paragraph}
                </p>
              ))}
            </section>
          )}

          <section className="prose-container">
            <div
              className="prose prose-lg max-w-none dark:prose-invert prose-p:leading-relaxed prose-a:text-primary prose-blockquote:border-primary"
              dangerouslySetInnerHTML={{ __html: chapterData.dynamicContent }}
            />
          </section>
        </div>

        <div className="my-16">
          <div className="my-16">
            <TextComponent className="">Knowbuild: Your smart assistant for seamless workflow integration and scalable growth.</TextComponent>
          </div>
          <AccordionCommon />
        </div>

        <div className="my-16 md:my-20 lg:my-32">
          <KnowmoreCommonButtons />
        </div>
      </div>
    </section>
  );
}

export async function generateMetadata({
  params,
}: {
  params: { mindsetid: string };
}) {
  const chapterNumber = parseInt(params.mindsetid, 10);
  const suffix = isNaN(chapterNumber) ? "" : ` Chapter ${chapterNumber}`;

  return getMetadata({
    title: `Knowbuild - Mindset${suffix}`,
    description: `Knowbuild Mindset${suffix}: leadership, structure, and strategies to help SMEs grow with clarity and confidence.`,
  });
}
