// Voice agent demo — auto-plays on scroll into view (muted by default).
// Audio uses pre-recorded M4A files (Ava Premium = Samika, Alex = Patient)
// so every visitor hears the exact same voices regardless of their device.

const SAMPLE_CALLS = {
  primary: [
    { who: "kiko",    t: "Hi, this is Samika at Westpark Internal Medicine. How can I help you today?",                          audio: "audio/kiko_p1.m4a" },
    { who: "patient", t: "I'd like to schedule an appointment. I've been feeling really tired for a few weeks.",               audio: "audio/patient_p1.m4a" },
    { who: "kiko",    t: "I'm sorry to hear that. Are you a current patient with Dr. Patel, or would this be a new visit?",    audio: "audio/kiko_p2.m4a" },
    { who: "patient", t: "I'd be a new patient.",                                                                               audio: "audio/patient_p2.m4a" },
    { who: "kiko",    t: "Got it. A few quick questions so I can share this with the doctor — has the fatigue affected your daily activities?", audio: "audio/kiko_p3.m4a" },
    { who: "patient", t: "Yeah, I'm tired by mid-afternoon most days.",                                                         audio: "audio/patient_p3.m4a" },
    { who: "kiko",    t: "Thanks for sharing that. Any prior care for this — have you seen anyone about it before?",            audio: "audio/kiko_p4.m4a" },
    { who: "patient", t: "Not yet.",                                                                                            audio: "audio/patient_p4.m4a" },
    { who: "kiko",    t: "I'll share all of this with Dr. Patel and call you back within the hour with a confirmed time.",      audio: "audio/kiko_p5.m4a" },
    { who: "system",  t: "Doctor approval received in 24s · Tuesday 2:30 PM offered · confirmed via SMS" },
  ],
  dental: [
    { who: "kiko",    t: "Thanks for calling Magnolia Dental. This is Samika — how can I help?",                                 audio: "audio/kiko_d1.m4a" },
    { who: "patient", t: "I think I need an implant. My dentist mentioned it last month.",                                     audio: "audio/patient_d1.m4a" },
    { who: "kiko",    t: "Happy to set up an implant consult. Which tooth are we looking at?",                                 audio: "audio/kiko_d2.m4a" },
    { who: "patient", t: "Lower left, the back one.",                                                                          audio: "audio/patient_d2.m4a" },
    { who: "kiko",    t: "Got it — molar nineteen. Do you have any imaging from your previous dentist we should request?",     audio: "audio/kiko_d3.m4a" },
    { who: "patient", t: "Yes, X-rays from about a month ago.",                                                                audio: "audio/patient_d3.m4a" },
    { who: "kiko",    t: "I'll note that. I have Thursday at ten AM or Friday at three fifteen with Dr. Chen — which works better for you?", audio: "audio/kiko_d4.m4a" },
    { who: "patient", t: "Thursday works.",                                                                                    audio: "audio/patient_d4.m4a" },
    { who: "system",  t: "Booked in Dentrix · SMS confirmation sent · imaging request flagged for office" },
  ],
};

// Estimate visual pacing for muted mode (ms) — mirrors natural speech rhythm
function estimateDuration(text) {
  return Math.max((text.trim().split(/\s+/).length / 2.4) * 1000 + 350, 1100);
}

// ── Waveform bars ─────────────────────────────────────────────────────────────
function WaveformBars({ active }) {
  return (
    <div className="vd__wave" aria-hidden>
      {Array.from({ length: 20 }, (_, i) => (
        <span key={i} style={{
          animationDelay:     `${(i * 80) % 1000}ms`,
          animationDuration:  `${700 + ((i * 97) % 500)}ms`,
          opacity:            active ? 1 : 0.25,
          animationPlayState: active ? "running" : "paused",
        }} />
      ))}
    </div>
  );
}

