'use client';
import React, {useEffect, useState} from 'react';
import Link from 'next/link';
import {useTranslations} from 'next-intl';
import {Carousel} from 'react-bootstrap';
import {getAffichesAdherents, type AfficheAdherent} from '@/services/evenementService';
import {evenementHref} from '@/utils/evenementHref';

interface AffichesAdherentsProps {
  locale: string;
}

const PAR_VUE = 4;

function chunk<T>(items: T[], size: number): T[][] {
  const groupes: T[][] = [];
  for (let i = 0; i < items.length; i += size) groupes.push(items.slice(i, i + size));
  return groupes;
}

/** Bloc déroulant des affiches des prochains événements organisés par les adhérents (spec L12). */
export default function AffichesAdherents({locale}: AffichesAdherentsProps) {
  const t = useTranslations('HomePage');
  const [affiches, setAffiches] = useState<AfficheAdherent[]>([]);

  useEffect(() => {
    getAffichesAdherents(12).then(setAffiches).catch(() => setAffiches([]));
  }, []);

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

  const formatDate = (date: string | null) =>
    date ? new Date(date).toLocaleDateString(locale, {day: 'numeric', month: 'short'}) : '';

  return (
    <section className="footerv2__affiches" data-testid="footer-affiches" aria-label={t('footer_affiches_title')}>
      <h4 className="footerv2__heading footerv2__heading--orange">{t('footer_affiches_title')}</h4>
      <Carousel indicators={false} interval={6000} controls={affiches.length > PAR_VUE}>
        {chunk(affiches, PAR_VUE).map((groupe, index) => (
          <Carousel.Item key={index}>
            <div className="footerv2__affiches-row">
              {groupe.map((affiche) => (
                <Link key={affiche.eveId} href={evenementHref(locale, affiche.eveId, affiche.libelle)} className="footerv2__affiche">
                  <img src={affiche.afficheUrl} alt={affiche.libelle} loading="lazy" />
                  <span className="footerv2__affiche-caption">
                    {affiche.libelle}
                    <small>
                      {formatDate(affiche.date)}
                      {affiche.vilNom && ` · ${affiche.vilNom}`}
                    </small>
                  </span>
                </Link>
              ))}
            </div>
          </Carousel.Item>
        ))}
      </Carousel>
    </section>
  );
}
