/* Workfloor — Podium-inspired sections (adapted to brand)
   1) VoiceAI  — "Hear it handle a call you'd have missed" (playable call cards)
   2) Integrations — "Connect with the tools you already use" (logo grid)
   ============================================================= */

const { useState: useVS, useEffect: useVE, useRef: useVR } = React;

/* Animated waveform bars (pure CSS heights driven by JS when "playing") */
const Waveform = ({ playing, progress }) => {
  const BARS = 44;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 3, height: 40, flex: 1 }}>
      {Array.from({ length: BARS }).map((_, i) => {
        const seed = (Math.sin(i * 1.7) * 0.5 + 0.5);
        const base = 0.25 + seed * 0.75;
        const passed = i / BARS <= progress;
        return (
          <span key={i} style={{
            flex: 1,
            height: `${(playing ? base : base * 0.55) * 100}%`,
            minHeight: 3,
            borderRadius: 2,
            background: passed ? "var(--wf-amber)" : "rgba(255,255,255,0.16)",
            transformOrigin: "center",
            transition: "height 0.18s ease, background 0.2s ease",
            animation: playing ? `wf-wave 0.9s ease-in-out ${i * 0.02}s infinite` : "none"
          }} />);
      })}
    </div>);
};

const VoiceCallCard = ({ call, active, onPlay }) => {
  const playing = active;
  const [progress, setProgress] = useVS(0);
  const rafRef = useVR(null);

  useVE(() => {
    if (!playing) { setProgress(0); return; }
    let start = null;
    const dur = 7000;
    const step = (t) => {
      if (start === null) start = t;
      const p = Math.min(1, (t - start) / dur);
      setProgress(p);
      if (p < 1) rafRef.current = requestAnimationFrame(step);
      else onPlay(null); // auto-stop at end
    };
    rafRef.current = requestAnimationFrame(step);
    return () => cancelAnimationFrame(rafRef.current);
  }, [playing]);

  const mm = Math.floor((progress * 7));
  const time = `0:0${mm}`;

  return (
    <div className="wf-card-lift" style={{
      background: active ? "#0b1a2a" : "#080f18",
      border: active ? "1px solid rgba(232,147,74,0.4)" : "1px solid rgba(255,255,255,0.06)",
      borderRadius: 14,
      padding: "22px 24px",
      display: "flex",
      flexDirection: "column",
      gap: 16,
      transition: "border-color 0.3s ease, background 0.3s ease"
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <button
          onClick={() => onPlay(active ? null : call.id)}
          aria-label={active ? "Pause" : "Play"}
          style={{
            width: 46, height: 46, borderRadius: "50%", flexShrink: 0,
            background: active ? "var(--wf-amber)" : "rgba(232,147,74,0.14)",
            border: active ? "none" : "1px solid rgba(232,147,74,0.4)",
            color: active ? "#111E2E" : "var(--wf-amber)",
            display: "flex", alignItems: "center", justifyContent: "center",
            cursor: "pointer", transition: "all 0.2s ease"
          }}>
          {active
            ? <svg width="14" height="14" viewBox="0 0 12 12" fill="currentColor"><rect x="2" y="1.5" width="3" height="9" rx="1" /><rect x="7" y="1.5" width="3" height="9" rx="1" /></svg>
            : <svg width="14" height="14" viewBox="0 0 13 13" fill="currentColor"><polygon points="2,1 12,6.5 2,12" /></svg>}
        </button>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 10.5, color: "var(--wf-amber)", fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", fontFamily: "var(--font-display)", marginBottom: 4 }}>{call.tag}</div>
          <div style={{ fontSize: 15, color: "#F5F3EE", fontWeight: 600, fontFamily: "var(--font-display)", letterSpacing: "-0.01em" }}>{call.title}</div>
        </div>
        <span style={{ fontSize: 11, color: "#3d5268", fontFamily: "var(--font-mono)", flexShrink: 0 }}>{active ? time : call.length}</span>
      </div>

      <Waveform playing={playing} progress={progress} />

      <p style={{ fontSize: 13, color: "#9AAABB", lineHeight: 1.6, margin: 0, fontStyle: "italic" }}>
        "{call.line}"
      </p>
    </div>);
};

const VoiceAI = () => {
  const [active, setActive] = useVS(null);
  const ref = useReveal();
  const CALLS = [
    { id: "c1", tag: "After-hours · No heat", title: "Cold emergency → same-day dispatch", length: "0:07", line: "Okay, no heat with a newborn in the house — I'm getting a tech to you tonight. I've got someone who can be there by 8." },
    { id: "c2", tag: "Gas smell", title: "Handles a gas leak, calm and routed", title2: "", length: "0:07", line: "If you smell gas, step outside first — I'll stay with you. I've already flagged this as priority and dispatch has it." },
    { id: "c3", tag: "AC down · 96°", title: "Books an urgent AC repair, no hold", length: "0:07", line: "No hold music, I promise. I've got a 2pm or a 4:30 today — which works better for you?" },
    { id: "c4", tag: "Quote follow-up", title: "Recovers a quote that went cold", length: "0:07", line: "Just circling back on that furnace quote from Tuesday — want me to lock in the install before the weekend rush?" }
  ];

  return (
    <section id="voice" data-screen-label="Voice AI" style={{ background: "var(--wf-navy-deep)", color: "var(--wf-text-warm)", position: "relative", overflow: "hidden" }}>
      <div className="wf-grid-bg" style={{ position: "absolute", inset: 0, opacity: 0.35, pointerEvents: "none" }} aria-hidden />
      <div className="wf-glow" style={{ position: "absolute", width: 600, height: 600, background: "rgba(232,147,74,0.05)", top: "-15%", right: "-5%", pointerEvents: "none" }} aria-hidden />
      <div className="wf-container" style={{ position: "relative" }}>
        <div ref={ref} className="wf-reveal" style={{ maxWidth: 720, marginBottom: 52 }}>
          <p className="eyebrow">Hear it work</p>
          <h2 style={{ fontSize: "clamp(32px, 4.6vw, 52px)", color: "var(--wf-text-warm)", margin: 0, lineHeight: 1.05, letterSpacing: "-0.03em", fontWeight: 500 }}>
            Hear it handle a call <span style={{ color: "var(--wf-amber)", fontStyle: "italic" }}>you'd have missed.</span>
          </h2>
          <p style={{ fontSize: 16, color: "var(--wf-slate-300)", marginTop: 18, lineHeight: 1.65, maxWidth: 560 }}>
            Real scenarios, handled in your voice — capturing the issue, calming the customer, and getting a tech on the way without a transfer or a hold.
          </p>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16 }}>
          {CALLS.map(c => (
            <VoiceCallCard key={c.id} call={c} active={active === c.id} onPlay={setActive} />
          ))}
        </div>
      </div>
    </section>);
};

