/* global React, Reveal, Icon */
// Interactive ROI / "Your Situation" tool

const { useState: useStateR, useEffect: useEffectR, useRef: useRefR, useMemo: useMemoR } = React;

const PAIN_POINTS = [
{ id: "p1", icon: "msg", text: "We run MANUAL PROCEDURES through WhatsApp, spreadsheets, or emails", cost: 1700, category: "automate", outcome: "Replace WhatsApp threads with a system that gives you a single source of truth." },
{ id: "p2", icon: "layers", text: "We PAY FOR TOOLS that don't connect to each other", cost: 900, category: "automate", outcome: "Stitch the tools you already pay for into one operational flow." },
{ id: "p3", icon: "phone", text: "Clients CAN'T BOOK, CAN'T PAY, or check anything without calling us", cost: 2100, category: "build", outcome: "Give clients a portal so they self-serve the easy 80% — without losing the human touch." },
{ id: "p4", icon: "clock", text: "Someone on the team SPENDS MOST OF THEIR DAY on admin", cost: 2400, category: "automate", outcome: "Automate the admin so that person can do the work you actually hired them for." },
{ id: "p5", icon: "user-x", text: "We've LOST CLIENTS because our process felt unprofessional", cost: 3000, category: "build", outcome: "Reshape the parts clients touch so the experience matches the quality of your work." },
{ id: "p6", icon: "file", text: "Reports, invoices, and updates are all PREPARED BY HAND", cost: 1300, category: "automate", outcome: "Generate the paperwork automatically — accurate, branded, sent on time." }];


function PainCard({ point, selected, onClick }) {
  const ref = useRefR(null);
  const [pressed, setPressed] = useStateR(false);
  const handle = (e) => {
    const rect = ref.current.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const span = document.createElement("span");
    span.className = "ripple";
    span.style.left = x + "px";
    span.style.top = y + "px";
    const size = Math.max(rect.width, rect.height) / 2;
    span.style.width = span.style.height = size + "px";
    ref.current.appendChild(span);
    setTimeout(() => span.remove(), 700);

    setPressed(true);
    setTimeout(() => setPressed(false), 140);
    onClick();
  };
  return (
    <button
      ref={ref}
      className={"pain-card" + (selected ? " selected" : "") + (pressed ? " pressed" : "")}
      onClick={handle}
      type="button">
      
      <span className="pain-icon">
        <Icon name={point.icon} size={17} />
      </span>
      <span className="pain-text">{point.text}</span>
      <span className="pain-check">
        <Icon name="check" size={11} />
      </span>
    </button>);

}

function Slider({ label, value, min, max, step, onChange, format }) {
  const [bump, setBump] = useStateR(false);
  useEffectR(() => {
    setBump(true);
    const t = setTimeout(() => setBump(false), 250);
    return () => clearTimeout(t);
  }, [value]);
  return (
    <div className="slider-row">
      <span className="slider-label">{label}</span>
      <input
        type="range"
        className="slider-input"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))} />
      
      <span className={"slider-value" + (bump ? " bump" : "")}>{format(value)}</span>
    </div>);

}

