"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState, useRef } from "react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchBanner,
  selectBannerItems,
  selectBannerLoaded,
  selectBannerLoading,
} from "@/store/slices/bannerSlice";
import { getStoredUser } from "@/lib/utils/persistAuth";
import CategoryChips from "./CategoryChips";
import type { BannerItem } from "@/types/api/banner.types";

function isValidUrl(u?: string) {
  return !!u && u.startsWith("http") && !u.includes("no_img");
}

// Prefer landscape_img (full URL) → portrait_img → skip
function getBannerImageUrl(item: BannerItem): string | null {
  if (isValidUrl(item.landscape_img)) return item.landscape_img;
  if (isValidUrl(item.portrait_img)) return item.portrait_img;
  return null;
}

function getItemHref(item: BannerItem): string {
  if (item.type === 3) return `/detail/${item.id}`; // Live News
  if (item.type === 4) return `/channel/${item.channel_id}`; // Show
  return `/detail/${item.id}`; // Article
}

function getTypeBadge(type: number): string {
  if (type === 3) return "LIVE";
  if (type === 4) return "SHOW";
  return "NEWS";
}

function fmtRelTime(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60_000);
  const hrs = Math.floor(mins / 60);
  if (mins < 60) return `${mins}m ago`;
  if (hrs < 24) return `${hrs}h ago`;
  return `${Math.floor(hrs / 24)}d ago`;
}

function fmtViews(n: number) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
  return String(n);
}

// Static fallback slides
const STATIC_SLIDES = [
  {
    img: "https://images.unsplash.com/photo-1529107386315-e1a2ed48a620?w=1400&q=80",
    badge: "BREAKING",
    kicker: "Politics · Exclusive",
    title:
      "Inside the 96 minutes that reshuffled Maharashtra's cabinet — and rewrote the 2027 alliance map",
    meta: "14 min ago · 412K views",
    href: "/article/maharashtra-cabinet-reshuffle",
    channel: "DTNews",
  },
  {
    img: "https://images.unsplash.com/photo-1611974789855-9c2a0a7236a3?w=1400&q=80",
    badge: "NEWS",
    kicker: "Business",
    title: "Rupee at six-month high: RBI seen letting it run past 82",
    meta: "1 hr ago · 318K views",
    href: "/article/rupee-six-month-high",
    channel: "DTNews",
  },
  {
    img: "https://images.unsplash.com/photo-1517976487492-5750f3195933?w=1400&q=80",
    badge: "SCIENCE",
    kicker: "Science · ISRO",
    title:
      "ISRO confirms Gaganyaan crewed mission window: Aug–Sep 2026 from SDSC SHAR",
    meta: "2 hr ago · 164K views",
    href: "/article/isro-gaganyaan-mission",
    channel: "DTNews",
  },
];

const SLIDE_INTERVAL = 5000;

interface HeroSectionProps {
  locale: string;
}

