// Root app — state machine + loading overlay

const LOADING_SEQUENCE = [
  { text: "Calculando potencial…", duration: 500 },
  { text: "Cruzando dados de mercado…", duration: 700 },
  { text: "Estimando adoção por produto…", duration: 700 },
  { text: "Quase lá…", duration: 600 },
];

function LoadingOverlay() {
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    if (idx >= LOADING_SEQUENCE.length - 1) return;
    const t = setTimeout(() => setIdx(idx + 1), LOADING_SEQUENCE[idx].duration);
    return () => clearTimeout(t);
  }, [idx]);
  return (
    <div className="loading-over">
      <div className="loading-spinner"></div>
      <div className="loading-text">{LOADING_SEQUENCE[idx].text}</div>
    </div>
  );
}

const INITIAL_FORM = {
  segmento: "",
  clientes: "",
  faturamento: "",
  produtos: [],
  nome: "",
  email: "",
  whatsapp: "",
  empresa: "",
  cargo: "",
  consent: false,
};

function App() {
  // state machine: 'landing' | 'modal' | 'loading' | 'result'
  const [stage, setStage] = React.useState("landing");
  const [modalOpen, setModalOpen] = React.useState(false);
  const [form, setForm] = React.useState(INITIAL_FORM);
  const [result, setResult] = React.useState(null);
  const [leadSent, setLeadSent] = React.useState(false);

  const onCalc = () => setModalOpen(true);
  const onCloseModal = () => setModalOpen(false);

  const onSubmit = () => {
    // Computa resultado antes de fechar o modal para incluir no e-mail
    const r = computeReceita(form);

    // Dispara e-mail em background (não bloqueia a UI)
    fetch('../send-mail-calc.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        nome:        form.nome,
        email:       form.email,
        whatsapp:    form.whatsapp,
        empresa:     form.empresa,
        cargo:       form.cargo,
        segmento:    form.segmento,
        clientes:    form.clientes,
        faturamento: form.faturamento,
        produtos:    form.produtos,
        total:       fmtBRL(r.total, { short: true }),
      }),
    })
      .then(res => res.json())
      .then(json => { if (json.ok) setLeadSent(true); })
      .catch(() => {}); // falha silenciosa — não bloqueia o resultado

    setModalOpen(false);
    setStage("loading");
    setResult(r);
    setTimeout(() => {
      setStage("result");
      window.scrollTo({ top: 0, behavior: "instant" });
    }, 2500);
  };

  const onRestart = () => {
    setForm(INITIAL_FORM);
    setResult(null);
    setStage("landing");
    setTimeout(() => window.scrollTo({ top: 0, behavior: "instant" }), 0);
  };

  const onSchedule = () => {
    alert("Aqui abriria o Calendly da SH Squads.\n\nLead já registrado no console:\n• " + form.nome + " (" + form.email + ")\n• " + form.empresa);
  };

  return (
    <React.Fragment>
      {stage === "landing" && <LandingPage onCalc={onCalc}/>}
      {stage === "result" && result && (
        <ResultScreen form={form} result={result} onRestart={onRestart} onSchedule={onSchedule} leadSent={leadSent}/>
      )}

      <CalcModal
        open={modalOpen}
        onClose={onCloseModal}
        form={form}
        setForm={setForm}
        onSubmit={onSubmit}
      />

      {stage === "loading" && <LoadingOverlay/>}
    </React.Fragment>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App/>);
