// PillNav — menu pilule avec curseur animé qui suit le hover.
// Inversion noir/blanc des labels gérée en JS direct (pas de mix-blend-mode
// qui pose des problèmes de transparence avec les sticky headers).

const PillNav = ({
  items = ['Sommaire', 'Services', 'Atelier', 'Cabinet', 'Contact'],
  color = '#ffffff', bg = '#000000', mono,
}) => {
  const [pos, setPos] = React.useState({ left: 0, width: 0, opacity: 0 });
  const [activeIdx, setActiveIdx] = React.useState(-1);
  const refs = React.useRef([]);

  const normalized = items.map((it) =>
    typeof it === 'string' ? { label: it, href: null } : it
  );

  const onEnter = (i) => {
    const el = refs.current[i];
    if (!el) return;
    const rect = el.getBoundingClientRect();
    setPos({ left: el.offsetLeft, width: rect.width, opacity: 1 });
    setActiveIdx(i);
  };
  const onLeave = () => {
    setPos((p) => ({ ...p, opacity: 0 }));
    setActiveIdx(-1);
  };

  const handleClick = (e, item) => {
    if (!item.href) return;
    if (item.href === '#top' || item.href === '/') {
      e.preventDefault();
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    if (item.href.startsWith('#')) {
      const target = document.querySelector(item.href);
      if (target) {
        e.preventDefault();
        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    }
  };

  return (
    <ul
      onMouseLeave={onLeave}
      style={{
        position: 'relative', display: 'flex', listStyle: 'none', padding: 4,
        margin: 0, borderRadius: 999, border: `1.5px solid ${color}`,
        background: bg, width: 'fit-content',
      }}
    >
      {normalized.map((item, i) => (
        <li
          key={item.label}
          ref={(el) => (refs.current[i] = el)}
          onMouseEnter={() => onEnter(i)}
          style={{
            position: 'relative', zIndex: 10, display: 'block',
          }}
        >
          <a
            href={item.href || '#'}
            onClick={(e) => handleClick(e, item)}
            style={{
              display: 'block', cursor: 'pointer', textDecoration: 'none',
              padding: '10px 20px', ...mono, fontSize: 11,
              color: activeIdx === i ? bg : color,
              transition: 'color 260ms cubic-bezier(0.22, 1, 0.36, 1)',
            }}
          >
            {item.label}
          </a>
        </li>
      ))}
      <li
        style={{
          position: 'absolute', zIndex: 0, height: 'calc(100% - 8px)', top: 4,
          left: pos.left, width: pos.width, opacity: pos.opacity,
          background: color, borderRadius: 999,
          transition: 'left 320ms cubic-bezier(0.22, 1, 0.36, 1), width 320ms cubic-bezier(0.22, 1, 0.36, 1), opacity 200ms ease',
        }}
      />
    </ul>
  );
};

window.PillNav = PillNav;
