"use client";

import Image from "next/image";
import Link from "next/link";
import BookmarkButton from "./BookmarkButton";
import type { Section, SectionArticle } from "@/types/api/section.types";

const STATIC_ARTICLES = [
  {
    img: "photo-1604868189265-219ba0ed7f05",
    cat: "pol" as const,
    catLabel: "Politics",
    title:
      "Lok Sabha clears Data Privacy Bill amid opposition walkout — what changes for you",
    time: "54m",
    views: "210K",
    slug: "lok-sabha-data-privacy-bill",
  },
  {
    img: "photo-1438449805896-28a666819a20",
    cat: "health" as const,
    catLabel: "Climate",
    title:
      "Cyclone Remal: ground report from the Bengal coast as floodwaters recede",
    time: "1h",
    views: "124K",
    slug: "cyclone-remal-bengal-coast",
  },
  {
    img: "photo-1518770660439-4636190af475",
    cat: "tech" as const,
    catLabel: "Tech",
    title:
      "How India's semiconductor mission is reshaping Gujarat's industrial belt",
    time: "1h",
    views: "56K",
    slug: "india-semiconductor-mission-gujarat",
  },
  {
    img: "photo-1611974789855-9c2a0a7236a3",
    cat: "biz" as const,
    catLabel: "Business",
    title:
      "Reliance Q4: retail saves the quarter as Jio ARPU dips for the first time",
    time: "2h",
    views: "147K",
    slug: "reliance-q4-results",
  },
  {
    img: "photo-1577563908411-5077b6dc7624",
    cat: "world" as const,
    catLabel: "World",
    title:
      "India–EU FTA talks resume in Brussels; auto tariffs back on the table",
    time: "2h",
    views: "89K",
    slug: "india-eu-fta-talks-brussels",
  },
  {
    img: "photo-1531415074968-036ba1b575da",
    cat: "sport" as const,
    catLabel: "Sport",
    title:
      "The Suryakumar paradox: best T20 batter in the world, still no Test cap",
    time: "3h",
    views: "226K",
    slug: "suryakumar-paradox-t20-test",
  },
];

function isValidImg(url: string) {
  return !!url && !url.includes("no_img");
}
function fmtViews(n: number) {
  if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
  if (n >= 1000) return `${Math.round(n / 1000)}K`;
  return String(n);
}
function fmtRelTime(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  const hrs = Math.floor(mins / 60);
  if (mins < 60) return `${mins}m`;
  if (hrs < 24) return `${hrs}h`;
  return `${Math.floor(hrs / 24)}d`;
}

interface LatestNewsSectionProps {
  section: Section;
  locale: string;
}

