"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import type { BlogPost } from "@/lib/blog";
import { BlogCard } from "./blog-card";
import { Search } from "./icons";

const PAGE_SIZE = 6;

export function BlogListing({
  posts,
  tags,
  activeTag,
}: {
  posts: BlogPost[];
  tags: string[];
  /** The pill matching the current route — /resources = "All", /resources/[category] = that category's label. */
  activeTag: string;
}) {
  const [query, setQuery] = useState("");
  const [visible, setVisible] = useState(PAGE_SIZE);

  // Map each tag label to the route it should navigate to — derived from the
  // posts themselves (post.category is the slug, post.tag is the label), so
  // clicking a pill is real navigation (URL changes, back/forward works)
  // instead of just flipping client-side state under an unchanged URL.
  const routeForTag = useMemo(() => {
    const map: Record<string, string> = { All: "/resources" };
    for (const p of posts) {
      if (!map[p.tag]) map[p.tag] = `/resources/${p.category}`;
    }
    return map;
  }, [posts]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return posts.filter((p) => {
      const matchesTag = activeTag === "All" || !activeTag || p.tag === activeTag;
      const matchesQuery =
        !q ||
        p.title.toLowerCase().includes(q) ||
        p.excerpt.toLowerCase().includes(q) ||
        p.tag.toLowerCase().includes(q);
      return matchesTag && matchesQuery;
    });
  }, [posts, query, activeTag]);

  const shown = filtered.slice(0, visible);

  return (
    <div>
      {/* Search */}
      <div className="mx-auto mb-8 flex max-w-xl items-center gap-3 rounded-pill border border-line bg-paper px-5 py-3 shadow-soft focus-within:border-leaf/60">
        <Search className="h-5 w-5 shrink-0 text-muted" />
        <input
          type="search"
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            setVisible(PAGE_SIZE);
          }}
          placeholder="Search articles, topics, or keywords…"
          aria-label="Search articles"
          className="min-w-0 flex-1 bg-transparent text-sm text-ink outline-none placeholder:text-muted"
        />
      </div>

      {/* Filter pills — real links, so the URL always matches what's shown
          and browser back/forward navigate between categories correctly. */}
      <div className="mb-10 flex flex-wrap justify-center gap-3">
        {tags.map((pill) => {
          const active = pill === activeTag;
          return (
            <Link
              key={pill}
              href={routeForTag[pill] || "/resources"}
              onClick={() => setVisible(PAGE_SIZE)}
              aria-current={active ? "page" : undefined}
              className={`btn-pill px-4 py-2 text-sm ${
                active
                  ? "bg-gradient-to-r from-leaf-deep via-teal to-sky text-white shadow-soft"
                  : "border border-line bg-paper text-ink-soft hover:border-leaf/50 hover:text-leaf-deep"
              }`}
            >
              {pill}
            </Link>
          );
        })}
      </div>

      {/* Grid */}
      {shown.length > 0 ? (
        <div className="grid gap-7 sm:grid-cols-2 lg:grid-cols-3">
          {shown.map((post) => (
            <BlogCard key={post.slug} post={post} />
          ))}
        </div>
      ) : (
        <p className="py-16 text-center text-muted">
          No articles match your search yet. Try a different keyword.
        </p>
      )}

      {/* Load more */}
      {visible < filtered.length && (
        <div className="mt-12 flex justify-center">
          <button
            onClick={() => setVisible((v) => v + PAGE_SIZE)}
            className="btn-pill bg-ink px-8 py-3.5 text-sm text-paper hover:bg-ink-soft"
          >
            Load More
          </button>
        </div>
      )}
    </div>
  );
}
