"use client";

import { useEffect } from "react";
import useEmblaCarousel from "embla-carousel-react";
import Image from "next/image";
import Link from "next/link";

import BlogCard from "./BlogCard";
import BlogSidebar from "./BlogSidebar";

type Blog = {
  _id: string;
  slug: string;
  title?: string;
  excerpt?: string;
  coverImage?: string;
  category?: string;
  publishedAt?: string;
  [key: string]: any;
};

type BlogSectionProps = {
  blogs: Blog[];
  trendingBlogs: Blog[];
  latestBlogs: Blog[];
};

export default function BlogSection({
  blogs,
  trendingBlogs,
  latestBlogs,
}: BlogSectionProps) {
  const sortedBlogs = blogs;

  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]);


  const topBlogs = sortedBlogs.slice(0, 6);

  const moreBlogs = sortedBlogs.slice(6);

  return (
    <section className="bg-ivory py-10">
      <div className="max-w-7xl mx-auto px-6 lg:px-0">

        <div className="grid grid-cols-1 lg:grid-cols-12 gap-12">

          <div className="lg:col-span-8 grid md:grid-cols-2 gap-8 items-start">
            {topBlogs.map((blog) => (
              <BlogCard
                key={blog._id}
                blog={blog}
              />
            ))}
          </div>

          <div className="lg:col-span-4">
            <BlogSidebar
              trendingBlogs={trendingBlogs}
              latestBlogs={latestBlogs}
            />
          </div>

        </div>


        {moreBlogs.length > 0 && (
          <section className="relative left-1/2 w-screen -translate-x-1/2 px-4">
            <div className="mx-auto max-w-7xl">
              <div className="text-center mb-10">

                <h2 className="font-serif italic text-3xl md:text-4xl text-espresso font-light leading-tight mt-4">
                  Explore More Stories
                </h2>
              </div>
            </div>

            <div
              className="embla overflow-hidden"
              ref={emblaRef}
            >
              <div
                className={`flex gap-6 pr-8 touch-pan-y will-change-transform ${
                  moreBlogs.length <= 2
                    ? "justify-center pl-8"
                    : "pl-8"
                }`}
              >
                {moreBlogs.map((blog) => (
                  <div
                    key={blog._id}
                    className="
                      relative
                      min-w-[85%]
                      sm:min-w-[60%]
                      md:min-w-[45%]
                      lg:min-w-[31%]
                      shrink-0
                    "
                  >
                    <Link
                      href={`/blogs/${blog.slug}`}
                      title={blog.title}
                      onClick={() => {
                        try {
                          sessionStorage.setItem(
                            "tghr-pending-blog-view",
                            blog.slug
                          );
                        } catch {
                          // Ignore storage errors
                        }
                      }}
                      className="
                        group
                        relative
                        block
                        aspect-[6/4]
                        overflow-hidden
                        rounded-[0.5rem]
                        bg-midnight
                      "
                    >
                      {/* IMAGE */}
                      {blog.coverImage && (
                        <Image
                          src={blog.coverImage}
                          alt={blog.title ?? ""}
                          title={blog.title ?? ""}
                          fill
                          quality={75}
                          sizes="(max-width: 640px) 85vw, (max-width: 1024px) 45vw, 31vw"
                          loading="lazy"
                          className="
                            object-cover
                            transition-transform
                            duration-700
                            group-hover:scale-105
                          "
                        />
                      )}

                      {/* Date */}
                      <div
                        className="
                          absolute
                          left-4
                          top-4
                          rounded-md
                          border
                          border-gold
                          bg-ivory
                          px-4
                          py-2
                          text-center
                          shadow
                        "
                      >
                        <p className="font-serif text-xl text-espresso">
                          {blog.publishedAt
                            ? new Date(blog.publishedAt)
                                .getDate()
                                .toString()
                                .padStart(2, "0")
                            : ""}
                        </p>

                        <span className="text-xs tracking-widest text-gold-deep">
                          {blog.publishedAt
                            ? new Date(blog.publishedAt)
                                .toLocaleString("en-US", {
                                  month: "short",
                                })
                                .toUpperCase()
                            : ""}
                        </span>
                      </div>

                      {/* OVERLAY */}
                      <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent" />

                      {/* CONTENT */}
                      <div className="absolute inset-x-0 bottom-0 p-5 text-ivory">

                        <div className="flex items-center justify-between gap-4">
                          <span className="text-[10px] uppercase tracking-widest text-gold">
                            {blog.category}
                          </span>
                        </div>

                        <h3 className="mt-3 font-serif text-xl text-ivory line-clamp-2">
                          {blog.title}
                        </h3>

                        <span className="mt-3 inline-block text-xs uppercase tracking-widest text-gold">
                          Read More
                        </span>

                      </div>
                    </Link>
                  </div>
                ))}
              </div>
            </div>
          </section>
        )}

      </div>
    </section>
  );
}