/* Dirigeants.jsx - adaptation du carrousel Leadership de Wealth Management */

const LEADERS = [
  {
    name: 'Emmanuel Lutaud',
    role: 'Directeur M&A',
    slug: 'emmanuel-lutaud',
    image: 'assets/img/leaders/emmanuel-lutaud.jpg',
  },
  {
    name: 'Benjamin Surville',
    role: 'Directeur général délégué du Groupe',
    slug: 'benjamin-surville',
    image: 'assets/img/leaders/benjamin-surville.png',
  },
  {
    name: 'Jérémy Aras',
    role: 'Directeur général délégué',
    slug: 'jeremy-aras',
    image: 'assets/img/leaders/jeremy-aras.webp',
  },
  {
    name: 'Charlotte Visdeloup',
    role: 'Directrice administrative et financière',
    slug: 'charlotte-visdeloup',
    image: 'assets/img/leaders/charlotte-visdeloup.png',
  },
  {
    name: 'Alex Roubinet',
    role: 'Chief of AI',
    slug: 'alex-roubinet',
    image: 'assets/img/leaders/alex-roubinet.jpg',
  },
  {
    name: 'Stéphane Peltier',
    role: 'Président',
    slug: 'stephane-peltier',
    image: 'assets/img/leaders/stephane-peltier.png',
  },
];

function Dirigeants() {
  const sectionRef = useRef(null);
  const [activeIndex, setActiveIndex] = useState(0);
  const [mobileLayout, setMobileLayout] = useState(false);
  const [sectionVisible, setSectionVisible] = useState(false);
  const [cycleKey, setCycleKey] = useState(0);
  const lastIndex = LEADERS.length - 1;

  useEffect(() => {
    const mobile = window.matchMedia('(max-width: 789.98px)');
    const syncLayout = () => setMobileLayout(mobile.matches);
    syncLayout();
    mobile.addEventListener('change', syncLayout);
    return () => mobile.removeEventListener('change', syncLayout);
  }, []);

  useEffect(() => {
    const section = sectionRef.current;
    if (!section || !('IntersectionObserver' in window)) {
      setSectionVisible(true);
      return;
    }
    const observer = new IntersectionObserver(
      ([entry]) => setSectionVisible(entry.isIntersecting),
      { threshold: 0.2 },
    );
    observer.observe(section);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (!mobileLayout || !sectionVisible || reduceMotion || activeIndex >= lastIndex) return;
    const timer = window.setTimeout(() => setActiveIndex(index => Math.min(index + 1, lastIndex)), 5000);
    return () => window.clearTimeout(timer);
  }, [activeIndex, mobileLayout, sectionVisible, cycleKey]);

  const selectLeader = (index) => {
    setActiveIndex(index);
    setCycleKey(key => key + 1);
  };

  const handleKeyDown = (event) => {
    if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
    event.preventDefault();
    if (event.key === 'Home') selectLeader(0);
    if (event.key === 'End') selectLeader(lastIndex);
    if (event.key === 'ArrowLeft') selectLeader(Math.max(activeIndex - 1, 0));
    if (event.key === 'ArrowRight') selectLeader(Math.min(activeIndex + 1, lastIndex));
  };

  return (
    <section id="equipe" className="pf-leadership" ref={sectionRef} aria-labelledby="dirigeants-title">
      <div className="pf-leadership-heading">
        <Eyebrow>Leadership</Eyebrow>
        <h2 id="dirigeants-title" className="pf-display-2">
          Des convictions fortes,<br />portées par <em>des entrepreneurs.</em>
        </h2>
        <p className="pf-body">
          Des dirigeants-entrepreneurs accessibles, directement engagés dans la relation et dans les décisions qui comptent.
        </p>
      </div>

      <div className="pf-leadership-stage">
        <aside className="pf-leadership-roster" aria-label="Équipe dirigeante">
          <p>Direction · Groupe Patrimmofi</p>
          <div className="pf-leadership-roster-list">
            {LEADERS.map((leader, index) => (
              <button
                type="button"
                key={leader.slug}
                className={activeIndex === index ? 'is-active' : ''}
                aria-controls={`leader-${leader.slug}`}
                aria-pressed={activeIndex === index}
                onClick={() => selectLeader(index)}
              >
                <span aria-hidden="true" />
                {leader.name}
              </button>
            ))}
          </div>
        </aside>

        <div
          className="pf-leadership-carousel"
          data-autoplay={mobileLayout && sectionVisible && activeIndex < lastIndex ? 'true' : 'false'}
          aria-label="Équipe dirigeante"
          aria-roledescription="carrousel"
          role="region"
          tabIndex="0"
          onKeyDown={handleKeyDown}
        >
          <div className="pf-leadership-viewport">
            <div
              className="pf-leadership-track"
              style={{ transform:`translate3d(${(-100 / LEADERS.length) * activeIndex}%, 0, 0)` }}
            >
              {LEADERS.map((leader, index) => {
                const isActive = activeIndex === index;
                return (
                  <article
                    id={`leader-${leader.slug}`}
                    className="pf-leader-slide"
                    data-active={isActive ? 'true' : 'false'}
                    aria-label={`${leader.name}, ${leader.role}, ${index + 1} sur ${LEADERS.length}`}
                    aria-roledescription="profil"
                    key={leader.slug}
                  >
                    <div className="pf-leader-card">
                      <div className="pf-leader-photo" aria-hidden="true">
                        <img src={leader.image} alt="" loading="lazy" decoding="async" />
                      </div>
                      <div className="pf-leader-shade" aria-hidden="true" />
                      <div className="pf-leader-copy pf-leader-copy-inactive" aria-hidden="true">
                        <h3>{leader.name}</h3>
                        <p>{leader.role}</p>
                      </div>
                      <div className="pf-leader-copy pf-leader-copy-active" aria-hidden="true">
                        <h3>{leader.name}</h3>
                        <p>{leader.role}</p>
                      </div>
                      <button
                        type="button"
                        className="pf-leader-card-hit"
                        aria-hidden={mobileLayout || !isActive}
                        aria-label={isActive && index < lastIndex ? 'Afficher le profil suivant' : `Afficher le profil de ${leader.name}`}
                        disabled={activeIndex === lastIndex}
                        onClick={() => selectLeader(isActive ? Math.min(index + 1, lastIndex) : index)}
                        tabIndex={!mobileLayout && isActive && activeIndex < lastIndex ? 0 : -1}
                      />
                    </div>
                  </article>
                );
              })}
            </div>
          </div>

          <div className="pf-leadership-mobile-controls" aria-label="Navigation des profils">
            <button type="button" aria-label="Profil précédent" disabled={activeIndex === 0} onClick={() => selectLeader(Math.max(activeIndex - 1, 0))}>
              <span aria-hidden="true">←</span>
            </button>
            <button type="button" aria-label="Profil suivant" disabled={activeIndex === lastIndex} onClick={() => selectLeader(Math.min(activeIndex + 1, lastIndex))}>
              <svg aria-hidden="true" className="pf-leadership-progress" viewBox="0 0 56 34">
                <rect fill="none" height="32" pathLength="1" rx="16" width="54" x="1" y="1" />
                <rect className="pf-leadership-progress-value" fill="none" height="32" key={`${activeIndex}-${cycleKey}`} pathLength="1" rx="16" width="54" x="1" y="1" />
              </svg>
              <span aria-hidden="true">→</span>
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Dirigeants });