// ── Main component ─────────────────────────────────────────────────────────────
function VoiceDemo() {
  const [tab,     setTab]     = React.useState("primary");
  const [playing, setPlaying] = React.useState(false);
  const [shown,   setShown]   = React.useState(0);
  const [unmuted, setUnmuted] = React.useState(false);

  const sectionRef = React.useRef(null);
  const timerRef   = React.useRef(null);
  const audioRef   = React.useRef(null);

  const lines    = SAMPLE_CALLS[tab];
  const progress = lines.length ? Math.min(shown / lines.length, 1) : 0;

  // No autoplay — user must click Play call to start.

  // ── Core playback engine ──────────────────────────────────────────────────
  // Plays lines one at a time. When unmuted: Audio file drives timing (onended).
  // When muted: estimated-duration timer drives timing.
  const stopAll = () => {
    clearTimeout(timerRef.current);
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.onended = null;
      audioRef.current = null;
    }
  };

  const playFrom = React.useCallback((idx) => {
    stopAll();
    if (idx >= lines.length) { setPlaying(false); setUnmuted(false); return; }

    setShown(idx + 1);
    const line = lines[idx];

    const advance = () => playFrom(idx + 1);

    if (unmuted && line.audio) {
      const audio = new Audio(line.audio);
      audioRef.current = audio;
      audio.onended = () => {
        const pause = line.who === "kiko" ? 380 : 520;
        timerRef.current = setTimeout(advance, pause);
      };
      audio.onerror = () => timerRef.current = setTimeout(advance, 400);
      audio.play().catch(() => timerRef.current = setTimeout(advance, estimateDuration(line.t)));
    } else {
      const delay = line.who === "system" ? 2800 : estimateDuration(line.t);
      timerRef.current = setTimeout(advance, delay);
    }
  }, [lines, unmuted]); // eslint-disable-line react-hooks/exhaustive-deps

  // ── Start / reset when playing or tab changes ─────────────────────────────
  React.useEffect(() => {
    setShown(0);
    stopAll();
    if (!playing) return;
    timerRef.current = setTimeout(() => playFrom(0), 700);
    return stopAll;
  }, [playing, tab]); // eslint-disable-line react-hooks/exhaustive-deps

  // ── Unmute toggle: restart current audio from beginning of current line ───
  const shownRef = React.useRef(shown);
  React.useEffect(() => { shownRef.current = shown; }, [shown]);

  React.useEffect(() => {
    if (!playing) return;
    stopAll();
    const idx = Math.max(0, shownRef.current - 1);
    timerRef.current = setTimeout(() => playFrom(idx), 80);
  }, [unmuted]); // eslint-disable-line react-hooks/exhaustive-deps

  // ── Controls ──────────────────────────────────────────────────────────────
  const handleTabSwitch = (t) => {
    stopAll();
    setTab(t);
    setPlaying(false);
    setShown(0);
    setUnmuted(false);
  };

  const handlePlayToggle = () => {
    if (playing) {
      stopAll();
      setPlaying(false);
    } else {
      setShown(0);
      setUnmuted(true);  // explicit Play click → start with audio on
      setPlaying(true);
    }
  };

  const visibleLines = lines.slice(0, shown);

  return (
    <section className="vd section section--paper" id="demo" ref={sectionRef}>
      <div className="container">
        <div className="vd__head">
          <span className="eyebrow">Hear it for yourself</span>
          <h2 className="display h-lg">A real call, <span className="serif">end to end.</span></h2>
        </div>

        <div className="vd__panel">
          {/* ── Chrome bar ── */}
          <div className="vd__chrome">
            <div className="vd__chrome-left">
              <WaveformBars active={playing} />
              <div className="vd__tabs">
                <button className={`vd__tab ${tab === "primary" ? "on" : ""}`} onClick={() => handleTabSwitch("primary")}>Primary care · new patient</button>
                <button className={`vd__tab ${tab === "dental"  ? "on" : ""}`} onClick={() => handleTabSwitch("dental")}>Dental · implant consult</button>
              </div>
            </div>
            <div className="vd__chrome-right">
              {playing && (
                <button
                  className={`vd__unmute ${unmuted ? "vd__unmute--on" : ""}`}
                  onClick={() => setUnmuted(u => !u)}
                  title={unmuted ? "Mute" : "Tap to unmute"}
                >
                  <span className="vd__unmute-icon">{unmuted ? "🔊" : "🔇"}</span>
                  {unmuted ? "Mute" : "Tap to unmute"}
                </button>
              )}
              <button className="vd__play" onClick={handlePlayToggle}>
                <span className="vd__play-icon">{playing ? "❙❙" : "▶"}</span>
                {playing ? "Pause" : "Play call"}
              </button>
            </div>
          </div>

          {/* ── Progress bar ── */}
          <div className="vd__progress-track">
            <div className="vd__progress-fill" style={{ width: (progress * 100) + "%" }} />
          </div>

          {/* ── Call meta + transcript ── */}
          <div className="vd__call">
            <div className="vd__meta">
              <div><span className="eyebrow">Caller</span><div>+1 (312) 555-0119</div></div>
              <div><span className="eyebrow">Time</span><div>10:47 PM · Tue</div></div>
              <div><span className="eyebrow">Duration</span><div>3m 12s</div></div>
              <div><span className="eyebrow">Outcome</span><div style={{ color: "#7CC7A1" }}>Booked ✓</div></div>
            </div>

            <div className="vd__transcript">
              {!playing && shown === 0 && (
                <div className="vd__idle">
                  <div className="vd__idle-icon">▶</div>
                  <div className="vd__idle-text">Hit Play call to hear a real conversation</div>
                </div>
              )}
              {visibleLines.map((l, i) => (
                <div key={i} className={`vd__line vd__line--${l.who}`}>
                  <span className="vd__who">
                    {l.who === "kiko" ? "Samika" : l.who === "patient" ? "Patient" : "System"}
                  </span>
                  <span className="vd__t">{l.t}</span>
                </div>
              ))}
              {playing && shown < lines.length && (
                <div className="vd__typing"><span /><span /><span /></div>
              )}
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .vd__head { margin-bottom: 48px; }
        .vd__head h2 { margin: 12px 0 0; }

        .vd__panel {
          background: var(--ink-900); color: var(--cream-100);
          border-radius: var(--radius-lg); overflow: hidden;
        }

        .vd__chrome {
          display: flex; justify-content: space-between; align-items: center;
          padding: 16px 20px; border-bottom: 1px solid rgba(247,241,228,0.1);
          flex-wrap: wrap; gap: 12px;
        }
        .vd__chrome-left  { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
        .vd__chrome-right { display: flex; align-items: center; gap: 10px; }

        .vd__wave { display: flex; gap: 2.5px; align-items: center; height: 28px; flex-shrink: 0; }
        .vd__wave span {
          display: block; width: 2.5px; border-radius: 2px;
          background: #7CC7A1; height: 30%;
          animation: vdBar 0.9s ease-in-out infinite alternate;
        }
        @keyframes vdBar { from { height: 15%; } to { height: 88%; } }

        .vd__tabs { display: flex; gap: 4px; }
        .vd__tab {
          background: transparent; border: 0; color: rgba(247,241,228,0.5);
          padding: 7px 13px; border-radius: var(--radius-pill);
          font-family: inherit; font-size: 13px; cursor: pointer; transition: all .2s;
        }
        .vd__tab:hover { color: rgba(247,241,228,0.8); }
        .vd__tab.on { background: rgba(247,241,228,0.1); color: var(--cream-100); }

        .vd__unmute {
          display: inline-flex; align-items: center; gap: 6px;
          background: rgba(247,241,228,0.08); border: 1px solid rgba(247,241,228,0.16);
          color: rgba(247,241,228,0.7); padding: 8px 14px; border-radius: var(--radius-pill);
          font-family: inherit; font-size: 12.5px; cursor: pointer; transition: all .2s;
        }
        .vd__unmute:hover { background: rgba(247,241,228,0.13); color: var(--cream-100); }
        .vd__unmute--on { background: rgba(124,199,161,0.15); border-color: rgba(124,199,161,0.35); color: #7CC7A1; }
        .vd__unmute-icon { font-size: 13px; }

        .vd__play {
          background: var(--cream-100); color: var(--ink-900); border: 0;
          padding: 9px 18px; border-radius: var(--radius-pill);
          font-family: inherit; font-size: 13.5px; font-weight: 500; cursor: pointer;
          display: inline-flex; align-items: center; gap: 8px; transition: opacity .15s;
        }
        .vd__play:hover { opacity: 0.88; }
        .vd__play-icon { font-size: 10px; }

        .vd__progress-track { height: 2px; background: rgba(247,241,228,0.08); }
        .vd__progress-fill  { height: 100%; background: #7CC7A1; transition: width 0.5s ease-out; }

        .vd__call { padding: 32px 40px 40px; }
        .vd__meta {
          display: grid; grid-template-columns: repeat(4, 1fr); gap: 24px;
          padding-bottom: 24px; border-bottom: 1px solid rgba(247,241,228,0.1); margin-bottom: 28px;
        }
        .vd__meta > div > div { font-size: 14px; margin-top: 4px; color: var(--cream-100); }
        .vd__meta .eyebrow { color: rgba(247,241,228,0.4); }

        .vd__idle {
          display: flex; flex-direction: column; align-items: center; gap: 12px;
          padding: 60px 0; color: rgba(247,241,228,0.3);
        }
        .vd__idle-icon { font-size: 28px; opacity: 0.5; }
        .vd__idle-text {
          font-family: var(--font-mono); font-size: 11px;
          letter-spacing: 0.12em; text-transform: uppercase;
        }

        .vd__transcript { min-height: 280px; display: flex; flex-direction: column; gap: 16px; }
        .vd__line { display: flex; gap: 16px; opacity: 0; animation: lineIn .35s ease-out forwards; }
        @keyframes lineIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); } }
        .vd__who {
          font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.14em;
          text-transform: uppercase; color: rgba(247,241,228,0.4);
          padding-top: 4px; min-width: 68px; flex-shrink: 0;
        }
        .vd__line--kiko .vd__who { color: #7CC7A1; }
        .vd__t { font-size: 15.5px; line-height: 1.55; flex: 1; max-width: 62ch; }
        .vd__line--system .vd__t {
          font-family: var(--font-mono); font-size: 11.5px; letter-spacing: 0.04em;
          color: rgba(247,241,228,0.5); padding: 8px 12px;
          background: rgba(247,241,228,0.05); border-radius: 6px;
        }

        .vd__typing { display: flex; gap: 4px; padding: 6px 0 0 84px; }
        .vd__typing span {
          width: 5px; height: 5px; border-radius: 50%;
          background: rgba(247,241,228,0.35); animation: vdBounce 1.2s infinite;
        }
        .vd__typing span:nth-child(2) { animation-delay: .15s; }
        .vd__typing span:nth-child(3) { animation-delay: .3s; }
        @keyframes vdBounce {
          0%,80%,100% { transform: translateY(0); opacity: .35; }
          40%          { transform: translateY(-5px); opacity: 1; }
        }

        @media (max-width: 700px) {
          .vd__meta  { grid-template-columns: 1fr 1fr; }
          .vd__call  { padding: 20px; }
          .vd__chrome { flex-direction: column; align-items: flex-start; }
        }
      `}</style>
    </section>
  );
}
window.VoiceDemo = VoiceDemo;
