// demo.jsx — Live call demo widget. Reused in hero + main demo section.

const { useState, useEffect, useRef, useMemo } = React;

// Deterministic-ish pseudo-random for stable waveform shapes per dialect.
function seededWave(seed, n = 40) {
  let s = seed * 9301 + 49297;
  const out = [];
  for (let i = 0; i < n; i++) {
    s = (s * 9301 + 49297) % 233280;
    out.push(0.18 + (s / 233280) * 0.82);
  }
  return out;
}

// Live waveform bars that pulse when "active"
function Waveform({ active, color = "#DA291C", barCount = 28, seed = 1, h = 36 }) {
  const base = useMemo(() => seededWave(seed, barCount), [seed, barCount]);
  const [tick, setTick] = useState(0);
  useEffect(() => {
    if (!active) return;
    const id = setInterval(() => setTick(t => t + 1), 90);
    return () => clearInterval(id);
  }, [active]);
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 3, height: h,
    }}>
      {base.map((b, i) => {
        const phase = (i + tick) * 0.55;
        const live = active ? 0.55 + 0.45 * Math.abs(Math.sin(phase)) : 0.18;
        const height = Math.max(3, b * live * h);
        return (
          <div key={i} style={{
            width: 2.5,
            height,
            background: active ? color : "#3a3a36",
            borderRadius: 2,
            transition: "height 90ms linear, background 180ms",
          }} />
        );
      })}
    </div>
  );
}

// Typewriter line — animates into existence over `ms` then resolves
function useTypewriter(text, ms, onDone) {
  const [shown, setShown] = useState("");
  useEffect(() => {
    if (!text) return;
    setShown("");
    let i = 0;
    const step = Math.max(15, ms / Math.max(1, text.length));
    const id = setInterval(() => {
      i++;
      setShown(text.slice(0, i));
      if (i >= text.length) {
        clearInterval(id);
        onDone && setTimeout(onDone, 600);
      }
    }, step);
    return () => clearInterval(id);
  }, [text, ms]);
  return shown;
}

function TranscriptLine({ turn, isActive, onDone, idx }) {
  const ms = Math.min(2200, turn.t.length * 28);
  const shown = isActive ? useTypewriter(turn.t, ms, onDone) : turn.t;
  const ai = turn.who === "ai";
  return (
    <div style={{
      display: "flex", gap: 12, padding: "10px 0",
      borderTop: idx === 0 ? "none" : "1px solid #1f1f1f",
      opacity: isActive ? 1 : 0.55,
      transition: "opacity 300ms",
    }}>
      <div style={{
        flexShrink: 0, width: 56,
        fontFamily: "Geist Mono, ui-monospace, monospace",
        fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase",
        color: ai ? "#DA291C" : "#8a8a85",
        paddingTop: 3,
      }}>
        {ai ? "HELVOX" : "Caller"}
      </div>
      <div style={{
        flex: 1, color: ai ? "#f5f5f1" : "#c8c8c2",
        fontSize: 14.5, lineHeight: 1.55,
        fontWeight: ai ? 500 : 400,
        fontFamily: "Geist, ui-sans-serif, system-ui, sans-serif",
      }}>
        {shown}
        {isActive && shown.length < turn.t.length && (
          <span style={{ display: "inline-block", width: 8, height: 14, background: ai ? "#DA291C" : "#8a8a85", marginLeft: 2, verticalAlign: "middle", animation: "blink 0.8s steps(2) infinite" }} />
        )}
      </div>
    </div>
  );
}

function LeadCard({ card, caller, number, city, visible }) {
  return (
    <div style={{
      opacity: visible ? 1 : 0,
      transform: visible ? "translateY(0)" : "translateY(12px)",
      transition: "opacity 600ms ease, transform 600ms ease",
      background: "#0e0e0e",
      border: "1px solid #262624",
      borderRadius: 12,
      padding: 18,
      fontFamily: "Geist, ui-sans-serif, system-ui",
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 14, paddingBottom: 12, borderBottom: "1px solid #1f1f1f",
      }}>
        <div style={{
          fontFamily: "Geist Mono, monospace", fontSize: 10,
          letterSpacing: "0.12em", textTransform: "uppercase", color: "#8a8a85",
        }}>
          Lead-Karte · #LD-{Math.floor(7000 + (caller || "").length * 137).toString().padStart(4, "0")}
        </div>
        <div style={{
          fontFamily: "Geist Mono, monospace", fontSize: 10,
          color: "#d2f24a", display: "flex", alignItems: "center", gap: 6,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: "#d2f24a", boxShadow: "0 0 8px #d2f24a" }} />
          ERFASST
        </div>
      </div>

      <div style={{ marginBottom: 12 }}>
        <div style={{ color: "#f5f5f1", fontSize: 17, fontWeight: 600 }}>{caller}</div>
        <div style={{ color: "#8a8a85", fontSize: 13, fontFamily: "Geist Mono, monospace", marginTop: 2 }}>{number} · {city}</div>
      </div>

      <Row label="Anliegen" value={card.intent} />
      <Row label="Dringlichkeit" value={card.urgency} accent={card.urgency === "Hoch" ? "#DA291C" : "#f5f5f1"} />
      <Row label="Termin" value={card.time} />
      <Row label="Aktion" value={card.action} />

      <div style={{
        marginTop: 14, display: "flex", flexWrap: "wrap", gap: 6,
      }}>
        {card.tags.map(tag => (
          <span key={tag} style={{
            fontFamily: "Geist Mono, monospace", fontSize: 10,
            padding: "3px 8px", border: "1px solid #2a2a26", borderRadius: 999,
            color: "#8a8a85", letterSpacing: "0.04em",
          }}>{tag}</span>
        ))}
      </div>
    </div>
  );
}

