// Progresso da exploração: leitura de scroll + conclusão do CTA final.
function ProgressRail() {
  const [progress, setProgress] = React.useState(0);
  const [complete, setComplete] = React.useState(false);

  React.useEffect(() => {
    let frame = null;
    const update = () => {
      frame = null;
      if (complete) {
        setProgress(100);
        return;
      }
      const max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
      const raw = Math.min(1, Math.max(0, window.scrollY / max));
      // A curva valoriza o caminho já percorrido e chega alta perto do cadastro.
      setProgress(Math.min(96, Math.round(Math.sqrt(raw) * 100)));
    };
    const onScroll = () => {
      if (frame === null) frame = requestAnimationFrame(update);
    };
    const onProgress = (event) => setComplete(Boolean(event.detail?.complete));
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    window.addEventListener("operation-progress", onProgress);
    return () => {
      if (frame !== null) cancelAnimationFrame(frame);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      window.removeEventListener("operation-progress", onProgress);
    };
  }, [complete]);

  const label = complete
    ? "Cadastro encaminhado"
    : progress >= 84
      ? "Só falta enviar o cadastro"
      : progress >= 58
        ? "Você já conhece a operação"
        : "Conhecendo as oportunidades";

  return (
    <React.Fragment>
      <div className="page-progress-track" aria-hidden="true">
        <span style={{ transform: `scaleX(${progress / 100})` }} />
      </div>
      <div
        className={`page-progress-status${progress > 8 ? " is-visible" : ""}${complete ? " is-complete" : ""}`}
        role="progressbar"
        aria-label="Progresso na Operação Brasil"
        aria-valuemin="0"
        aria-valuemax="100"
        aria-valuenow={progress}
      >
        <span className="page-progress-copy">{label}</span>
        <strong>{progress}%</strong>
      </div>
    </React.Fragment>
  );
}
window.ProgressRail = ProgressRail;
