"use client";
import React, { useEffect, useState } from "react";

type Event = { title: string; date: string; location?: string; signupUrl?: string };

export function CalendarView() {
  const [events, setEvents] = useState<Event[]>([]);

  useEffect(() => {
    (async () => {
      try {
        const res = await fetch("/api/content?path=pt/competicoes/future.json");
        const json = await res.json();
        setEvents(json.events ?? []);
      } catch {}
    })();
  }, []);

  // Simple month grid from provided future events
  const byMonth = events.reduce<Record<string, Event[]>>((acc, e) => {
    const month = new Date(e.date).toLocaleString("pt-PT", { month: "long", year: "numeric" });
    acc[month] ??= [];
    acc[month].push(e);
    return acc;
  }, {});

  return (
    <section aria-labelledby="calendar-title">
      <h2 id="calendar-title" className="text-xl font-semibold">Calendário</h2>
      <div className="grid gap-4 md:grid-cols-2 mt-2">
        {Object.entries(byMonth).map(([m, items]) => (
          <div key={m} className="border p-3">
            <h3 className="font-bold">{m}</h3>
            <ul className="mt-2 space-y-1">
              {items.map((e, idx) => (
                <li key={idx}>
                  <strong>{e.title}</strong> — {new Date(e.date).toLocaleDateString("pt-PT")}
                  {e.location && <span className="ml-2">({e.location})</span>}
                  {e.signupUrl && (
                    <a className="ml-2 underline" href={e.signupUrl} target="_blank" rel="noopener noreferrer">Inscrição</a>
                  )}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </section>
  );
}