function Row({ label, value, accent = "#f5f5f1" }) {
  return (
    <div style={{ display: "flex", gap: 12, padding: "6px 0", alignItems: "baseline" }}>
      <div style={{
        flexShrink: 0, width: 92,
        fontFamily: "Geist Mono, monospace", fontSize: 10,
        textTransform: "uppercase", letterSpacing: "0.08em", color: "#666660",
      }}>{label}</div>
      <div style={{ color: accent, fontSize: 13.5, fontWeight: 500 }}>{value}</div>
    </div>
  );
}

// Main demo widget. Auto-plays a call, loops, can switch industry.
function LiveCallDemo({ industry, onIndustryChange, compact = false }) {
  const data = window.HELVOX_DATA;
  const scripts = data.scripts;
  const demoAudioSrc = data.demoAudioSrc;
  const keys = Object.keys(scripts);
  const script = scripts[industry] || scripts.sanitaer;
  const demoVoiceLabel = data.demoVoiceLabel || script.dialect;
  const audioRef = useRef(null);

  const [step, setStep] = useState(-1); // -1 = ringing
  const [latency, setLatency] = useState(412);
  const [audioPlaying, setAudioPlaying] = useState(false);
  const cardVisible = step >= script.turns.length - 1;

  const toggleAudio = () => {
    const audio = audioRef.current;
    if (!audio || !demoAudioSrc) return;

    if (audioPlaying) {
      audio.pause();
      audio.currentTime = 0;
      setAudioPlaying(false);
      return;
    }

    audio.currentTime = 0;
    setAudioPlaying(true);
    const playPromise = audio.play();
    if (playPromise && typeof playPromise.catch === "function") {
      playPromise.catch(() => setAudioPlaying(false));
    }
  };

  // Reset when industry changes
  useEffect(() => {
    setStep(-1);
    const ringT = setTimeout(() => setStep(0), 1500);
    return () => clearTimeout(ringT);
  }, [industry]);

  // Step advancer (called from each line's onDone)
  const advance = () => {
    setStep(s => {
      if (s >= script.turns.length - 1) {
        return s;
      }
      return s + 1;
    });
  };

  // Live-ish latency jitter
  useEffect(() => {
    const id = setInterval(() => {
      setLatency(380 + Math.floor(Math.random() * 90));
    }, 700);
    return () => clearInterval(id);
  }, []);

  useEffect(() => {
    return () => {
      if (audioRef.current) audioRef.current.pause();
    };
  }, []);

  const aiTalking = step >= 0 && step < script.turns.length && script.turns[step].who === "ai";
  const callerTalking = step >= 0 && step < script.turns.length && script.turns[step].who === "caller";

  return (
    <div style={{
      background: "#0c0c0c",
      border: "1px solid #1f1f1f",
      borderRadius: 16,
      overflow: "hidden",
      fontFamily: "Geist, ui-sans-serif, system-ui",
    }}>
      {/* Top bar */}
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "12px 16px", borderBottom: "1px solid #1f1f1f",
        background: "#0a0a0a",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            width: 8, height: 8, borderRadius: 999,
            background: "#DA291C", boxShadow: "0 0 12px #DA291C",
            animation: "pulse 1.2s ease-in-out infinite",
          }} />
          <span style={{
            fontFamily: "Geist Mono, monospace", fontSize: 10,
            letterSpacing: "0.14em", textTransform: "uppercase", color: "#f5f5f1",
          }}>Live · eingehender Anruf</span>
        </div>
        <div style={{
          fontFamily: "Geist Mono, monospace", fontSize: 10,
          letterSpacing: "0.1em", color: "#8a8a85",
          display: "flex", alignItems: "center", gap: 10,
        }}>
          <button
            type="button"
            onClick={toggleAudio}
            disabled={!demoAudioSrc}
            style={{
              padding: "7px 10px", borderRadius: 6,
              border: `1px solid ${audioPlaying ? "#DA291C" : "#2a2a26"}`,
              background: audioPlaying ? "transparent" : "#141414",
              color: audioPlaying ? "#DA291C" : "#f5f5f1",
              cursor: demoAudioSrc ? "pointer" : "not-allowed",
              fontFamily: "Geist Mono, monospace", fontSize: 10,
              letterSpacing: "0.08em", whiteSpace: "nowrap",
            }}
          >
            {audioPlaying ? "■ TON" : "▶ TON"}
          </button>
          <span>{demoVoiceLabel.toUpperCase()} · {latency}MS</span>
        </div>
      </div>

      <audio
        ref={audioRef}
        src={demoAudioSrc}
        preload="auto"
        onEnded={() => setAudioPlaying(false)}
        onPause={() => setAudioPlaying(false)}
      />

      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        gap: 12, flexWrap: "wrap",
        padding: "12px 16px", borderBottom: "1px solid #1f1f1f",
        background: "#090909",
      }}>
        <span style={{
          color: "#c8c8c2", fontSize: 13.5, lineHeight: 1.5,
        }}>
          Glauben Sie nicht, dass diese Stimme KI-generiert ist?
        </span>
        <a
          href="/julia-demo.html"
          aria-label="Julia Demo öffnen"
          style={{
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            padding: "7px 11px", borderRadius: 6,
            border: "1px solid #2a2a26", background: "#111111",
            color: "#f5f5f1", textDecoration: "none",
            fontFamily: "Geist Mono, monospace", fontSize: 10,
            letterSpacing: "0.08em", textTransform: "uppercase",
            whiteSpace: "nowrap",
          }}
        >
          Fragen Sie Julia etwas
        </a>
      </div>

      {/* Industry switcher */}
      {onIndustryChange && (
        <div style={{
          display: "flex", gap: 0, overflowX: "auto", scrollbarWidth: "none",
          borderBottom: "1px solid #1f1f1f", background: "#0a0a0a",
        }}>
          {keys.map(k => (
            <button key={k} onClick={() => onIndustryChange(k)} style={{
              flex: 1, minWidth: 90, padding: "10px 14px",
              background: industry === k ? "#141414" : "transparent",
              border: "none", borderRight: "1px solid #1f1f1f",
              color: industry === k ? "#f5f5f1" : "#8a8a85",
              fontFamily: "Geist Mono, monospace", fontSize: 11,
              letterSpacing: "0.04em", textTransform: "uppercase",
              cursor: "pointer", whiteSpace: "nowrap",
            }}>
              {scripts[k].label}
            </button>
          ))}
        </div>
      )}

      <div style={{
        display: "grid",
        gridTemplateColumns: compact ? "1fr" : "1.3fr 1fr",
        gap: 0,
      }}>
        {/* Left: caller + transcript */}
        <div style={{
          padding: 18, borderRight: compact ? "none" : "1px solid #1f1f1f",
          minHeight: compact ? 380 : 420,
        }}>
          {/* Caller card */}
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            paddingBottom: 14, marginBottom: 14, borderBottom: "1px solid #1f1f1f",
          }}>
            <div>
              <div style={{ color: "#f5f5f1", fontSize: 15, fontWeight: 600 }}>{script.caller}</div>
              <div style={{ color: "#8a8a85", fontSize: 12, fontFamily: "Geist Mono, monospace" }}>{script.number}</div>
            </div>
            <Waveform active={callerTalking} color="#8a8a85" seed={script.caller.length} h={28} />
          </div>

          {/* AI waveform */}
          <div style={{
            display: "flex", alignItems: "center", gap: 10, padding: "10px 12px",
            background: "#0a0a0a", borderRadius: 8, marginBottom: 10,
            border: "1px solid #1a1a1a",
          }}>
            <div style={{
              fontFamily: "Geist Mono, monospace", fontSize: 10,
              letterSpacing: "0.1em", color: "#DA291C", flexShrink: 0,
            }}>HELVOX →</div>
            <Waveform active={aiTalking} color="#DA291C" seed={11} h={22} barCount={36} />
          </div>

          {/* Transcript */}
          <div style={{
            maxHeight: 260, overflowY: "hidden",
          }}>
            {step < 0 ? (
              <div style={{
                color: "#666660", fontSize: 13, fontFamily: "Geist Mono, monospace",
                padding: "30px 0", textAlign: "center", letterSpacing: "0.1em",
              }}>
                ◐ Verbindung wird aufgebaut…
              </div>
            ) : (
              script.turns.slice(0, step + 1).map((turn, i) => (
                <TranscriptLine
                  key={`${industry}-${i}`}
                  turn={turn}
                  isActive={i === step}
                  onDone={i === step ? advance : undefined}
                  idx={i}
                />
              ))
            )}
          </div>
        </div>

        {/* Right: lead card */}
        {!compact && (
          <div style={{ padding: 18, background: "#080808" }}>
            <LeadCard
              card={script.card}
              caller={script.caller}
              number={script.number}
              city={script.city}
              visible={cardVisible}
            />

            {!cardVisible && (
              <div style={{
                marginTop: 18, padding: "16px 14px",
                fontFamily: "Geist Mono, monospace", fontSize: 11,
                color: "#666660", letterSpacing: "0.06em", lineHeight: 1.8,
              }}>
                <div>⏵ STT-Stream aktiv</div>
                <div>⏵ Dialekt: {script.dialect}</div>
                <div>⏵ Intent-Klassifikator: läuft</div>
                <div>⏵ Lead-Extraktion: läuft</div>
                <div style={{ color: "#444", marginTop: 8 }}>Karte erscheint nach Gesprächsende.</div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

window.LiveCallDemo = LiveCallDemo;
window.Waveform = Waveform;