export default function HeroSection({ locale: _locale }: HeroSectionProps) {
  const dispatch = useAppDispatch();
  const items = useAppSelector(selectBannerItems);
  const isLoaded = useAppSelector(selectBannerLoaded);
  const isLoading = useAppSelector(selectBannerLoading);

  const [active, setActive] = useState(0);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
  // Latch: once API data arrives, never fall back to static slides mid-session
  const pinnedRef = useRef<typeof items | null>(null);
  if (items.length > 0) pinnedRef.current = items;

  // Fetch banner once on mount
  useEffect(() => {
    if (!isLoaded && !isLoading) {
      const user = getStoredUser();
      dispatch(fetchBanner({ user_id: user?.id ?? 0 }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Use pinned API data if available, otherwise fall back to static
  const slides = pinnedRef.current ?? (isLoaded ? items : null);
  const count =
    slides && slides.length > 0 ? slides.length : STATIC_SLIDES.length;

  // Auto-slide
  useEffect(() => {
    if (count <= 1) return;
    timerRef.current = setInterval(() => {
      setActive((prev) => (prev + 1) % count);
    }, SLIDE_INTERVAL);
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [count]);

  function goTo(i: number) {
    setActive(i);
    if (timerRef.current) clearInterval(timerRef.current);
    timerRef.current = setInterval(() => {
      setActive((prev) => (prev + 1) % count);
    }, SLIDE_INTERVAL);
  }

  function prev() {
    goTo((active - 1 + count) % count);
  }
  function next() {
    goTo((active + 1) % count);
  }

  return (
    <section className="hero">
      <div className="wrap">
        <div className="hero-grid">
          {/* ── Main carousel feature ── */}
          <div
            className="hero-feature"
            style={{ position: "relative", overflow: "hidden" }}
          >
            {slides
              ? slides.map((item, i) => {
                  const imgUrl = getBannerImageUrl(item);
                  const href = getItemHref(item);
                  const badge = getTypeBadge(item.type);
                  const isLive = item.type === 3;

                  return (
                    <Link
                      key={`${item.type}-${item.id}`}
                      href={`/${href.replace(/^\//, "")}`}
                      style={{
                        position: "absolute",
                        inset: 0,
                        opacity: i === active ? 1 : 0,
                        transition: "opacity 0.6s ease",
                        pointerEvents: i === active ? "auto" : "none",
                        display: "block",
                      }}
                    >
                      {imgUrl ? (
                        <Image
                          src={imgUrl}
                          alt={item.title}
                          fill
                          style={{ objectFit: "cover" }}
                          priority={i === 0}
                          unoptimized
                        />
                      ) : (
                        <div
                          style={{
                            position: "absolute",
                            inset: 0,
                            background: "#0e0e1a",
                          }}
                        />
                      )}
                      <div className="badges">
                        <div
                          className={`badge-breaking${isLive ? "" : " badge-type"}`}
                        >
                          {isLive && <span className="pulse" />}
                          {badge}
                        </div>
                        {item.updated_at && (
                          <div className="badge-soft">
                            Updated {fmtRelTime(item.updated_at)}
                          </div>
                        )}
                      </div>
                      <div className="hero-content">
                        <div className="kicker">
                          {item.type === 4
                            ? "Show"
                            : item.type === 3
                              ? "Live News"
                              : "News"}
                        </div>
                        <h1>{item.title}</h1>
                        {item.short_description && (
                          <p
                            style={{
                              fontSize: "0.9rem",
                              color: "rgba(255,255,255,0.75)",
                              lineHeight: 1.5,
                              marginBottom: "0.75rem",
                              display: "-webkit-box",
                              WebkitLineClamp: 2,
                              WebkitBoxOrient: "vertical",
                              overflow: "hidden",
                            }}
                          >
                            {item.short_description}
                          </p>
                        )}
                        <div className="hero-meta">
                          <span className="stat">
                            <svg
                              className="icn-12"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                            >
                              <circle cx="12" cy="12" r="3" />
                              <path d="M2 12s4-8 10-8 10 8 10 8-4 8-10 8S2 12 2 12z" />
                            </svg>
                            {fmtViews(item.total_view)} views
                          </span>
                          {item.total_like > 0 && (
                            <>
                              <span className="dot" />
                              <span className="stat">
                                <svg
                                  className="icn-12"
                                  viewBox="0 0 24 24"
                                  fill="none"
                                  stroke="currentColor"
                                  strokeWidth="2"
                                >
                                  <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
                                </svg>
                                {fmtViews(item.total_like)}
                              </span>
                            </>
                          )}
                        </div>
                      </div>
                    </Link>
                  );
                })
              : STATIC_SLIDES.map((s, i) => (
                  <Link
                    key={i}
                    href={s.href}
                    style={{
                      position: "absolute",
                      inset: 0,
                      opacity: i === active ? 1 : 0,
                      transition: "opacity 0.6s ease",
                      pointerEvents: i === active ? "auto" : "none",
                      display: "block",
                    }}
                  >
                    <Image
                      src={s.img}
                      alt={s.title}
                      fill
                      style={{ objectFit: "cover" }}
                      priority={i === 0}
                    />
                    <div className="badges">
                      <div className="badge-breaking">
                        <span className="pulse" />
                        {s.badge}
                      </div>
                    </div>
                    <div className="hero-content">
                      <div className="kicker">{s.kicker}</div>
                      <h1>{s.title}</h1>
                      <div className="hero-meta">
                        <div className="av">
                          {s.channel.slice(0, 2).toUpperCase()}
                        </div>
                        <b>{s.channel}</b>
                        <span className="dot" />
                        <span className="stat">{s.meta}</span>
                      </div>
                    </div>
                  </Link>
                ))}

            {/* Navigation arrows */}
            {count > 1 && (
              <>
                <button
                  onClick={prev}
                  aria-label="Previous"
                  style={{
                    position: "absolute",
                    left: 12,
                    top: "50%",
                    transform: "translateY(-50%)",
                    zIndex: 10,
                    background: "rgba(0,0,0,0.45)",
                    border: "none",
                    borderRadius: "50%",
                    width: 36,
                    height: 36,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    cursor: "pointer",
                    color: "#fff",
                  }}
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2.5"
                  >
                    <path d="M15 18l-6-6 6-6" />
                  </svg>
                </button>
                <button
                  onClick={next}
                  aria-label="Next"
                  style={{
                    position: "absolute",
                    right: 12,
                    top: "50%",
                    transform: "translateY(-50%)",
                    zIndex: 10,
                    background: "rgba(0,0,0,0.45)",
                    border: "none",
                    borderRadius: "50%",
                    width: 36,
                    height: 36,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    cursor: "pointer",
                    color: "#fff",
                  }}
                >
                  <svg
                    width="16"
                    height="16"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2.5"
                  >
                    <path d="M9 18l6-6-6-6" />
                  </svg>
                </button>
              </>
            )}

            {/* Slide indicator dots */}
            {count > 1 && (
              <div
                style={{
                  position: "absolute",
                  bottom: 16,
                  left: "50%",
                  transform: "translateX(-50%)",
                  display: "flex",
                  gap: 6,
                  zIndex: 10,
                }}
              >
                {Array.from({ length: count }).map((_, i) => (
                  <button
                    key={i}
                    onClick={() => goTo(i)}
                    aria-label={`Go to slide ${i + 1}`}
                    style={{
                      width: i === active ? 20 : 7,
                      height: 7,
                      borderRadius: 4,
                      background:
                        i === active ? "var(--brand)" : "rgba(255,255,255,0.5)",
                      border: "none",
                      cursor: "pointer",
                      padding: 0,
                      transition: "all 0.3s ease",
                    }}
                  />
                ))}
              </div>
            )}
          </div>

          {/* ── Side cards (non-active banner items) ── */}
          <div className="hero-side">
            {(slides ?? STATIC_SLIDES).map((card, i) => {
              if (i === active) return null;
              const isApiItem = slides !== null;
              const apiItem = isApiItem ? (card as BannerItem) : null;
              const staticItem = !isApiItem
                ? (card as (typeof STATIC_SLIDES)[0])
                : null;

              const imgUrl = isApiItem
                ? getBannerImageUrl(card as BannerItem)
                : (card as (typeof STATIC_SLIDES)[0]).img;
              const title = isApiItem
                ? (card as BannerItem).title
                : (card as (typeof STATIC_SLIDES)[0]).title;
              const href = isApiItem
                ? getItemHref(card as BannerItem)
                : (card as (typeof STATIC_SLIDES)[0]).href;
              const badgeLabel = isApiItem
                ? getTypeBadge((card as BannerItem).type)
                : (card as (typeof STATIC_SLIDES)[0]).badge;
              const metaLine =
                isApiItem && apiItem
                  ? `${fmtViews(apiItem.total_view)} views`
                  : (staticItem?.meta ?? "");

              return (
                <Link
                  key={
                    isApiItem
                      ? `${(card as BannerItem).type}-${(card as BannerItem).id}`
                      : i
                  }
                  href={`/${href.replace(/^\//, "")}`}
                  className="side-card"
                  onClick={() => goTo(i)}
                >
                  <div className="thumb">
                    {imgUrl ? (
                      <Image
                        src={imgUrl}
                        alt=""
                        width={130}
                        height={88}
                        unoptimized={isApiItem}
                        style={{
                          objectFit: "cover",
                          width: "100%",
                          height: "100%",
                        }}
                      />
                    ) : (
                      <div
                        style={{
                          width: 130,
                          height: 88,
                          background: "#2a2a3e",
                          borderRadius: 4,
                        }}
                      />
                    )}
                  </div>
                  <div className="body">
                    <div className="cat">{badgeLabel}</div>
                    <h3>{title}</h3>
                    <div className="meta">{metaLine}</div>
                  </div>
                </Link>
              );
            })}
          </div>
        </div>

        {/* <CategoryChips /> */}
      </div>
    </section>
  );
}
