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

// Specific to this tab: within the last 5 hours, shows a combined
// "1h 42m ago" style. Beyond that, falls back to the normal shared format.
function supporterTimeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  if (isNaN(diff) || diff < 0) return "just now";

  const totalMinutes = Math.floor(diff / 60000);
  const FIVE_HOURS_MIN = 5 * 60;

  if (totalMinutes < 1) return "just now";
  if (totalMinutes < FIVE_HOURS_MIN) {
    const h = Math.floor(totalMinutes / 60);
    const m = totalMinutes % 60;
    if (h === 0) return `${m}m ago`;
    return `${h}h ${m}m ago`;
  }

  return timeAgo(iso);
}

type Supporter = { name: string; amount: number; message: string | null; createdAt: string };
type Performer = { name: string; points: number };
type BadgeTier = { min: number; max: number | null; crosses: number };

// Renders 1-N repeated badge icons based on which admin-defined amount range
// the gift falls into (e.g. $1-10 -> 1 cross, $10-100 -> 2, $100+ -> 3) —
// not extra fake badges, just a visual scale of the same real badge.
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 PartnersInMission() {
  const [tab, setTab] = useState<"supporters" | "performers">("supporters");
  const [supporters, setSupporters] = useState<Supporter[]>([]);
  const [performers, setPerformers] = useState<Performer[]>([]);
  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 },
  ]);

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch("/api/community-sidebar");
        const data = await res.json();
        setSupporters(data.supporters || []);
        setPerformers(data.topPerformers || []);
        if (data.marqueeSeconds) setMarqueeSeconds(data.marqueeSeconds);
        if (data.supporterBadgeSize) setBadgeSize(data.supporterBadgeSize);
        if (data.badgeTiers) {
          try {
            setBadgeTiers(JSON.parse(data.badgeTiers));
          } catch {}
        }
      } catch {}
    }
    load();
    const interval = setInterval(load, 20000); // refresh every 20s — real data, not fabricated
    return () => clearInterval(interval);
  }, []);

  return (
    <div className="card p-4 min-w-0 w-full max-w-full overflow-hidden">
      <h3 className="font-bold mb-1">Partners in Mission</h3>
      <p className="text-xs text-neutral-500 mb-4">Generous hearts who supported us. Thank you for your support.</p>

      <div className="flex gap-2 mb-4 min-w-0">
        <button
          onClick={() => setTab("supporters")}
          className={`flex-1 min-w-0 text-xs font-semibold py-2 px-2 rounded-full transition-colors whitespace-nowrap overflow-hidden text-ellipsis ${
            tab === "supporters" ? "bg-red-600 text-white" : "bg-neutral-800 text-neutral-400"
          }`}
        >
          Supported Users
        </button>
        <button
          onClick={() => setTab("performers")}
          className={`flex-1 min-w-0 text-xs font-semibold py-2 px-2 rounded-full transition-colors whitespace-nowrap overflow-hidden text-ellipsis ${
            tab === "performers" ? "bg-red-600 text-white" : "bg-neutral-800 text-neutral-400"
          }`}
        >
          Top Performers
        </button>
      </div>

      {/* Auto-scrolling list of real data (supporters or top point earners) */}
      <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` }}>
          {tab === "supporters" ? (
            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">{supporterTimeAgo(s.createdAt)}</span>
                </div>
              ))
            )
          ) : performers.length === 0 ? (
            <p className="text-neutral-500 text-xs text-center py-4">No points earned yet.</p>
          ) : (
            [...performers, ...performers].map((p, i) => (
              <div key={i} className="flex items-center justify-between gap-2 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">{p.name}</span>
                  <CrossBadge size={badgeSize} />
                </div>
                <span className="text-amber-400 text-xs font-semibold shrink-0">{p.points} pts</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>
    </div>
  );
}