/* ---------------- INTEGRATIONS — "Connect with the tools you already use" ---------------- */
const Integrations = () => {
  const ref = useReveal();
  const TOOLS = [
    "Jobber", "HouseCall Pro", "ServiceTitan",
    "QuickBooks", "Calendly", "Stripe",
    "Twilio", "FieldEdge", "+ many more"
  ];
  return (
    <section data-screen-label="Integrations" style={{ background: "var(--wf-cream)" }}>
      <div className="wf-container">
        <div ref={ref} className="wf-reveal wf-int-grid-2" style={{ display: "grid", gridTemplateColumns: "0.9fr 1.1fr", gap: 64, alignItems: "center" }}>
          <div>
            <p className="eyebrow">Integrations</p>
            <h2 style={{ fontSize: "clamp(30px, 4vw, 46px)", margin: 0, lineHeight: 1.08, letterSpacing: "-0.03em", fontWeight: 500 }}>
              Connect the tools you <span style={{ color: "var(--wf-amber)", fontStyle: "italic" }}>already run on.</span>
            </h2>
            <p style={{ fontSize: 16, color: "var(--wf-slate-400)", lineHeight: 1.7, margin: "20px 0 28px", maxWidth: 420 }}>
              We build on top of your existing stack — your CRM, your scheduler, your phones. Nothing to rip out, nothing new to learn.
            </p>
            <a href="contact.html" className="wf-pill" style={{ padding: "12px 26px", fontSize: 14 }}>
              <svg width={11} height={11} viewBox="0 0 13 13" fill="#111E2E" aria-hidden><polygon points="2,1 12,6.5 2,12" /></svg>
              Watch a demo
            </a>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
            {TOOLS.map(t => {
              const isMore = t === "+ many more";
              return (
              <div key={t} className="wf-int-tile" style={{
                background: isMore ? "rgba(232,147,74,0.1)" : "#fff",
                border: isMore ? "1px solid rgba(232,147,74,0.4)" : "1px solid var(--wf-border-cream)",
                borderRadius: 12,
                aspectRatio: "1.6 / 1",
                display: "flex", alignItems: "center", justifyContent: "center",
                padding: 10, textAlign: "center",
                fontSize: 13, fontWeight: 600, color: isMore ? "var(--wf-amber)" : "var(--wf-slate-500)",
                fontFamily: "var(--font-display)", letterSpacing: "-0.01em",
                transition: "transform 0.25s ease, box-shadow 0.25s ease, border-color 0.25s ease"
              }}>
                {t}
              </div>);
            })}
          </div>
        </div>
      </div>
    </section>);
};

Object.assign(window, { VoiceAI, Integrations });
