"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import CrossBadge from "@/components/CrossBadge";
import { timeAgo } from "@/lib/timeAgo";

type Supporter = { name: string; amount: number; message: string | null; createdAt: string };
type RecentPost = { slug: string; title: string; featuredImageUrl: string | null; publishedAt: string | null };
type Category = { id: string; name: string; slug: string; postCount: number };
type BadgeTier = { min: number; max: number | null; crosses: number };

function RepeatedBadges({ amount, size, tiers }: { amount: number; size: number; tiers: BadgeTier[] }) {
  const matched = tiers.find((t) => amount >= t.min && (t.max === null || amount < t.max));
  const count = matched ? matched.crosses : 1;
  return (
    <span className="inline-flex items-center gap-0.5">
      {Array.from({ length: count }).map((_, i) => <CrossBadge key={i} size={size} />)}
    </span>
  );
}

export default function BlogSidebar() {
  const [tab, setTab] = useState<"supporters" | "categories">("supporters");
  const [supporters, setSupporters] = useState<Supporter[]>([]);
  const [marqueeSeconds, setMarqueeSeconds] = useState(25);
  const [badgeSize, setBadgeSize] = useState(13);
  const [badgeTiers, setBadgeTiers] = useState<BadgeTier[]>([
    { min: 1, max: 10, crosses: 1 },
    { min: 10, max: 100, crosses: 2 },
    { min: 100, max: null, crosses: 3 },
  ]);
  const [recentPosts, setRecentPosts] = useState<RecentPost[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);

  useEffect(() => {
    fetch("/api/community-sidebar")
      .then((r) => r.json())
      .then((data) => {
        setSupporters(data.supporters || []);
        if (data.marqueeSeconds) setMarqueeSeconds(data.marqueeSeconds);
        if (data.supporterBadgeSize) setBadgeSize(data.supporterBadgeSize);
        if (data.badgeTiers) {
          try { setBadgeTiers(JSON.parse(data.badgeTiers)); } catch {}
        }
      })
      .catch(() => {});

    fetch("/api/blog/sidebar")
      .then((r) => r.json())
      .then((data) => {
        setRecentPosts(data.recentPosts || []);
        setCategories(data.categories || []);
      })
      .catch(() => {});
  }, []);

  return (
    <div className="card p-4 min-w-0 w-full max-w-full overflow-hidden">
      <div className="flex gap-1.5 mb-4 min-w-0">
        {([
          ["supporters", "Supporters"],
          ["categories", "Categories"],
        ] as const).map(([key, label]) => (
          <button
            key={key}
            onClick={() => setTab(key)}
            className={`flex-1 min-w-0 text-xs font-semibold py-2 px-1.5 rounded-full transition-colors whitespace-nowrap overflow-hidden text-ellipsis ${
              tab === key ? "bg-red-600 text-white" : "bg-neutral-800 text-neutral-400"
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {tab === "supporters" && (
        <>
          <div className="max-h-80 overflow-hidden relative min-w-0 w-full">
            <div className="space-y-3 min-w-0" style={{ animation: `scroll-up ${marqueeSeconds}s linear infinite` }}>
              {supporters.length === 0 ? (
                <p className="text-neutral-500 text-xs text-center py-4">No supporters yet — be the first!</p>
              ) : (
                [...supporters, ...supporters].map((s, i) => (
                  <div key={i} className="text-sm border-b border-neutral-800 pb-2 last:border-0 min-w-0">
                    <div className="flex items-center gap-1.5 min-w-0">
                      <span className="font-semibold truncate">{s.name}</span>
                      <RepeatedBadges amount={s.amount} size={badgeSize} tiers={badgeTiers} />
                    </div>
                    {s.message && <p className="text-xs text-neutral-400 mt-0.5 line-clamp-2">"{s.message}"</p>}
                    <span className="text-xs text-neutral-500">{timeAgo(s.createdAt)}</span>
                  </div>
                ))
              )}
            </div>
          </div>
          <Link href="/tips" className="btn-primary flex items-center justify-center text-center mt-4 py-3 px-3 text-sm leading-snug">
            Support Creators
          </Link>
        </>
      )}

      {tab === "categories" && (
        <div className="flex flex-wrap gap-2">
          {categories.length === 0 ? (
            <p className="text-neutral-500 text-xs text-center py-4 w-full">No categories yet.</p>
          ) : (
            categories.map((c) => (
              <Link
                key={c.id}
                href={`/blog?category=${c.slug}`}
                className="px-3 py-1.5 rounded-full text-xs font-medium bg-neutral-800 text-neutral-300 hover:bg-red-600 hover:text-white transition-colors"
              >
                {c.name} <span className="opacity-60">({c.postCount})</span>
              </Link>
            ))
          )}
        </div>
      )}
    </div>
  );
}