function useCountUp(target, duration = 420) {
  const [val, setVal] = useStateR(0);
  const fromRef = useRefR(0);
  useEffectR(() => {
    const from = fromRef.current;
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      const v = from + (target - from) * eased;
      setVal(v);
      if (t < 1) raf = requestAnimationFrame(tick);else
      fromRef.current = target;
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return val;
}

function fmtEuro(n) {
  return "€" + Math.round(n).toLocaleString("en-US");
}

function ROITool() {
  const [selected, setSelected] = useStateR(new Set());
  const [team, setTeam] = useStateR(5);
  const [revenue, setRevenue] = useStateR(30000);
  const [phase2, setPhase2] = useStateR(false);
  const [loading, setLoading] = useStateR(false);
  const [typed, setTyped] = useStateR("");
  const [bulletsIn, setBulletsIn] = useStateR(0);

  const selectedList = PAIN_POINTS.filter((p) => selected.has(p.id));
  const count = selected.size;

  // Cost: sum + small multipliers from team & revenue
  const teamMult = 0.6 + team / 25; // 0.6 to ~1.4
  const revMult = 0.5 + revenue / 100000;
  const rawCost = selectedList.reduce((a, p) => a + p.cost, 0) * teamMult * revMult;
  const animatedCost = useCountUp(rawCost);
  const [flash, setFlash] = useStateR(false);

  // Flash when count reaches steady value
  const prevTargetRef = useRefR(rawCost);
  useEffectR(() => {
    if (prevTargetRef.current !== rawCost) {
      prevTargetRef.current = rawCost;
      const t = setTimeout(() => {
        setFlash(true);
        setTimeout(() => setFlash(false), 300);
      }, 420);
      return () => clearTimeout(t);
    }
  }, [rawCost]);

  // Approach detection
  const approach = useMemoR(() => {
    if (selectedList.length === 0) return null;
    const a = selectedList.filter((p) => p.category === "automate").length;
    const b = selectedList.filter((p) => p.category === "build").length;
    if (a > 0 && b > 0) return "hybrid";
    if (a > 0) return "automate";
    return "build";
  }, [selectedList]);

  const projectCost = rawCost * 4.2; // ~4 month payback
  const paybackMonths = rawCost > 0 ? Math.max(2, Math.round(projectCost / rawCost)) : 4;

  const togglePain = (id) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);else
      next.add(id);
      return next;
    });
    if (phase2) {
      // reset phase 2 if user changes selection after viewing it
      setPhase2(false);
      setTyped("");
      setBulletsIn(0);
    }
  };

  const handleReading = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      setPhase2(true);
    }, 2000);
  };

  // Typewriter for diagnosis
  const diagnosis = useMemoR(() => {
    if (!approach) return "";
    const counts = {
      automate: selectedList.filter((p) => p.category === "automate").length,
      build: selectedList.filter((p) => p.category === "build").length
    };
    const lead = {
      automate: "Your business already works — it's the friction inside it that's eating your time.",
      build: "You're held back by tools you don't have yet, not the people you have.",
      hybrid: "Half of what's slowing you down can be automated tomorrow. The other half needs to be built."
    }[approach];
    const middle = count >= 4 ?
    " The pattern is clear: too many decisions are still living in someone's head." :
    count === 3 ?
    " There's a clear pattern here, and it's fixable in a single, focused engagement." :
    " Two signals is enough to see the shape of the problem.";
    const tail = ` At ${team} people and roughly €${revenue.toLocaleString()}/mo, the math says you'll recoup the build in about ${paybackMonths} months — and then it pays you, every month after that.`;
    return lead + middle + tail;
  }, [approach, count, team, revenue, paybackMonths, selectedList]);

  useEffectR(() => {
    if (!phase2) return;
    setTyped("");
    setBulletsIn(0);
    let i = 0;
    const id = setInterval(() => {
      i++;
      setTyped(diagnosis.slice(0, i));
      if (i >= diagnosis.length) {
        clearInterval(id);
        // bullets reveal after typing
        let b = 0;
        const bi = setInterval(() => {
          b++;
          setBulletsIn(b);
          if (b >= 3) clearInterval(bi);
        }, 220);
      }
    }, 14);
    return () => clearInterval(id);
  }, [phase2, diagnosis]);

  const outcomes = useMemoR(() => {
    if (selectedList.length === 0) return [];
    const list = selectedList.slice(0, 3).map((p) => p.outcome);
    while (list.length < 3) list.push("Document what we changed so your team can run it without us.");
    return list;
  }, [selectedList]);

  const approachConfig = {
    automate: { label: "Automating your existing operations", title: "Automate first.", sub: "We make what you have work without humans where it shouldn't need them." },
    build: { label: "Building something new", title: "Build the missing piece.", sub: "There's a system-shaped hole in your operation. We'll fill it cleanly." },
    hybrid: { label: "Automate first, build what's missing", title: "Hybrid approach.", sub: "Automate the friction this quarter; build the bigger piece in parallel." }
  };

  const reset = () => {
    setSelected(new Set());
    setPhase2(false);
    setTyped("");
    setBulletsIn(0);
  };

  return (
    <section className="pad" id="situation">
      <div className="shell">
        <div className="roi-wrap">
          <Reveal className="roi-head">
            <div className="eyebrow">Your situation</div>
            <h2 className="serif">Stop losing money please.</h2>
            <p>Click what's true about your business — we'll turn it into numbers and show you exactly what we'd do to fix it.</p>
          </Reveal>

          <Reveal className="pain-grid">
            {PAIN_POINTS.map((p) =>
            <PainCard
              key={p.id}
              point={p}
              selected={selected.has(p.id)}
              onClick={() => togglePain(p.id)} />

            )}
          </Reveal>

          <div className={"sliders-wrap" + (count >= 2 ? " open" : "")}>
            <div className="sliders-inner">
              <div className="sliders-hint">Help us make this personal —</div>
              <Slider
                label="Team size"
                value={team}
                min={1}
                max={50}
                step={1}
                onChange={setTeam}
                format={(v) => `${v} ${v === 1 ? "person" : "people"}`} />
              
              <Slider
                label="Monthly revenue"
                value={revenue}
                min={5000}
                max={250000}
                step={5000}
                onChange={setRevenue}
                format={(v) => `€${v.toLocaleString()}/mo`} />
              
            </div>
          </div>

          <div className={"meter" + (count > 0 ? " live" : "")}>
            <div className="meter-eyebrow">Your situation costs approximately</div>
            <div className={"meter-num" + (flash ? " flash" : "")}>
              {count === 0 ? "€0" : fmtEuro(animatedCost)}
            </div>
            <div className="meter-sub">per month — in lost time, labor, and revenue</div>

            {count > 0 &&
            <>
                <div className="meter-divider" />
                <div className="meter-rows">
                  {selectedList.map((p, i) => {
                  const rowCost = p.cost * teamMult * revMult;
                  const labels = {
                    p1: "Manual operations",
                    p2: "Disconnected tool stack",
                    p3: "Missing self-service",
                    p4: "Admin time tax",
                    p5: "Lost client revenue",
                    p6: "Manual paperwork"
                  };
                  return (
                    <div
                      key={p.id}
                      className="meter-row"
                      style={{ animationDelay: i * 60 + "ms" }}>
                      
                        <span className="l">{labels[p.id]}</span>
                        <span className="r">{fmtEuro(rowCost)}/mo</span>
                      </div>);

                })}
                </div>
                <div className={"meter-payback in"}>
                  <div className="num">{paybackMonths} months</div>
                  <div className="desc">until the right system pays for itself — then it's pure savings, every month.</div>
                </div>
              </>
            }
          </div>

          <div className={"reading-wrap" + (count >= 2 && !phase2 ? " open" : "")}>
            <div className="reading-inner">
              <button className="reading-btn" disabled={loading} onClick={handleReading}>
                {loading ?
                <>
                    <span className="spinner" />
                    Reading the room…
                  </> :

                <>
                    Get my reading <Icon name="arrow-right" size={14} />
                  </>
                }
              </button>
            </div>
          </div>

          {phase2 && approach &&
          <div className="roi-phase2">
              <div className="phase2-card in reading-card">
                <div className="eyebrow">Our read on your situation</div>
                <div className="reading-text">
                  {typed}
                  {typed.length < diagnosis.length && <span className="cursor" />}
                </div>
              </div>

              <div className="phase2-card in approach-card" style={{ transitionDelay: "220ms" }}>
                <span className={"approach-badge " + approach}>
                  <span style={{
                  width: 6, height: 6, borderRadius: "50%",
                  background: approach === "automate" ? "#5a7a45" : approach === "build" ? "var(--gold-dark)" : "#3a6590"
                }} />
                  {approachConfig[approach].label}
                </span>
                <div className="approach-title">{approachConfig[approach].title}</div>
                <div className="approach-sub">{approachConfig[approach].sub}</div>
                <ul className="approach-bullets">
                  {outcomes.map((o, i) =>
                <li key={i} className={i < bulletsIn ? "in" : ""}>{o}</li>
                )}
                </ul>
                <div className="approach-strip">
                  {[
                { k: "automate", t: "Automate", d: "Make what they have work without humans." },
                { k: "build", t: "Build", d: "Create something new that didn't exist." },
                { k: "hybrid", t: "Hybrid", d: "Both, in the right order." }].
                map((s) =>
                <div key={s.k} className={"approach-strip-cell" + (s.k === approach ? " on" : "")}>
                      <span className="t">{s.t}</span>
                      <span className="d">{s.d}</span>
                    </div>
                )}
                </div>
              </div>

              <div className="phase2-card in cta-card" style={{ transitionDelay: "440ms" }}>
                <h3>Let's look at this together.</h3>
                <p>Book 30 minutes — no pitch, no pressure. We'll walk through your exact numbers and show you what the right approach would cost and save.</p>
                <div className="cta-buttons">
                  <a className="btn btn-gold" href="#contact">Book a free 30-min call <Icon name="arrow-right" size={14} /></a>
                  <button className="btn btn-ghost" onClick={reset}>Try a different situation</button>
                </div>
              </div>
            </div>
          }
        </div>
      </div>
    </section>);

}

Object.assign(window, { ROITool });