// Cost section — combines: calculator + narrative + planilha vs BinGest hint.
// Lives on a dark navy cinema background.

function CostSection() {
  // Inputs
  const [obras, setObras] = React.useState(4);
  const [func, setFunc] = React.useState(8);
  const [diaria, setDiaria] = React.useState(160);
  const [horasPlanilha, setHorasPlanilha] = React.useState(6);

  // Derived losses (educated heuristics)
  // 1) Diárias mal-lançadas: ~3% da folha mensal (24 dias úteis)
  const folha = func * diaria * 24;
  const lossDiarias = folha * 0.03;
  // 2) Tempo perdido em planilha — hora a R$ 65 (custo médio do gestor)
  const lossHoras = horasPlanilha * 4 * 65;
  // 3) Atraso em recebimentos: ~1.2% sobre receita estimada (R$ 22k/obra)
  const receita = obras * 22000;
  const lossRecebiveis = receita * 0.012;
  // 4) Retrabalho de assistência técnica não rastreada: R$ 320/obra/mês
  const lossAT = obras * 320;

  const totalLoss = lossDiarias + lossHoras + lossRecebiveis + lossAT;
  const yearLoss = totalLoss * 12;
  const planAnnual = 12 * 159.99; // Empresarial annual cost
  const roi = totalLoss / 159.99;

  return (
    <section id="perda" className="section-dark" style={{ paddingTop: 140, paddingBottom: 140 }}>
      {/* Subtle dotted backdrop */}
      <div aria-hidden="true" style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(rgba(255,255,255,.06) 1px, transparent 1px)",
        backgroundSize: "32px 32px",
        maskImage: "radial-gradient(ellipse at 50% 30%, #000 30%, transparent 70%)",
        WebkitMaskImage: "radial-gradient(ellipse at 50% 30%, #000 30%, transparent 70%)",
      }} />

      <div className="container relative">
        <div style={{ maxWidth: 780, marginBottom: 60 }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "6px 12px 6px 8px", borderRadius: 999,
            background: "rgba(220,38,38,.12)", color: "#FF8A8A",
            border: "1px solid rgba(220,38,38,.25)",
            fontSize: 12, fontWeight: 600, letterSpacing: ".06em",
            marginBottom: 24,
          }}>
            <span style={{
              width: 6, height: 6, borderRadius: 999, background: "var(--red-500)",
              animation: "hotspot-pulse-red 1.4s ease-out infinite",
            }} />
            ALERTA · CONTADOR EM TEMPO REAL
          </div>
          <h2 className="t-h1" style={{ color: "#fff", marginBottom: 18 }}>
            Sem o BinGest, sua obra está vazando dinheiro<br/>
            <span style={{ color: "#FF8A8A" }}>todo dia útil.</span>
          </h2>
          <p className="t-lead" style={{ color: "rgba(255,255,255,.65)", maxWidth: 620 }}>
            Ajuste sua realidade abaixo. O contador soma — em tempo real — quanto
            você está perdendo em diárias mal-lançadas, retrabalho em planilha,
            atrasos em recebimentos e assistência técnica fora do radar.
          </p>
        </div>

        {/* Calculator grid */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "1.05fr 1fr",
          gap: 28,
          alignItems: "stretch",
        }} className="cost-grid">

          {/* Left: sliders */}
          <div style={{
            background: "rgba(255,255,255,.04)",
            border: "1px solid rgba(255,255,255,.10)",
            borderRadius: 24,
            padding: 32,
          }}>
            <div style={{ marginBottom: 4, fontSize: 11, letterSpacing: ".12em", color: "rgba(255,255,255,.5)", fontWeight: 600, textTransform: "uppercase" }}>
              Sua operação
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, marginBottom: 24, color: "#fff" }}>
              Como é sua obra hoje?
            </div>

            <Slider
              label="Obras ativas simultâneas"
              value={obras} setValue={setObras} min={1} max={20}
              fmt={(v) => `${v} obra${v>1?"s":""}`}
            />
            <Slider
              label="Funcionários em campo"
              value={func} setValue={setFunc} min={1} max={40}
              fmt={(v) => `${v} pessoa${v>1?"s":""}`}
            />
            <Slider
              label="Diária média"
              value={diaria} setValue={setDiaria} min={80} max={350} step={5}
              fmt={(v) => `R$ ${v}`}
            />
            <Slider
              label="Horas por semana em planilha"
              value={horasPlanilha} setValue={setHorasPlanilha} min={0} max={20}
              fmt={(v) => `${v} h/sem`}
              last
            />
          </div>

          {/* Right: loss panel */}
          <div style={{
            background: "linear-gradient(180deg, rgba(220,38,38,.10), rgba(220,38,38,0))",
            border: "1px solid rgba(220,38,38,.22)",
            borderRadius: 24,
            padding: 32,
            display: "flex",
            flexDirection: "column",
          }}>
            <div style={{ fontSize: 11, letterSpacing: ".12em", color: "rgba(255,255,255,.5)", fontWeight: 600, textTransform: "uppercase", marginBottom: 4 }}>
              Estimativa de prejuízo mensal
            </div>

            <div style={{
              fontFamily: "var(--font-mono)",
              fontSize: "clamp(48px, 7vw, 88px)",
              fontWeight: 600,
              color: "#FF6B6B",
              letterSpacing: "-0.04em",
              lineHeight: 0.95,
              marginTop: 8, marginBottom: 22,
              textShadow: "0 0 60px rgba(255,107,107,.25)",
              fontVariantNumeric: "tabular-nums",
            }}>
              <BigCurrency value={totalLoss} />
            </div>

            <div style={{ display: "grid", gap: 10, marginBottom: 22 }}>
              <LossRow icon={<IconUsers size={14} />} label="Diárias mal-lançadas (≈3% da folha)" value={lossDiarias} />
              <LossRow icon={<IconClock size={14} />} label="Horas perdidas em planilha" value={lossHoras} />
              <LossRow icon={<IconWallet size={14} />} label="Atraso em recebimentos" value={lossRecebiveis} />
              <LossRow icon={<IconHelmet size={14} />} label="Assistência técnica fora do radar" value={lossAT} />
            </div>

            <div style={{
              marginTop: "auto",
              padding: "18px 20px",
              borderRadius: 14,
              background: "rgba(255,255,255,.05)",
              border: "1px solid rgba(255,255,255,.10)",
              display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap",
            }}>
              <div>
                <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.55)", letterSpacing: ".06em", textTransform: "uppercase", fontWeight: 600 }}>
                  Por ano
                </div>
                <div className="mono tabular" style={{ fontSize: 22, fontWeight: 600, color: "#fff" }}>
                  <BigCurrency value={yearLoss} decimals={0} />
                </div>
              </div>
              <div style={{ width: 1, alignSelf: "stretch", background: "rgba(255,255,255,.10)" }} />
              <div>
                <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.55)", letterSpacing: ".06em", textTransform: "uppercase", fontWeight: 600 }}>
                  vs BinGest Empresarial
                </div>
                <div className="mono tabular" style={{ fontSize: 22, fontWeight: 600, color: "var(--green-500)" }}>
                  {Math.round(roi).toLocaleString("pt-BR")}× ROI
                </div>
              </div>
              <a href="#demo" className="btn btn-blue btn-sm" style={{ marginLeft: "auto" }}>
                Parar de perder <IconArrow size={14} />
              </a>
            </div>
          </div>
        </div>

        {/* Narrative: o João */}
        <Narrative loss={Math.round(totalLoss)} />
      </div>

      <style>{`
        @media (max-width: 900px) {
          .cost-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

function Slider({ label, value, setValue, min, max, step=1, fmt, last=false }) {
  return (
    <div style={{ marginBottom: last ? 0 : 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
        <label style={{ fontSize: 13.5, color: "rgba(255,255,255,.85)", fontWeight: 500 }}>{label}</label>
        <span className="mono tabular" style={{ fontSize: 15, fontWeight: 600, color: "#fff" }}>{fmt(value)}</span>
      </div>
      <input
        type="range" min={min} max={max} step={step} value={value}
        onChange={(e) => setValue(Number(e.target.value))}
        style={{
          width: "100%", appearance: "none", height: 4, borderRadius: 999,
          background: `linear-gradient(to right, var(--blue-500) 0%, var(--blue-500) ${((value-min)/(max-min))*100}%, rgba(255,255,255,.10) ${((value-min)/(max-min))*100}%, rgba(255,255,255,.10) 100%)`,
          outline: "none", cursor: "pointer",
        }}
        className="bg-slider"
      />
      <style>{`
        .bg-slider::-webkit-slider-thumb {
          -webkit-appearance: none; appearance: none;
          width: 22px; height: 22px; border-radius: 999px;
          background: #fff; border: 4px solid var(--blue-500);
          cursor: grab;
          box-shadow: 0 4px 14px rgba(42,91,255,.45);
        }
        .bg-slider::-moz-range-thumb {
          width: 22px; height: 22px; border-radius: 999px;
          background: #fff; border: 4px solid var(--blue-500);
          cursor: grab;
        }
      `}</style>
    </div>
  );
}

function LossRow({ icon, label, value }) {
  return (
    <div style={{
      display: "flex", justifyContent: "space-between", alignItems: "center",
      padding: "12px 14px", borderRadius: 12,
      background: "rgba(255,255,255,.04)",
      border: "1px solid rgba(255,255,255,.06)",
    }}>
      <span style={{ display: "flex", alignItems: "center", gap: 10, color: "rgba(255,255,255,.85)", fontSize: 13 }}>
        <span style={{
          width: 26, height: 26, borderRadius: 8,
          background: "rgba(220,38,38,.18)", color: "#FF8A8A",
          display: "grid", placeItems: "center",
        }}>{icon}</span>
        {label}
      </span>
      <span className="mono tabular" style={{ color: "#FF8A8A", fontSize: 14, fontWeight: 600 }}>
        <BigCurrency value={value} />
      </span>
    </div>
  );
}

function BigCurrency({ value, decimals = 0 }) {
  // Smooth tween toward value as it changes
  const [n, setN] = React.useState(value);
  React.useEffect(() => {
    let raf, t0;
    const from = n, to = value;
    const dur = 600;
    const step = (t) => {
      if (!t0) t0 = t;
      const p = Math.min(1, (t - t0) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setN(from + (to - from) * eased);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return <>R$ {n.toLocaleString("pt-BR", { minimumFractionDigits: decimals, maximumFractionDigits: decimals })}</>;
}

function Narrative({ loss }) {
  return (
    <div style={{
      marginTop: 90,
      display: "grid", gridTemplateColumns: "1fr", gap: 28,
    }}>
      <div className="t-eyebrow" style={{ color: "rgba(255,255,255,.5)" }}>História real, sem maquiagem</div>

      <div style={{
        display: "grid",
        gridTemplateColumns: "repeat(3, 1fr)",
        gap: 18,
      }} className="story-grid">
        <StoryStep
          step="01"
          when="Segunda · 07h12"
          title="João lança 5 diárias na planilha"
          body="Dois nomes saem errados. Uma diária some por causa de fórmula quebrada. Ninguém percebe."
          tone="bad"
        />
        <StoryStep
          step="02"
          when="Sexta · 17h45"
          title="A obra fechou no vermelho?"
          body="João abre 3 planilhas, 2 conversas no WhatsApp e a calculadora. Demora 2h e ainda fica em dúvida."
          tone="bad"
        />
        <StoryStep
          step="03"
          when="Fim do mês"
          title="O DRE não bate"
          body="Faltam R$ 1.840 de custos. Não sabe se a margem foi 12% ou 18%. Decide 'no sentimento' a próxima obra."
          tone="bad"
        />
      </div>

      <div style={{
        padding: "26px 28px",
        borderRadius: 18,
        background: "linear-gradient(135deg, rgba(34,197,94,.15), rgba(34,197,94,0))",
        border: "1px solid rgba(34,197,94,.25)",
        display: "flex", alignItems: "center", gap: 22, flexWrap: "wrap",
      }}>
        <span style={{
          width: 44, height: 44, borderRadius: 14,
          background: "var(--green-600)", color: "#fff",
          display: "grid", placeItems: "center",
        }}>
          <IconCheck size={22} />
        </span>
        <div style={{ flex: 1, minWidth: 280 }}>
          <div style={{ fontSize: 11.5, color: "rgba(255,255,255,.55)", letterSpacing: ".06em", textTransform: "uppercase", fontWeight: 600, marginBottom: 4 }}>
            Com BinGest
          </div>
          <div style={{ fontSize: 18, fontWeight: 500, color: "#fff", lineHeight: 1.4 }}>
            João faz check-in da equipe no celular do mestre. O DRE fecha sozinho.
            Ele sabe — em <span className="mono" style={{ color: "var(--green-500)", fontWeight: 700 }}>3 cliques</span> — qual obra deu lucro.
          </div>
        </div>
        <a href="#demo" className="btn btn-blue btn-sm" style={{ flex: "0 0 auto" }}>
          Ver na prática <IconArrow size={14} />
        </a>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .story-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
}

function StoryStep({ step, when, title, body, tone }) {
  const bad = tone === "bad";
  return (
    <div style={{
      padding: "22px 22px 24px",
      borderRadius: 18,
      background: bad ? "rgba(220,38,38,.06)" : "rgba(34,197,94,.08)",
      border: bad ? "1px solid rgba(220,38,38,.18)" : "1px solid rgba(34,197,94,.22)",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14 }}>
        <span className="mono" style={{
          fontSize: 11, fontWeight: 600, color: bad ? "#FF8A8A" : "var(--green-500)",
          letterSpacing: ".1em",
        }}>{step}</span>
        <span style={{ fontSize: 11, color: "rgba(255,255,255,.5)" }}>{when}</span>
      </div>
      <div style={{ fontSize: 17, fontWeight: 600, color: "#fff", marginBottom: 8, letterSpacing: "-0.01em", lineHeight: 1.2 }}>
        {title}
      </div>
      <div style={{ fontSize: 13.5, color: "rgba(255,255,255,.65)", lineHeight: 1.5 }}>
        {body}
      </div>
    </div>
  );
}

window.CostSection = CostSection;
