"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Flame, TrendingUp, Circle } from "lucide-react";
import { Avatar } from "./Avatar";
import { sfx } from "@/lib/sfx";
import type { User } from "@/lib/types";
import { useTrending } from "@/lib/use-trending";

// A colour per row, so they read as distinct cards. The tags
// themselves are counted from the site's own posts.
const ACCENTS = [
  { accent: "#ff3c5f", tint: "linear-gradient(90deg,#ff3c5f,#ff8a3c)" },
  { accent: "#7b2ff7", tint: "linear-gradient(90deg,#7b2ff7,#d43cae)" },
  { accent: "#0ea5e9", tint: "linear-gradient(90deg,#0ea5e9,#22d3ee)" },
  { accent: "#f59e0b", tint: "linear-gradient(90deg,#f59e0b,#fbbf24)" },
  { accent: "#2fd573", tint: "linear-gradient(90deg,#2fd573,#4ade80)" },
];

/** Five bars shaped by the count, so the sparkline means something. */
const barsFor = (count: number) =>
  [0.4, 0.7, 0.5, 0.9, 1].map((f) => Math.round(f * Math.min(1, count / 3) * 100));

export function TrendingTopics() {
  const router = useRouter();
  const topics = useTrending(5);

  // Nothing to be trending about yet. An empty card is worse than none.
  if (topics.length === 0) return null;

  return (
    <div className="rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-[#0c0c0c] p-4">
      <h3 className="flex items-center gap-1.5 font-semibold text-[15px] mb-3">
        <Flame size={15} className="text-orange-500" /> Trending Topics
      </h3>
      <div className="flex flex-col gap-1.5">
        {topics.map((t, i) => (
          <button
            key={t.tag}
            onClick={() => router.push(`/search?q=${encodeURIComponent(t.tag)}`)}
            className="tr-row"
            style={{
              ["--tint" as string]: ACCENTS[i % ACCENTS.length].tint,
              ["--accent" as string]: ACCENTS[i % ACCENTS.length].accent,
            }}
          >
            <span className="tr-rank">{i + 1}</span>
            <span className="tr-body">
              <span className="tr-tag">#{t.tag}</span>
              <span className="tr-count">
                {t.count} post{t.count === 1 ? "" : "s"}
              </span>
            </span>
            <span className="tr-spark">
              {barsFor(t.count).map((h, bi) => (
                <i
                  key={bi}
                  style={{ height: `${h}%`, animationDelay: `${bi * 0.13}s` }}
                />
              ))}
            </span>
            {t.count >= 3 ? (
              <Flame size={13} className="tr-flame text-orange-500" />
            ) : (
              <TrendingUp size={13} className="relative z-[2] text-neutral-300 shrink-0" />
            )}
          </button>
        ))}
      </div>
    </div>
  );
}

/**
 * Presence isn't tracked server-side, so "online" is derived from a stable
 * hash of the user id — consistent between renders rather than flickering
 * randomly, and easy to swap for real presence later.
 */
function isOnline(id: string) {
  let h = 0;
  for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) & 0xffff;
  return h % 10 < 6;
}

export function OnlineFriends() {
  const [people, setPeople] = useState<User[]>([]);

  useEffect(() => {
    let stop = false;
    async function load(attempt = 0) {
      if (stop) return;
      try {
        const r = await fetch("/api/users/suggested");
        const d = r.ok ? await r.json() : [];
        if (Array.isArray(d) && d.length > 0) {
          setPeople(d);
          return;
        }
      } catch {
        /* retry */
      }
      if (attempt < 6) setTimeout(() => load(attempt + 1), 900);
    }
    load();
    return () => {
      stop = false;
    };
  }, []);

  const online = people.filter((p) => isOnline(p.id)).slice(0, 9);
  if (online.length === 0) return null;

  return (
    <div className="rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-[#0c0c0c] p-4">
      <h3 className="flex items-center gap-1.5 font-semibold text-[15px] mb-3">
        <Circle size={9} className="fill-emerald-500 text-emerald-500" />
        Online Friends
        <span className="text-neutral-400 font-normal text-xs">({online.length})</span>
      </h3>
      <div className="flex flex-wrap gap-2.5">
        {online.map((u) => (
          <Link
            key={u.id}
            href={`/messages?to=${u.username}`}
            onClick={() => sfx.click()}
            title={`Message ${u.name}`}
            className="relative group"
          >
            <Avatar user={u} size={40} />
            <span className="mg-dot" />
            <span className="absolute -bottom-1 left-1/2 -translate-x-1/2 opacity-0 group-hover:opacity-100 transition-opacity text-[9px] font-bold bg-black text-white px-1.5 py-0.5 rounded-full whitespace-nowrap pointer-events-none">
              {u.username}
            </span>
          </Link>
        ))}
      </div>
    </div>
  );
}
