/* global React */
const { useState, useEffect, useRef } = React;

function Kinetic({ t }) {
  const lines = t.kinetic;
  const [idx, setIdx] = useState(0);
  const [phase, setPhase] = useState("active"); // active → out → next
  const ref = useRef(null);
  const [run, setRun] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setRun(true);
        });
      },
      { threshold: 0.4 },
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  useEffect(() => {
    if (!run) return;
    const hold = setTimeout(() => setPhase("out"), 1800);
    return () => clearTimeout(hold);
  }, [idx, run]);
  useEffect(() => {
    if (phase !== "out") return;
    const t = setTimeout(() => {
      setIdx((i) => (i + 1) % lines.length);
      setPhase("active");
    }, 600);
    return () => clearTimeout(t);
  }, [phase, lines.length]);

  return (
    <section className="kinetic" ref={ref}>
      <div className="kinetic-stage">
        {lines.map((line, i) => (
          <h2
            key={i}
            className={`kinetic-line ${i === idx && phase === "active" ? "is-active" : ""} ${i === idx && phase === "out" ? "is-out" : ""}`}
          >
            {line.map((seg, j) => (
              <span key={j} className={seg.tone}>
                {seg.text}
              </span>
            ))}
          </h2>
        ))}
      </div>
    </section>
  );
}

