"use client";

import { useEffect, useState } from "react";
import { ArrowRight, Radio, ShieldCheck, UsersRound } from "lucide-react";
import type { DiscordCommunityStatus, DiscordStreamerStatus } from "../lib/discord";

const fallbackCommunity: DiscordCommunityStatus = {
  ok: false,
  invite: "https://discord.com/invite/pTNwsZrvym",
};

const fallbackStreamers: DiscordStreamerStatus = {
  ok: false,
  configured: false,
  count: 0,
  streamers: [],
};

export default function DiscordPulse() {
  const [community, setCommunity] = useState<DiscordCommunityStatus>(fallbackCommunity);
  const [streamers, setStreamers] = useState<DiscordStreamerStatus>(fallbackStreamers);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let alive = true;

    Promise.all([
      fetch("/api/discord", { cache: "no-store" }).then((res) => res.json()),
      fetch("/api/discord/streamers", { cache: "no-store" }).then((res) => res.json()),
    ])
      .then(([communityData, streamerData]) => {
        if (!alive) return;
        setCommunity(communityData);
        setStreamers(streamerData);
      })
      .catch(() => undefined)
      .finally(() => alive && setLoading(false));

    return () => {
      alive = false;
    };
  }, []);

  const members = community.members ?? null;
  const online = community.online ?? null;

  return (
    <div className="discord-pulse" aria-live="polite">
      <div className="discord-pulse-main">
        <div className="discord-pulse-icon"><UsersRound size={24}/></div>
        <div>
          <small>LIVE AUS UNSEREM DISCORD</small>
          <strong>{community.name || "BexoGames Community"}</strong>
          <span>{loading ? "Community-Daten werden geladen …" : community.ok ? "Direkt mit unserem Discord verbunden" : "Discord erreichbar über unseren Invite"}</span>
        </div>
      </div>

      <div className="discord-stat">
        <Radio size={16}/>
        <span><b>{online ?? "–"}</b><small>gerade online</small></span>
      </div>
      <div className="discord-stat">
        <UsersRound size={16}/>
        <span><b>{members ?? "–"}</b><small>Mitglieder</small></span>
      </div>
      <div className="discord-stat">
        <ShieldCheck size={16}/>
        <span><b>{streamers.configured ? streamers.count : "bereit"}</b><small>{streamers.configured ? "Streamer-Rolle" : "Rollenprüfung"}</small></span>
      </div>

      <a className="discord-pulse-join" href={community.invite || fallbackCommunity.invite} target="_blank" rel="noopener noreferrer">
        Beitreten <ArrowRight size={16}/>
      </a>
    </div>
  );
}