export default function LatestNewsSection({ section }: LatestNewsSectionProps) {
  const lhref = (path: string) => `${path}`;
  const apiArticles = (section.data ?? []) as SectionArticle[];
  const hasApi = apiArticles.length > 0;

  return (
    <section className="sec">
      <div className="wrap">
        <div className="sec-head">
          <div className="sec-title">
            <h2>{section.title}</h2>
            <span className="count">
              {section.sub_title
                ? section.sub_title
                : hasApi
                  ? `${apiArticles.length} stories`
                  : "Latest stories"}
            </span>
          </div>
          <Link href={`/section/${section.id}`} className="sec-link">
            View All
            <svg className="icn-14" viewBox="0 0 24 24">
              <path d="M5 12h14M13 6l6 6-6 6" />
            </svg>
          </Link>
        </div>

        {/* Vertical list — one article per row, image left + content right */}
        <div style={{ display: "flex", flexDirection: "column", gap: "0" }}>
          {(hasApi ? apiArticles.slice(0, 8) : STATIC_ARTICLES).map((a, i) => {
            const isApiItem = hasApi;
            const img = isApiItem
              ? isValidImg((a as SectionArticle).web_image)
                ? (a as SectionArticle).web_image
                : isValidImg((a as SectionArticle).landscape_img)
                  ? (a as SectionArticle).landscape_img
                  : null
              : `https://images.unsplash.com/${(a as (typeof STATIC_ARTICLES)[number]).img}?w=600&q=80`;
            const title = isApiItem
              ? (a as SectionArticle).title
              : (a as (typeof STATIC_ARTICLES)[number]).title;
            const catLabel = isApiItem
              ? (a as SectionArticle).category
              : (a as (typeof STATIC_ARTICLES)[number]).catLabel;
            const href = isApiItem
              ? lhref(`/detail/${(a as SectionArticle).id}`)
              : lhref(
                  `/detail/${(a as (typeof STATIC_ARTICLES)[number]).slug}`,
                );
            const timeMeta = isApiItem
              ? fmtRelTime((a as SectionArticle).created_at)
              : (a as (typeof STATIC_ARTICLES)[number]).time;
            const viewsMeta = isApiItem
              ? fmtViews((a as SectionArticle).total_view)
              : (a as (typeof STATIC_ARTICLES)[number]).views;
            const isLast =
              i ===
              (hasApi
                ? Math.min(apiArticles.length, 8)
                : STATIC_ARTICLES.length) -
                1;

            return (
              <Link
                key={
                  isApiItem
                    ? (a as SectionArticle).id
                    : (a as (typeof STATIC_ARTICLES)[number]).img
                }
                href={href}
                style={{
                  display: "flex",
                  gap: "1rem",
                  alignItems: "flex-start",
                  padding: "1rem 0",
                  borderBottom: isLast ? "none" : "1px solid var(--border)",
                  textDecoration: "none",
                  color: "inherit",
                }}
              >
                {/* Thumbnail */}
                <div
                  style={{
                    flexShrink: 0,
                    width: 120,
                    height: 80,
                    borderRadius: 8,
                    overflow: "hidden",
                    position: "relative",
                    background: "#e5e7eb",
                  }}
                >
                  {img ? (
                    <Image
                      src={img}
                      alt=""
                      fill
                      style={{ objectFit: "cover" }}
                      unoptimized={isApiItem}
                    />
                  ) : null}
                </div>

                {/* Content */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <span
                    style={{
                      display: "inline-block",
                      fontSize: 10,
                      fontWeight: 700,
                      letterSpacing: "0.08em",
                      textTransform: "uppercase",
                      color: "var(--brand)",
                      marginBottom: 5,
                    }}
                  >
                    {catLabel}
                  </span>
                  <h3
                    style={{
                      fontSize: "0.9375rem",
                      fontWeight: 600,
                      lineHeight: 1.4,
                      margin: "0 0 8px",
                      WebkitLineClamp: 2,
                      display: "-webkit-box",
                      WebkitBoxOrient: "vertical",
                      overflow: "hidden",
                      color: "var(--ink)",
                    }}
                  >
                    {title}
                  </h3>
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: "0.75rem",
                      fontSize: "0.75rem",
                      fontFamily: "var(--mono)",
                      color: "var(--text-tertiary)",
                    }}
                  >
                    <span
                      style={{ display: "flex", alignItems: "center", gap: 4 }}
                    >
                      <svg
                        className="icn-12"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                      >
                        <circle cx="12" cy="12" r="9" />
                        <path d="M12 7v5l3 2" />
                      </svg>
                      {timeMeta}
                    </span>
                    <span
                      style={{ display: "flex", alignItems: "center", gap: 4 }}
                    >
                      <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>
                      {viewsMeta}
                    </span>
                    <BookmarkButton />
                  </div>
                </div>
              </Link>
            );
          })}
        </div>

        {/* <div className="live-banner">
          <div className="live-icon">
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              width="26"
              height="26"
            >
              <rect x="2" y="5" width="20" height="14" rx="2" />
              <path d="M8 21h8M12 19v2" />
              <polygon
                points="10 9 16 12 10 15"
                fill="currentColor"
                stroke="none"
              />
            </svg>
          </div>
          <div className="live-text">
            <div className="tag">
              <span className="dot" />
              LIVE NOW
            </div>
            <h3>Parliament Live · Data Privacy Bill — final vote</h3>
            <p>With Ravish Kumar &amp; Karthik Iyer · 24,318 watching now</p>
          </div>
          <div className="live-mini-bars">
            <b />
            <b />
            <b />
            <b />
            <b />
          </div>
          <Link href={lhref("/channel/ndtv-24x7")} className="btn-watch">
            <span className="pulse-sm" />
            Watch Live
            <svg
              className="icn-14"
              viewBox="0 0 24 24"
              fill="currentColor"
              stroke="none"
            >
              <polygon points="6 4 20 12 6 20" />
            </svg>
          </Link>
        </div> */}
      </div>
    </section>
  );
}
