/* global React */

function DiscordCommunity() {
  const [presence, setPresence] = React.useState({
    count: null,
    invite: 'https://discord.com/invite/EyVJBNmD',
  });

  React.useEffect(() => {
    let active = true;

    const loadPresence = async () => {
      try {
        const response = await fetch('/api/discord-widget');
        if (!response.ok) throw new Error(`Discord returned ${response.status}`);

        const data = await response.json();
        if (!active) return;

        setPresence({
          count: Number(data.presence_count) || 0,
          invite: data.instant_invite || 'https://discord.com/invite/EyVJBNmD',
        });
      } catch {
        if (active) {
          setPresence((current) => ({ ...current, count: null }));
        }
      }
    };

    loadPresence();
    const refreshTimer = window.setInterval(loadPresence, 60000);

    return () => {
      active = false;
      window.clearInterval(refreshTimer);
    };
  }, []);

  const onlineLabel = presence.count === null
    ? 'Community online'
    : `${presence.count} ${presence.count === 1 ? 'member' : 'members'} online`;

  return (
    <section className="discord-section" aria-labelledby="discord-section-title">
      <div className="discord-community-card">
        <div className="discord-card-intro">
          <div className="discord-mark" aria-hidden="true">
            <svg viewBox="0 0 24 24" fill="currentColor">
              <path d="M19.54 5.34A16.85 16.85 0 0 0 15.44 4a11.7 11.7 0 0 0-.52 1.07 15.65 15.65 0 0 0-5.82 0A11.7 11.7 0 0 0 8.56 4c-1.44.25-2.82.7-4.1 1.34C1.86 9.2 1.16 12.96 1.5 16.67a16.65 16.65 0 0 0 5.03 2.54c.4-.55.77-1.13 1.08-1.74-.6-.23-1.18-.5-1.73-.83l.43-.34c3.34 1.55 7.01 1.55 10.31 0l.44.34c-.56.33-1.14.61-1.74.84.31.6.67 1.18 1.08 1.73a16.57 16.57 0 0 0 5.03-2.54c.4-4.3-.69-8.02-1.89-11.33ZM8.5 14.4c-1 0-1.82-.92-1.82-2.05s.8-2.05 1.82-2.05c1.02 0 1.84.93 1.82 2.05 0 1.13-.8 2.05-1.82 2.05Zm7 0c-1 0-1.82-.92-1.82-2.05s.8-2.05 1.82-2.05c1.02 0 1.84.93 1.82 2.05 0 1.13-.8 2.05-1.82 2.05Z"></path>
            </svg>
          </div>
          <div>
            <span className="discord-kicker">Bubbly community</span>
            <h2 id="discord-section-title">Join us on Discord</h2>
            <p className="discord-tagline">
              Your home for Bubbly support, setup advice, bug reports, and product feedback.
            </p>
          </div>
        </div>

        <div className="discord-presence">
          <span className="discord-online-count" aria-live="polite">{onlineLabel}</span>
        </div>

        <a
          className="discord-join-button"
          href={presence.invite}
          target="_blank"
          rel="noreferrer"
        >
          Join Discord
          <span aria-hidden="true">→</span>
        </a>
      </div>
    </section>
  );
}
