"use client";

import { useEffect, useMemo, useState } from "react";
import { Newspaper } from "lucide-react";
import { AiImage } from "@/components/AiImage";
import { useContactSettings } from "@/components/ContactProvider";
import { whatsappHref } from "@/lib/contact-api";
import { newsImageUrl, type NewsItem } from "@/lib/news-api";

type Props = {
  article: NewsItem;
  related: NewsItem[];
};

const FALLBACK_COVERS = [
  "/img/destinationBg32.webp",
  "/img/image_1863.webp",
  "/img/image_1864.webp",
  "/img/destinationBg.webp",
];

function coverSrc(item: NewsItem) {
  if (item.cover_image) return newsImageUrl(item.cover_image);
  return FALLBACK_COVERS[item.id % FALLBACK_COVERS.length];
}

type TocItem = { id: string; title: string; level: 2 | 3 };

function buildToc(html: string): { html: string; toc: TocItem[] } {
  if (!html?.trim()) return { html: "", toc: [] };

  const toc: TocItem[] = [];
  let index = 0;
  const nextHtml = html.replace(
    /<(h2|h3)(\b[^>]*)>([\s\S]*?)<\/\1>/gi,
    (_match, tag: string, attrs: string, inner: string) => {
      index += 1;
      const level = tag.toLowerCase() === "h2" ? 2 : 3;
      const idMatch = attrs.match(/\bid=["']([^"']+)["']/i);
      const id = idMatch?.[1] || `section-${index}`;
      const title = inner.replace(/<[^>]+>/g, "").trim() || `Section ${index}`;
      toc.push({ id, title, level: level as 2 | 3 });
      if (idMatch) return `<${tag}${attrs}>${inner}</${tag}>`;
      return `<${tag}${attrs} id="${id}">${inner}</${tag}>`;
    },
  );

  return { html: nextHtml, toc };
}

export function NewsDetailView({ article, related }: Props) {
  const { contact } = useContactSettings();
  const { html, toc } = useMemo(
    () => buildToc(article.content || ""),
    [article.content],
  );
  const [active, setActive] = useState(toc[0]?.id ?? "");
  const wa = whatsappHref(contact.whatsapp || contact.phone);
  const waLabel = contact.phone || "WhatsApp";

  useEffect(() => {
    if (!toc.length) return;
    setActive(toc[0].id);
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
        if (visible?.target?.id) setActive(visible.target.id);
      },
      { rootMargin: "-20% 0px -60% 0px", threshold: [0.1, 0.4, 0.7] },
    );
    toc.forEach((item) => {
      const el = document.getElementById(item.id);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [toc]);

  const scrollTo = (id: string) => {
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const published = article.published_at
    ? new Date(article.published_at).toLocaleDateString("en-GB", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      })
    : null;

  return (
    <section className="bg-[#f5f8fa] py-8 sm:py-12">
      <div className="mx-auto grid w-[min(1180px,calc(100%-2rem))] gap-8 lg:grid-cols-[minmax(0,1fr)_300px]">
        <article className="rounded-2xl border border-[var(--line)] bg-white p-5 sm:p-8 lg:p-10">
          <p className="text-xs tracking-wide text-muted">
            <a href="/" className="hover:text-accent">
              Home
            </a>
            <span className="mx-2">›</span>
            <a href="/news" className="hover:text-accent">
              News
            </a>
            <span className="mx-2">›</span>
            <span className="text-brand-deep">{article.category}</span>
          </p>

          <h1 className="mt-4 font-[family-name:var(--font-display)] text-2xl font-bold text-brand-deep sm:text-3xl lg:text-4xl">
            {article.title}
          </h1>

          <div className="mt-4 flex flex-wrap items-center gap-3 text-sm text-muted">
            <span className="inline-flex items-center gap-1.5 rounded-full bg-accent/10 px-3 py-1 text-xs font-bold text-brand-deep">
              <Newspaper className="h-3.5 w-3.5 text-accent" />
              {article.category}
            </span>
            {published ? <span>{published}</span> : null}
            <span>VNSAILS Travel Guide</span>
          </div>

          {article.excerpt ? (
            <p className="mt-6 text-sm leading-relaxed text-muted sm:text-base">
              {article.excerpt}
            </p>
          ) : null}

          <div className="mt-6 overflow-hidden rounded-2xl">
            <AiImage
              src={coverSrc(article)}
              alt={article.title}
              className="aspect-[16/9] w-full"
            />
          </div>

          {html.trim() ? (
            <div
              className="news-prose mt-8 scroll-smooth [&_h2]:scroll-mt-28 [&_h3]:scroll-mt-28"
              dangerouslySetInnerHTML={{ __html: html }}
            />
          ) : (
            <p className="mt-8 text-sm text-muted">No content yet.</p>
          )}

          <div className="mt-10 rounded-2xl bg-[linear-gradient(120deg,#17627a,#2b98ba,#4fb0d1)] p-6 text-white sm:p-8">
            <h2 className="text-xl font-bold sm:text-2xl">
              Get the best cruise tours deals with us!
            </h2>
            <p className="mt-3 max-w-2xl text-sm text-white/85 sm:text-base">
              Compare routes, cabins and seasonal offers — book Halong Bay cruises with
              local VNSAILS support.
            </p>
            <div className="mt-5 flex flex-wrap gap-3">
              <a
                href="/cruise-tours"
                className="rounded-full bg-white px-5 py-2.5 text-sm font-bold text-accent"
              >
                Browse cruises
              </a>
              <a
                href={wa}
                target="_blank"
                rel="noreferrer"
                className="rounded-full border border-white/40 px-5 py-2.5 text-sm font-bold text-white"
              >
                WhatsApp {waLabel}
              </a>
            </div>
          </div>
        </article>

        <aside className="lg:sticky lg:top-28 lg:self-start">
          {toc.length > 0 && (
            <div className="rounded-2xl border border-[var(--line)] bg-white p-5 shadow-[0_8px_24px_rgba(13,58,77,0.04)]">
              <h2 className="text-base font-bold text-brand-deep">Content summary</h2>
              <nav className="mt-4 space-y-2">
                {toc.map((item) => (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => scrollTo(item.id)}
                    className={`block w-full text-left leading-snug transition ${
                      item.level === 3 ? "ml-3 border-l border-[var(--line)] pl-3 text-xs" : "text-sm"
                    } ${
                      active === item.id
                        ? "font-semibold text-accent"
                        : "text-muted hover:text-brand-deep"
                    }`}
                  >
                    {item.title}
                  </button>
                ))}
              </nav>
            </div>
          )}

          <div
            className={`rounded-2xl border border-[var(--line)] bg-white p-5 ${
              toc.length > 0 ? "mt-4" : ""
            }`}
          >
            <h3 className="font-bold text-brand-deep">Related articles</h3>
            <div className="mt-3 space-y-3">
              {related.length === 0 ? (
                <p className="text-sm text-muted">No related articles.</p>
              ) : (
                related.map((item) => (
                  <a key={item.slug} href={`/news/${item.slug}`} className="group block">
                    <div className="overflow-hidden rounded-xl">
                      <AiImage
                        src={coverSrc(item)}
                        alt={item.title}
                        className="aspect-[16/10] w-full transition group-hover:scale-105"
                      />
                    </div>
                    <p className="mt-2 line-clamp-2 text-sm font-semibold text-brand-deep group-hover:text-accent">
                      {item.title}
                    </p>
                  </a>
                ))
              )}
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}
