"use client";

import Link from "@/components/Link";
import { useSearchParams } from "next/navigation";
import { BlogCard, BlogCta, blogDate } from "@/components/BlogParts";
import Breadcrumbs, { type Crumb } from "@/components/Breadcrumbs";
import Icon from "@/components/Icon";
import SiteEffects from "@/components/SiteEffects";
import { blogAuthor, blogPosts } from "@/content/blog-posts";

/**
 * The blog list with its ?q= search applied. It reads the URL in the browser, so the server sends /blog once, as
 * the full list (the page's Suspense fallback), and search results render client-side. Reading searchParams on the
 * server instead streamed a second copy of the page into the HTML.
 */
export default function BlogIndex({ crumbs }: { crumbs: Crumb[] }) {
  const q = (useSearchParams().get("q") ?? "").trim().slice(0, 80);
  return <BlogView q={q} crumbs={crumbs} />;
}

export function BlogView({ q = "", crumbs }: { q?: string; crumbs: Crumb[] }) {
  const sorted = [...blogPosts].sort((a, b) => b.date.localeCompare(a.date));
  const needle = q.toLowerCase();
  const posts = q
    ? sorted.filter((p) => `${p.title} ${p.excerpt} ${p.body.replace(/<[^>]+>/g, " ")}`.toLowerCase().includes(needle))
    : sorted;
  const featured = !q ? posts[0] : undefined;
  const list = featured ? posts.slice(1) : posts;

  return (
    <>
      <section className="an-hero">
        <div className="an-wrap">
          <div className="an-hero__copy an-blog-hero">
            <Breadcrumbs items={crumbs} />
            <span className="an-eyebrow">Blog</span>
            <h1 className="an-h1">Insights to Help Advertisers <span className="an-ai-text">Reach New Customers</span></h1>
            <p className="an-lede">News, event recaps and practical advice on search, AI discovery and multi-channel advertising.</p>
            <form className="an-blog-search" action="/blog" method="get" role="search">
              <label className="an-sr" htmlFor="blog-q">Search articles</label>
              <span className="an-blog-search__ico"><Icon name="search" size={18} /></span>
              <input key={q} id="blog-q" type="search" name="q" defaultValue={q} placeholder="Search articles" autoComplete="off" />
              <button type="submit" className="an-btn an-btn--primary an-btn--sm">Search</button>
            </form>
          </div>
        </div>
      </section>

      {featured ? (
        <section className="an-section an-blog-featsec">
          <div className="an-wrap">
            <Link className="an-blog-feat an-reveal" href={`/blog/${featured.slug}`}>
              <span className="an-blog-feat__img"><img src={featured.image} alt={featured.imageAlt} width={1600} height={1000} fetchPriority="high" /></span>
              <span className="an-blog-feat__body">
                <span className="an-blog-feat__badge">Featured</span>
                <h2>{featured.title}</h2>
                <p>{featured.excerpt}</p>
                <span className="an-blog-byline"><span>{blogAuthor}</span><span><time dateTime={featured.date}>{blogDate(featured)}</time></span><span>{featured.minutes} min read</span></span>
                <span className="an-btn an-btn--primary an-btn--sm">Read article <Icon name="arrow" size={16} /></span>
              </span>
            </Link>
          </div>
        </section>
      ) : null}

      <section className="an-section an-blog-listsec">
        <div className="an-wrap">
          <div className="an-blog-listhead an-reveal">
            <div>
              <h2 className="an-h2">{q ? `Results for “${q}”` : "Latest articles"}</h2>
              <p>{list.length} article{list.length === 1 ? "" : "s"}</p>
            </div>
            {q ? <Link className="an-link" href="/blog">Clear search</Link> : null}
          </div>
          {list.length ? (
            <div className="an-blog-grid an-reveal">{list.map((p) => <BlogCard key={p.slug} post={p} />)}</div>
          ) : (
            <div className="an-blog-empty an-reveal">
              <Icon name="search" size={22} />
              <p>No articles match your search. Try a different word, or <Link href="/blog">browse all articles</Link>.</p>
            </div>
          )}
        </div>
      </section>
      <BlogCta />
      <SiteEffects />
    </>
  );
}
