"use client";

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

const STATIC_TRENDING = [
  {
    rank: 1,
    img: "photo-1577563908411-5077b6dc7624",
    title:
      "Maharashtra reshuffle: a quiet promotion tells you more than three loud ones",
    time: "2h · 412K reads",
    slug: "maharashtra-reshuffle-quiet-promotion",
  },
  {
    rank: 2,
    img: "photo-1611974789855-9c2a0a7236a3",
    title: "Rupee at six-month high: is RBI ready to let it run past 82?",
    time: "3h · 318K reads",
    slug: "rupee-six-month-high-rbi",
  },
  {
    rank: 3,
    img: "photo-1626814026160-2237a95fc5a0",
    title: "'Bombay Velvet 2' first reviews are in — and they aren't kind",
    time: "4h · 281K reads",
    slug: "bombay-velvet-2-reviews",
  },
  {
    rank: 4,
    img: "photo-1587474260584-136574528ed5",
    title: "Why Delhi's air quality plan needs a regional rewrite — now",
    time: "5h · 244K reads",
    slug: "delhi-air-quality-plan-regional",
  },
  {
    rank: 5,
    img: "photo-1531415074968-036ba1b575da",
    title:
      "Suryakumar paradox: best T20 batter in the world, still no Test cap",
    time: "5h · 226K reads",
    slug: "suryakumar-paradox-t20-test",
  },
  {
    rank: 6,
    img: "photo-1567157577867-05ccb1388e66",
    title:
      "The quiet boom: how Tier-2 cities became India's new startup capitals",
    time: "6h · 198K reads",
    slug: "tier-2-cities-startup-capitals",
  },
  {
    rank: 7,
    img: "photo-1518770660439-4636190af475",
    title: "How India's semiconductor mission is reshaping Gujarat",
    time: "6h · 167K reads",
    slug: "india-semiconductor-mission-gujarat",
  },
  {
    rank: 8,
    img: "photo-1517976487492-5750f3195933",
    title: "Inside ISRO's new launch complex at Sriharikota",
    time: "7h · 142K reads",
    slug: "isro-new-launch-complex-sriharikota",
  },
];

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 hrs = Math.floor(diff / 3600000);
  if (hrs < 24) return `${hrs}h`;
  return `${Math.floor(hrs / 24)}d`;
}

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

export default function TrendingSection({ section }: TrendingSectionProps) {
  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>
            {section.sub_title && (
              <span className="count">{section.sub_title}</span>
            )}
          </div>
          <Link href={`/section/${section.id}`} className="sec-link">
            See All
            <svg className="icn-14" viewBox="0 0 24 24">
              <path d="M5 12h14M13 6l6 6-6 6" />
            </svg>
          </Link>
        </div>

        <div className="trend-scroll">
          {hasApi
            ? apiArticles.map((a, i) => {
                const imgUrl = isValidImg(a.web_image)
                  ? a.web_image
                  : isValidImg(a.portrait_img)
                    ? a.portrait_img
                    : null;
                return (
                  <Link
                    key={a.id}
                    href={lhref(`/detail/${a.id}`)}
                    className="trend-card"
                  >
                    <div className="image">
                      {imgUrl ? (
                        <Image
                          src={imgUrl}
                          alt=""
                          width={240}
                          height={132}
                          unoptimized
                        />
                      ) : (
                        <div
                          style={{
                            width: 240,
                            height: 132,
                            background: "#e5e7eb",
                            borderRadius: 6,
                          }}
                        />
                      )}
                      <div className="trend-rank">{i + 1}</div>
                    </div>
                    <div className="body">
                      <h4>{a.title}</h4>
                      <span className="time">
                        <svg className="icn-12" viewBox="0 0 24 24">
                          <circle cx="12" cy="12" r="9" />
                          <path d="M12 7v5l3 2" />
                        </svg>
                        {fmtRelTime(a.created_at)} · {fmtViews(a.total_view)}{" "}
                        reads
                      </span>
                    </div>
                  </Link>
                );
              })
            : STATIC_TRENDING.map(({ rank, img, title, time, slug }) => (
                <Link
                  key={rank}
                  href={lhref(`/detail/${slug}`)}
                  className="trend-card"
                >
                  <div className="image">
                    <Image
                      src={`https://images.unsplash.com/${img}?w=300&q=75`}
                      alt=""
                      width={240}
                      height={132}
                    />
                    <div className="trend-rank">{rank}</div>
                  </div>
                  <div className="body">
                    <h4>{title}</h4>
                    <span className="time">
                      <svg className="icn-12" viewBox="0 0 24 24">
                        <circle cx="12" cy="12" r="9" />
                        <path d="M12 7v5l3 2" />
                      </svg>
                      {time}
                    </span>
                  </div>
                </Link>
              ))}
        </div>
      </div>
    </section>
  );
}
