"use client";

import { useEffect } from "react";
import Icon from "@/components/ui/Icon";
import type { EventOrganizer } from "@/lib/api/events";
import { useOrganizersStore } from "@/store/events";

/** Organizer cards on an event page. The event only carries id and name; bio, services and contacts come from the organizer list. */
export default function Organizers({ organizers }: { organizers: EventOrganizer[] }) {
  const store = useOrganizersStore();

  useEffect(() => {
    if (organizers.length > 0 && store.status === "idle") void store.load();
  }, [organizers.length, store.status, store.load]);

  if (organizers.length === 0) return null;

  return (
    <section className="lfd-org" aria-labelledby="org-h">
      <h2 id="org-h" className="lfd-h2">
        {organizers.length === 1 ? "Organizer" : "Organizers"}
      </h2>
      {organizers.map((o) => {
        // Falls back to the name from the event when the list is still loading or failed.
        const full = store.items.find((x) => x.id === o.id);
        return (
          <article key={o.id} className="lfd-card lfd-org-card">
            <h3>{o.name}</h3>
            {full?.bio && <p className="lf-muted">{full.bio}</p>}
            {full && full.services.length > 0 && (
              <ul className="lfd-org-services">
                {full.services.map((s) => (
                  <li key={s.id}>
                    <strong>{s.name}</strong>
                    {s.description && <span>{s.description}</span>}
                  </li>
                ))}
              </ul>
            )}
            {(full?.phone || full?.email) && (
              <div className="lfd-social">
                {full.phone && (
                  <a href={`tel:${full.phone.replace(/\s/g, "")}`}>
                    <Icon name="call" />
                    {full.phone}
                  </a>
                )}
                {full.email && (
                  <a href={`mailto:${full.email}`}>
                    <Icon name="mail" />
                    Email
                  </a>
                )}
              </div>
            )}
          </article>
        );
      })}
    </section>
  );
}