function ScrambleNumber({ target = 1138.65, decimals = 2, active }) {
  const [val, setVal] = useState(target);
  useEffect(() => {
    if (!active) return;
    let raf, t0;
    const dur = 800;
    const tick = (t) => {
      if (!t0) t0 = t;
      const p = Math.min(1, (t - t0) / dur);
      if (p < 1) {
        setVal(Math.random() * target * 1.4);
        raf = requestAnimationFrame(tick);
      } else {
        setVal(target);
      }
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active, target]);
  return <>${val.toFixed(decimals)}</>;
}

function CountUpPct({ target = 58.4, active }) {
  // Use the shared useCountUp hook (IntersectionObserver-driven, proven in bento)
  const [val, ref] = window.useCountUp(target, { duration: 1400, decimals: 1 });
  return <span ref={ref}>{val}</span>;
}

function HowItWorks({ t }) {
  const STEPS = t.how.steps;
  const [active, setActive] = useState(0);

  // Auto-cycle through steps every 5s
  useEffect(() => {
    const i = setInterval(() => setActive((a) => (a + 1) % 4), 5500);
    return () => clearInterval(i);
  }, []);

  const [typed, setTyped] = useState("");
  const fullEmail = "info@eoma.ai";
  useEffect(() => {
    if (active !== 0) {
      setTyped("");
      return;
    }
    let i = 0;
    const t = setInterval(() => {
      i++;
      setTyped(fullEmail.slice(0, i));
      if (i >= fullEmail.length) clearInterval(t);
    }, 80);
    return () => clearInterval(t);
  }, [active]);

  return (
    <section className="how" id="how">
      <Reveal className="how-card-shell">
        <div className="how-card-bg"></div>
        <div className="how-shell-left">
          <span className="eyebrow frost">{t.how.eyebrow}</span>
          <h2 className="how-shell-title">
            <span className="gray">{t.how.ha}</span>
            <br />
            <span className="navy">{t.how.hb} </span>
            <span className="accent">{t.how.hbAccent}</span>
          </h2>
          <p className="how-shell-sub">{t.how.sub}</p>
          <div className="how-shell-tabs">
            {STEPS.map((s, i) => (
              <button
                key={i}
                className={`how-tab ${i === active ? "is-active" : ""}`}
                onClick={() => setActive(i)}
              >
                <span className="how-tab-num">{String(i + 1).padStart(2, "0")}</span>
                <span className="how-tab-name">{s.title}</span>
              </button>
            ))}
          </div>
          <div className="how-shell-foot">{t.how.foot}</div>
        </div>

        <div className="how-shell-right">
          <div className="how-tiles">
            {/* Tile 1 — Set up your brand (Brand + Website wizard steps) */}
            <div
              className={`how-tile ${active === 0 ? "is-active" : ""}`}
              onClick={() => setActive(0)}
            >
              <div className="how-tile-head">
                <span className="how-tile-num">01</span>
                <span className="how-tile-label">{t.how.tile1.label}</span>
              </div>
              <div className="how-tile-body">
                <div className="ht-mock ht-mock-1">
                  <div className="ht-wiz-progress">
                    {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => (
                      <span key={i} className={i <= 1 ? "on" : ""}></span>
                    ))}
                  </div>
                  <div className="ht-wiz-step">{t.how.tile1.wizardStep}</div>
                  <div className="ht-wiz-q">{t.how.tile1.question}</div>
                  <div className="ht-wiz-sub">{t.how.tile1.sub}</div>
                  <div className="ht-wiz-input focus">
                    <span>
                      https://
                      {active === 0 ? typed.replace("info@", "") || "acme.com" : "acme.com"}
                    </span>
                    {active === 0 && typed.length < fullEmail.length && (
                      <span className="cursor"></span>
                    )}
                  </div>
                  <div className="ht-wiz-cta">{t.how.tile1.cta}</div>
                </div>
              </div>
            </div>

            {/* Tile 2 — Pull rival data (Competitor drawer from dashboard) */}
            <div
              className={`how-tile ${active === 1 ? "is-active" : ""}`}
              onClick={() => setActive(1)}
            >
              <div className="how-tile-head">
                <span className="how-tile-num">02</span>
                <span className="how-tile-label">{t.how.tile2.label}</span>
              </div>
              <div className="how-tile-body">
                <div className="ht-mock ht-mock-2">
                  <div className="ht-comp-head">
                    <div className="ht-comp-trophy">🏆</div>
                    <div className="ht-comp-htext">
                      <div className="ht-comp-htitle">{t.how.tile2.title}</div>
                      <div className="ht-comp-hsub">{t.how.tile2.sub}</div>
                    </div>
                  </div>
                  <div className="ht-comp-rank">
                    <span className="ht-comp-rank-num">#2</span>
                    <span className="ht-comp-rank-tot">/ 12</span>
                    <span className="ht-comp-tier ht-tier-comp">{t.how.tile2.tier}</span>
                  </div>
                  <div className="ht-comp-section-label">{t.how.tile2.rivalsLabel}</div>
                  <div className="ht-comp-list">
                    {t.how.tile2.rivals.map((c) => {
                      const brandKind = c.n.split(".")[0];
                      return (
                        <div key={c.n} className="ht-comp-row">
                          <span className="ht-comp-row-name">
                            <span className="ht-comp-row-logo">
                              <PlatformLogo kind={brandKind} size={14} alt={c.n} />
                            </span>
                            {c.n}
                          </span>
                          <span className={`ht-comp-row-badge ht-pos-${c.pos}`}>
                            <span className="ht-comp-row-icon">{c.icon}</span>
                            {c.label}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                  <div className="ht-comp-gaps-label">
                    <span className="ht-warn">⚠</span> {t.how.tile2.gapsLabel}
                  </div>
                  <div className="ht-comp-gaps">
                    {t.how.tile2.gaps.map((g, i) => (
                      <div key={i} className="ht-gap-row">
                        <span className={`ht-gap-sev ${g.sevCls}`}>{g.sev}</span>
                        <span className="ht-gap-kw">{g.kw}</span>
                        <span className={`ht-gap-pres ${g.presCls}`}>{g.pres}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Tile 3 — Visibility climbs */}
            <div
              className={`how-tile ${active === 2 ? "is-active" : ""}`}
              onClick={() => setActive(2)}
            >
              <div className="how-tile-head">
                <span className="how-tile-num">03</span>
                <span className="how-tile-label">{t.how.tile3.label}</span>
              </div>
              <div className="how-tile-body">
                <div className="ht-mock ht-mock-3">
                  <div className="ht-vis-kicker">{t.how.tile3.kicker}</div>
                  <div className="ht-vis-hero">
                    <span
                      className="ht-vis-pct"
                      style={{
                        color: window.__rateToColor ? window.__rateToColor(58.4) : "#D9A93A",
                      }}
                    >
                      <CountUpPct active={active === 2} />
                    </span>
                    <span className="ht-vis-sym">%</span>
                    <span className="ht-vis-delta">{t.how.tile3.deltaTxt}</span>
                  </div>
                  <div className="ht-vis-compare">
                    {[
                      { n: "You", v: 58.4, you: true },
                      { n: "stripe.com", v: 71.2 },
                      { n: "square.com", v: 44.1 },
                      { n: "adyen.com", v: 32.8 },
                    ].map((c) => {
                      const brandKind = c.you ? null : c.n.split(".")[0];
                      return (
                        <div key={c.n} className={`ht-vis-cmp ${c.you ? "you" : ""}`}>
                          <span className="ht-vis-cmp-n">
                            {brandKind && (
                              <span className="ht-vis-cmp-logo">
                                <PlatformLogo kind={brandKind} size={12} alt={c.n} />
                              </span>
                            )}
                            {c.n}
                          </span>
                          <span className="ht-vis-cmp-bar">
                            <span
                              style={{
                                width: `${c.v}%`,
                                background: c.you ? "var(--hue-yellow)" : "rgba(22,30,51,0.25)",
                              }}
                            ></span>
                          </span>
                          <span className="ht-vis-cmp-v">{c.v.toFixed(1)}%</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </div>

            {/* Tile 4 — Execute (Weekly Actions from dashboard) */}
            <div
              className={`how-tile ${active === 3 ? "is-active" : ""}`}
              onClick={() => setActive(3)}
            >
              <div className="how-tile-head">
                <span className="how-tile-num">04</span>
                <span className="how-tile-label">{t.how.tile4.label}</span>
              </div>
              <div className="how-tile-body">
                <div className="ht-mock ht-mock-4">
                  <div className="ht-act-head">
                    <div className="ht-act-htitle">{t.how.tile4.title}</div>
                    <div className="ht-act-streak">{t.how.tile4.streak}</div>
                  </div>
                  <div className="ht-act-progress">
                    <span
                      className="ht-act-pct"
                      style={{
                        color: window.__rateToColor ? window.__rateToColor(62) : "#9BC95E",
                      }}
                    >
                      %62
                    </span>
                    <span className="ht-act-bar">
                      <span
                        className="ht-act-bar-fill"
                        style={{
                          width: "62%",
                          background: window.__rateToColor ? window.__rateToColor(62) : "#9BC95E",
                        }}
                      ></span>
                    </span>
                    <span className="ht-act-count">5/8</span>
                  </div>
                  <div className="ht-act-tabs">
                    {t.how.tile4.tabs.map((tab) => (
                      <span key={tab.l} className={`ht-act-tab ${tab.on ? "on" : ""}`}>
                        {tab.l}
                        <span className="ht-act-tab-c">{tab.c}</span>
                      </span>
                    ))}
                  </div>
                  <div className="ht-act-list">
                    {t.how.tile4.actions.map((a, i) => (
                      <div key={i} className={`ht-act-row ${a.done ? "done" : ""}`}>
                        <span className={`ht-act-check ${a.done ? "on" : ""}`}>
                          {a.done && "✓"}
                        </span>
                        <span className={`ht-act-prio ht-prio-${a.p}`}></span>
                        <span className="ht-act-title">{a.title}</span>
                        <span className="ht-act-eff">{a.eff}</span>
                        <span className={`ht-act-cat ht-cat-${a.catColor}`}>{a.cat}</span>
                        {a.agent && <span className="ht-act-zap">⚡</span>}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Reveal>
    </section>
  );
}

Object.assign(window, { Kinetic, HowItWorks });
