/* Floating section index rail — visible on arrival, scrollspy, smooth-scroll */
function SectionRail() {
  const sections = [
    { n: '01', label: 'Le constat',           id: 'problem' },
    { n: '02', label: 'La vitrine',           id: 'vitrine' },
    { n: '03', label: 'Le modèle & prix',     id: 'niveaux' },
    { n: '04', label: 'Catalogue',            id: 'solutions' },
    { n: '05', label: 'Capacités avancées',   id: 'capacites' },
    { n: '06', label: 'Souveraineté',         id: 'securite' },
    { n: '07', label: 'Process',              id: 'process' },
    { n: '08', label: 'FAQ',                  id: 'faq' },
  ];

  const [active, setActive] = useState(-1);
  const [hovered, setHovered] = useState(false);
  const [expandedMobile, setExpandedMobile] = useState(false);

  // Scrollspy
  useEffect(() => {
    const handler = () => {
      const probeY = window.innerHeight * 0.35;
      let current = -1;
      for (let i = 0; i < sections.length; i++) {
        const el = document.getElementById(sections[i].id);
        if (!el) continue;
        const r = el.getBoundingClientRect();
        if (r.top <= probeY) current = i;
      }
      setActive(current);
    };
    handler();
    window.addEventListener('scroll', handler, { passive: true });
    window.addEventListener('resize', handler);
    return () => {
      window.removeEventListener('scroll', handler);
      window.removeEventListener('resize', handler);
    };
  }, []);

  const jump = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 64;
    window.scrollTo({ top: y, behavior: 'smooth' });
    setExpandedMobile(false);
  };

  const progress = active < 0 ? 0 : (active + 1) / sections.length;

  return (
    <>
      {/* === DESKTOP: vertical floating rail (right side, centered) === */}
      <aside
        className="hidden lg:flex fixed right-5 xl:right-7 top-1/2 -translate-y-1/2 z-40 select-none"
        onMouseEnter={() => setHovered(true)}
        onMouseLeave={() => setHovered(false)}
        aria-label="Sommaire des sections"
      >
        <div className={`relative flex items-stretch gap-3 rounded-3xl p-2.5 transition-all duration-500
          ${hovered ? 'bg-ink-900/85 backdrop-blur-xl border border-paper-300/10 shadow-[0_20px_60px_-15px_rgba(0,0,0,0.6)]' : 'bg-transparent border border-transparent'}`}>

          {/* progress spine */}
          <div className="relative w-[3px] my-2 rounded-full bg-paper-300/10 overflow-hidden">
            <div
              className="absolute inset-x-0 top-0 rounded-full bg-gradient-to-b from-violet-600 via-violet-500 to-cy-400 transition-all duration-700"
              style={{ height: `${progress * 100}%`, boxShadow: '0 0 12px rgba(124,58,237,0.7)' }}
            ></div>
          </div>

          {/* items */}
          <ol className="flex flex-col gap-1">
            {sections.map((s, i) => {
              const isActive = i === active;
              const isPast = i < active;
              return (
                <li key={s.id}>
                  <a
                    href={`#${s.id}`}
                    onClick={jump(s.id)}
                    aria-current={isActive ? 'true' : undefined}
                    className={`group flex items-center gap-3 rounded-full pl-2 pr-3 py-1.5 transition-all duration-300 outline-none focus-visible:ring-2 focus-visible:ring-violet-500/60
                      ${isActive
                        ? 'bg-violet-600/15 border border-violet-600/30'
                        : 'border border-transparent hover:bg-paper-300/5'}`}
                  >
                    {/* number bullet */}
                    <span className={`grid place-items-center w-7 h-7 rounded-full shrink-0 font-mono text-[10.5px] font-semibold tracking-tight transition-all
                      ${isActive
                        ? 'bg-gradient-to-br from-violet-600 to-cy-400 text-white shadow-[0_0_18px_-2px_rgba(124,58,237,0.8)]'
                        : isPast
                          ? 'bg-violet-600/20 text-violet-400 border border-violet-600/30'
                          : 'bg-paper-300/5 text-paper-300/55 border border-paper-300/10 group-hover:text-paper-100 group-hover:border-paper-300/30'}`}>
                      {isPast && !isActive
                        ? <svg viewBox="0 0 12 12" className="w-2.5 h-2.5" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2 6.5l2.5 2.5L10 3.5" /></svg>
                        : s.n}
                    </span>

                    {/* label — collapsed by default, expands on hover */}
                    <span className={`overflow-hidden whitespace-nowrap transition-all duration-500 ${hovered ? 'max-w-[170px] opacity-100' : 'max-w-0 opacity-0'}`}>
                      <span className={`pr-1 text-[12.5px] tracking-tight ${isActive ? 'text-paper-50 font-medium' : 'text-paper-100/75'}`}>
                        {s.label}
                      </span>
                    </span>
                  </a>
                </li>
              );
            })}
          </ol>
        </div>
      </aside>

      {/* === MOBILE: compact pill bottom-right with expand === */}
      <div className="lg:hidden fixed right-4 bottom-5 z-40">
        {expandedMobile && (
          <div
            className="absolute bottom-full right-0 mb-3 w-[230px] rounded-2xl bg-ink-900/95 backdrop-blur-xl border border-paper-300/10 p-2 shadow-[0_20px_60px_-15px_rgba(0,0,0,0.7)]"
            style={{ animation: 'fadeIn .2s ease' }}
          >
            <div className="px-2.5 pt-1.5 pb-2 flex items-center justify-between">
              <span className="font-mono text-[10px] tracking-[0.22em] uppercase text-paper-300/50">Sommaire</span>
              <span className="font-mono text-[10px] text-violet-400">{active < 0 ? '—' : `${String(active + 1).padStart(2, '0')}/08`}</span>
            </div>
            <ol className="flex flex-col">
              {sections.map((s, i) => {
                const isActive = i === active;
                const isPast = i < active;
                return (
                  <li key={s.id}>
                    <a
                      href={`#${s.id}`}
                      onClick={jump(s.id)}
                      className={`flex items-center gap-2.5 px-2.5 py-2 rounded-lg transition ${isActive ? 'bg-violet-600/15' : 'hover:bg-paper-300/5'}`}
                    >
                      <span className={`grid place-items-center w-6 h-6 rounded-full font-mono text-[10px] font-semibold ${isActive ? 'bg-gradient-to-br from-violet-600 to-cy-400 text-white' : isPast ? 'bg-violet-600/20 text-violet-400 border border-violet-600/30' : 'bg-paper-300/5 text-paper-300/55 border border-paper-300/10'}`}>
                        {isPast && !isActive
                          ? <svg viewBox="0 0 12 12" className="w-2.5 h-2.5" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2 6.5l2.5 2.5L10 3.5" /></svg>
                          : s.n}
                      </span>
                      <span className={`text-[12.5px] tracking-tight ${isActive ? 'text-paper-50 font-medium' : 'text-paper-100/75'}`}>
                        {s.label}
                      </span>
                    </a>
                  </li>
                );
              })}
            </ol>
          </div>
        )}
        <button
          onClick={() => setExpandedMobile(v => !v)}
          aria-label="Ouvrir le sommaire"
          aria-expanded={expandedMobile}
          className="w-14 h-14 rounded-full bg-gradient-to-br from-violet-600 to-cy-400 grid place-items-center text-white shadow-[0_10px_30px_-6px_rgba(124,58,237,0.7)] active:scale-95 transition relative"
        >
          {/* progress ring */}
          <svg viewBox="0 0 56 56" className="absolute inset-0 w-full h-full -rotate-90">
            <circle cx="28" cy="28" r="25" fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth="2" />
            <circle
              cx="28" cy="28" r="25" fill="none"
              stroke="white" strokeWidth="2" strokeLinecap="round"
              strokeDasharray={2 * Math.PI * 25}
              strokeDashoffset={2 * Math.PI * 25 * (1 - progress)}
              style={{ transition: 'stroke-dashoffset .5s ease' }}
            />
          </svg>
          <span className="relative font-mono text-[12px] font-semibold">
            {active < 0 ? '00' : String(active + 1).padStart(2, '0')}
          </span>
        </button>
      </div>
    </>
  );
}

window.SectionRail = SectionRail;
