"use client";

import Image from "next/image";
import { useState, useEffect } from "react";
import useEmblaCarousel from "embla-carousel-react";
import { ChevronDown } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { Reveal } from "@/components/shared/Reveal";

type NumberedPoint = {
  title: string;
  description: string;
};

type BlogCard = {
  title: string;
  description: string;
  points: NumberedPoint[];
};

type BlogSection = {
  id: string;

  type:
    | "introduction"
    | "numbered"
    | "two-column"
    | "standard";

  title?: string;

  content?: string;

  points?: NumberedPoint[];

  cards?: BlogCard[];
};

type Props = {
  blog: {
    slug: string;
    title: string;
    excerpt: string;
    coverImage: string;
    introImage?: string;
    category: string;
    sections: BlogSection[];
    gallery?: string[];
  };
};

/* SECTION HEADING */

function SectionHeading({
  label,
  title,
}: {
  label?: string;
  title?: string;
}) {
  return (
    <div>

      {title && (
        <h2 className="font-sans text-center text-[12px] font-medium uppercase tracking-[0.45em] text-gold-deep">
          {title}
        </h2>
      )}

    </div>
  );
}

function PointList({
  points,
  centered = false,
}: {
  points?: NumberedPoint[];
  centered?: boolean;
}) {
  const validPoints =
    points?.filter(
      (point) =>
        point?.title?.trim() ||
        point?.description?.trim()
    ) ?? [];

  if (!validPoints.length) {
    return null;
  }

  return (
    <div
      className={
        centered
          ? "mt-4 flex justify-center"
          : "mt-4"
      }
    >
      <ul
        className="
          grid
          w-full
          grid-cols-1
          gap-x-8
          gap-y-4
          text-left
          sm:grid-cols-2
        "
      >
        {validPoints.map((point, index) => (
          <li
            key={index}
            className="
              relative
              pl-5
              font-sans
              text-[14px]
              leading-6
              text-mahogany
              transition-colors
              duration-500
              hover:text-espresso
            "
          >
            {/* BULLET */}
            <span
              className="
                absolute
                left-1
                top-[10px]
                h-1.5
                w-1.5
                rounded-full
                bg-gold-deep
              "
            />

            {/* POINT TITLE */}
            {hasText(point.title) && (
              <span className="font-normal text-mahogany">
                {point.title}
              </span>
            )}

            {/* POINT DESCRIPTION */}
            {hasText(point.description) && (
              <>
                {hasText(point.title) && <span> — </span>}

                <span
                  dangerouslySetInnerHTML={{
                    __html: point.description,
                  }}
                />
              </>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}

/* INTRODUCTION */

function IntroductionSection({
  section,
  introImage,
}: {
  section: BlogSection;
  introImage?: string;
}) {
  return (
    <section className="relative left-1/2 mt-2 w-screen -translate-x-1/2 bg-ivory px-6 py-16 md:px-12 md:py-20">

      <Reveal>
        <div className="mx-auto max-w-7xl">

          <div className="grid items-center gap-12 lg:grid-cols-[1.1fr_0.9fr] lg:gap-20">

            {/* LEFT */}

            <div>

              <SectionHeading
                label="Introduction"
                title={section.title}
              />

              {section.content && (
                <div
                  className="
                    mt-8
                    font-sans
                    text-sm
                    font-light
                    leading-8
                    text-mahogany
                    md:text-base
                  "
                  dangerouslySetInnerHTML={{
                    __html: section.content,
                  }}
                />
              )}

            </div>

            {/* RIGHT */}

            {introImage && (
              <Reveal direction="right">

                <div className="relative aspect-[8/5] w-full overflow-hidden rounded-[1.05rem] bg-espresso/10">

                  <Image
                    src={introImage}
                    alt={
                      section.title ||
                      "Introduction"
                    }
                    title={
                      section.title ||
                      "Introduction"
                    }
                    fill
                    sizes="(max-width: 768px) 100vw, 40vw"
                    className="object-cover"
                  />

                </div>

              </Reveal>
            )}

          </div>
        </div>
      </Reveal>

    </section>
  );
}

/* NUMBERED POINTS */

function NumberedSection({
  section,
}: {
  section: BlogSection;
}) {
  if (!section.points?.length) {
    return null;
  }

  return (
    <section className="relative left-1/2 w-screen -translate-x-1/2 bg-cream px-6 py-16 md:px-12 md:py-20">

        <div className="mx-auto max-w-7xl">

          <SectionHeading
            label="Highlights"
            title={section.title}
          />

          <div className="mx-auto mt-6 max-w-6xl">

            {section.points.map(
              (item, index) => (
                <Reveal key={index}>

                  <div className="group border-b border-gold/15 py-8">

                    <div className="grid lg:grid-cols-[90px_1fr]">

                      {/* NUMBER */}

                      <div>
                        <span className="font-serif text-5xl text-gold/25 transition-all duration-500 group-hover:text-gold">
                          {(index + 1)
                            .toString()
                            .padStart(2, "0")}
                        </span>
                      </div>

                      {/* CONTENT */}

                      <div>

                        {item.title && (
                          <h3 className="font-serif text-2xl text-espresso transition-colors duration-500 group-hover:text-gold-deep">
                            {item.title}
                          </h3>
                        )}

                        {item.description && (
                          <div
                            className="
                              mt-2
                              text-[16px]
                              leading-8
                              text-mahogany
                            "
                            dangerouslySetInnerHTML={{
                              __html:
                                item.description,
                            }}
                          />
                        )}

                      </div>

                    </div>

                  </div>

                </Reveal>
              )
            )}

          </div>
        </div>
    </section>
  );
}

/* =========================================================
   HELPERS
========================================================= */

function hasText(value?: string) {
  if (!value) return false;

  const text = value
    .replace(/<[^>]*>/g, "")
    .replace(/&nbsp;/gi, " ")
    .trim();

  return text.length > 0;
}

function hasCardContent(card?: BlogCard) {
  if (!card) return false;

  const hasTitle = hasText(card.title);

  const hasDescription = hasText(
    card.description
  );

  const hasPoints =
    card.points?.some(
      (point) =>
        hasText(point?.title) ||
        hasText(point?.description)
    ) ?? false;

  return (
    hasTitle ||
    hasDescription ||
    hasPoints
  );
}

/* =========================================================
   CARD CONTENT
========================================================= */

function BlogCardContent({
  card,
}: {
  card: BlogCard;
}) {
  const hasDescription = hasText(card.description);

  const hasPoints =
    card.points?.some(
      (point) =>
        hasText(point?.title) ||
        hasText(point?.description)
    ) ?? false;

  return (
    <div className="w-full">

      {/* CARD DESCRIPTION — only when available */}
      {hasDescription && (
        <div
          className="
            blog-column-content
            text-[15px]
            leading-7
            text-mahogany
          "
          dangerouslySetInnerHTML={{
            __html: card.description,
          }}
        />
      )}

      {/* POINTS — always two columns when points exist */}
      {hasPoints && (
        <PointList
          points={card.points}
        />
      )}

    </div>
  );
}

/* =========================================================
   TWO-COLUMN / CARDS SECTION
========================================================= */

function TwoColumnSection({
  section,
}: {
  section: BlogSection;
}) {
  const [openIndex, setOpenIndex] = useState<number | null>(
    null
  );

  const cards =
    section.cards?.filter(hasCardContent) ?? [];

  if (!cards.length) {
    return null;
  }

  const cardCount = cards.length;

  return (
    <section className="relative left-1/2 w-screen -translate-x-1/2 bg-ivory px-6 py-16 md:px-12 md:py-20">

      <div className="mx-auto max-w-7xl">

        <Reveal>

          {/* =================================================
              SECTION HEADER
          ================================================= */}

          <SectionHeading
            label="Explore"
            title={section.title}
          />

          {/* SECTION DESCRIPTION */}

          {hasText(section.content) && (
            <div
              className="
                mx-auto
                mt-6
                max-w-4xl
                text-center
                text-[17px]
                leading-8
                text-mahogany
              "
              dangerouslySetInnerHTML={{
                __html: section.content!,
              }}
            />
          )}

        </Reveal>

        {/* =================================================
            CARDS
        ================================================= */}

        <div
          className={`
            mx-auto
            mt-12
            grid
            max-w-6xl
            items-start
            gap-8
            ${
              cardCount === 1
                ? "lg:grid-cols-1 lg:max-w-6xl"
                : "lg:grid-cols-2"
            }
          `}
        >

          {cards.map((card, index) => {

            const open = openIndex === index;

            const isLast =
              index === cards.length - 1;

            const isOdd =
              cards.length % 2 !== 0;

            return (
              <div
                key={index}
                className={`
                  w-full
                  ${
                    isOdd && isLast
                      ? "lg:col-span-2 lg:mx-auto lg:w-[calc(50%-1rem)]"
                      : ""
                  }
                `}
              >

                <motion.div
                  onHoverStart={() =>
                    setOpenIndex(index)
                  }
                  onHoverEnd={() =>
                    setOpenIndex(null)
                  }
                  className="
                    group
                    overflow-hidden
                    rounded-[22px]
                    border
                    border-gold/15
                    bg-cream
                    will-change-transform
                    transition-all
                    duration-500
                    hover:border-gold
                    hover:shadow-[0_25px_60px_rgba(0,0,0,.08)]
                  "
                >

                  {/* =================================================
                      CARD HEADER
                  ================================================= */}

                  <button
                    type="button"
                    onClick={() =>
                      setOpenIndex(
                        open ? null : index
                      )
                    }
                    className="
                      flex
                      w-full
                      items-center
                      justify-between
                      px-7
                      py-5
                      text-left
                      will-change-transform
                      transition-colors
                      group-hover:bg-gold/5
                    "
                  >

                    <h3
                      className="
                        font-serif
                        text-[26px]
                        italic
                        text-espresso
                        transition-colors
                        will-change-transform
                        duration-500
                        group-hover:text-gold-deep
                      "
                    >
                      {card.title}
                    </h3>

                    <motion.div
                      animate={{
                        rotate: open ? 180 : 0,
                      }}
                      transition={{
                        duration: 0.25,
                      }}
                      className="shrink-0"
                    >
                      <ChevronDown
                        size={24}
                        className="text-gold"
                      />
                    </motion.div>

                  </button>

                  {/* =================================================
                      CARD CONTENT
                  ================================================= */}

                  <AnimatePresence initial={false}>

                    {open && (
                      <motion.div
                        initial={{
                          height: 0,
                          opacity: 0,
                        }}
                        animate={{
                          height: "auto",
                          opacity: 1,
                        }}
                        exit={{
                          height: 0,
                          opacity: 0,
                        }}
                        transition={{
                          height: {
                            duration: 0.35,
                            ease: [
                              0.4,
                              0,
                              0.2,
                              1,
                            ],
                          },
                          opacity: {
                            duration: 0.2,
                          },
                        }}
                        className="overflow-hidden"
                      >

                        <div
                          className="
                            px-8
                            pb-7
                            font-sans
                            text-sm
                            leading-6
                            text-mahogany
                          "
                        >

                          <BlogCardContent
                            card={card}
                          />

                        </div>

                      </motion.div>
                    )}

                  </AnimatePresence>

                </motion.div>

              </div>
            );
          })}

        </div>

      </div>

    </section>
  );
}

/* =========================================================
   STANDARD CONTENT
========================================================= */

function StandardContentSection({
  section,
}: {
  section: BlogSection;
}) {
  return (
    <section className="relative left-1/2 w-screen -translate-x-1/2 bg-cream px-6 py-16 md:px-12 md:py-20">
      <Reveal>
        <div className="mx-auto w-full max-w-4xl">

          <SectionHeading
            label="Article"
            title={section.title}
          />

          {section.content && (
            <div
              className="
                blog-rich-content
                mt-8
                w-full
                text-center
                font-sans
                text-[17px]
                leading-8
                text-mahogany
              "
              dangerouslySetInnerHTML={{
                __html: section.content,
              }}
            />
          )}

        </div>
      </Reveal>
    </section>
  );
}

/* =========================================================
   BLOG CONTENT
========================================================= */

export default function BlogContent({
  blog,
}: Props) {

  const [emblaRef, emblaApi] = useEmblaCarousel({
    loop: true,
    align: "start",
    dragFree: false,
  });

  useEffect(() => {
    if (!emblaApi) return;

    const autoplay = window.setInterval(() => {
      emblaApi.scrollNext();
    }, 3000);

    return () =>
      window.clearInterval(autoplay);
  }, [emblaApi]);

  return (
    <div className="mx-auto max-w-7xl mt-8">

      <div className="mx-auto max-w-4xl text-center">

        <h2 className="font-serif text-2xl leading-relaxed text-espresso md:text-3xl">
          {blog.excerpt}
        </h2>

      </div>

      {/* =================================================
          SECTIONS
      ================================================= */}

      {blog.sections?.length > 0 && (
        <div>

          {blog.sections.map((section) => {

            switch (section.type) {

              case "introduction":
                return (
                  <IntroductionSection
                    key={section.id}
                    section={section}
                    introImage={
                      blog.introImage
                    }
                  />
                );

              case "numbered":
                return (
                  <NumberedSection
                    key={section.id}
                    section={section}
                  />
                );

              case "two-column":
                return (
                  <TwoColumnSection
                    key={section.id}
                    section={section}
                  />
                );

              case "standard":
              default:
                return (
                  <StandardContentSection
                    key={section.id}
                    section={section}
                  />
                );
            }

          })}

        </div>
      )}

      {/* =================================================
          GALLERY
      ================================================= */}

      {blog.gallery &&
        blog.gallery.length > 0 && (
          <section className="relative left-1/2 w-screen -translate-x-1/2 bg-espresso px-4 py-16 md:py-20">

            <Reveal>

              <div className="mx-auto max-w-fulls">

                <h2 className="font-sans text-center text-[12px] font-medium uppercase tracking-[0.45em] text-gold-deep">
                  Gallery
                </h2>

                {/* Embla Carousel */}

                <div
                  className="embla mt-10 overflow-hidden"
                  ref={emblaRef}
                >

                  <div
                    className="
                      flex
                      gap-6
                      pl-10
                      touch-pan-y
                      will-change-transform
                    "
                  >

                    {blog.gallery.map(
                      (image, index) => (
                        <div
                          key={index}
                          className="
                            relative
                            min-w-[85%]
                            sm:min-w-[60%]
                            md:min-w-[45%]
                            lg:min-w-[31%]
                            aspect-[4/3]
                            shrink-0
                            overflow-hidden
                            rounded-xl
                            bg-espresso/10
                          "
                        >

                          <Image
                            src={image}
                            alt={`${blog.title} gallery ${
                              index + 1
                            }`}
                            title={`${blog.title} gallery ${
                              index + 1
                            }`}
                            fill
                            quality={75}
                            sizes="
                              (max-width: 640px) 85vw,
                              (max-width: 1024px) 45vw,
                              31vw
                            "
                            loading="lazy"
                            className="
                              object-cover
                              transition-transform
                              duration-700
                              hover:scale-105
                            "
                          />

                        </div>
                      )
                    )}

                  </div>

                </div>

              </div>

            </Reveal>

          </section>
        )}

    </div>
  );
}