/* TryIt — interactive demo block.
   Voice agent picker (gender × accent × language) + fake call UI w/ animated waveform.
   WhatsApp-style text demo wired to window.claude.complete. */

const VOICE_OPTIONS = [
  { id: "layla",  name: "Layla",   gender: "female", accent: "en-GB",  flag: "🇬🇧", desc: "British English · warm, professional" },
  { id: "amira",  name: "Amira",   gender: "female", accent: "ar-AE",  flag: "🇦🇪", desc: "Emirati Arabic · friendly", status: "renovating" },
  { id: "james",  name: "James",   gender: "male",   accent: "en-GB",  flag: "🇬🇧", desc: "British English · confident, dry", status: "renovating" },
  { id: "ethan",  name: "Ethan",   gender: "male",   accent: "en-US",  flag: "🇺🇸", desc: "American English · direct, modern", status: "renovating" },
  { id: "priya",  name: "Priya",   gender: "female", accent: "en-IN",  flag: "🇮🇳", desc: "Indian English · clear, courteous", status: "renovating" },
];

const STATUS_LABEL = {
  "maintenance": { en: "In maintenance",  ar: "قيد الصيانة" },
  "renovating":  { en: "Renovating",      ar: "قيد التجديد" },
  "in-progress": { en: "In progress",     ar: "قيد التنفيذ" },
};

const LANGUAGES = [
  "Arabic", "English", "Hindi", "Urdu", "Russian", "French", "German",
  "Mandarin", "Farsi", "Tagalog", "Spanish", "Portuguese", "Italian",
  "Turkish", "Japanese", "Korean", "Dutch", "Swedish", "Polish", "Greek",
  "Hebrew", "Thai", "Vietnamese", "Indonesian", "Malay",
];

/* ===== Animated waveform ===== */
const Waveform = ({ active, accent }) => {
  const bars = 48;
  return (
    <div className="wave" data-active={active}>
      {Array.from({ length: bars }).map((_, i) => (
        <span
          key={i}
          className="wave-bar"
          style={{
            animationDelay: `${(i % 12) * 0.06}s`,
            background: accent || "var(--accent)",
          }}
        />
      ))}
      <style>{`
        .wave {
          display: flex;
          align-items: center;
          gap: 3px;
          height: 64px;
          width: 100%;
        }
        .wave-bar {
          flex: 1;
          height: 6px;
          border-radius: 2px;
          background: var(--accent);
          opacity: .35;
          transition: height .3s var(--ease);
        }
        .wave[data-active="true"] .wave-bar {
          animation: waveBar 1.1s var(--ease) infinite;
          opacity: 1;
        }
        @keyframes waveBar {
          0%, 100% { height: 6px; }
          25% { height: 38px; }
          50% { height: 14px; }
          75% { height: 50px; }
        }
      `}</style>
    </div>
  );
};

/* ===== Retell wiring config =====
   1. Deploy the Cloudflare Worker in ./worker (wrangler deploy)
   2. Replace RETELL_TOKEN_ENDPOINT below with the Worker's public URL
   3. Fill AGENT_MAP with your Retell agent IDs.
      Single-agent mode: leave only `default` filled — every voice in the
      picker routes to that one agent (picker becomes cosmetic).
      Per-voice agents: add an entry per voiceId for distinct voices.
   The Retell Web SDK script tag must be loaded in Wastafy.html. */
const RETELL_TOKEN_ENDPOINT = "https://wastafy-api.wastafy.workers.dev/api/retell/web-call";
const AGENT_MAP = {
  default: "agent_de9f6d0e59071919c62950f011",
  // layla:  "agent_xxx",
  // amira:  "agent_xxx",
  // james:  "agent_xxx",
  // ethan:  "agent_xxx",
  // priya:  "agent_xxx",
};

/* ===== Voice demo ===== */
const VoiceDemo = ({ lang }) => {
  const isAR = lang === "ar";
  const [voiceId, setVoiceId] = React.useState("layla");
  const [calling, setCalling] = React.useState(false);
  const [seconds, setSeconds] = React.useState(0);
  const [transcript, setTranscript] = React.useState([]);
  const [error, setError] = React.useState("");
  const clientRef = React.useRef(null);
  const voice = VOICE_OPTIONS.find(v => v.id === voiceId);

  /* Timer ticks only while a call is active. */
  React.useEffect(() => {
    if (!calling) return;
    const t = setInterval(() => setSeconds(s => s + 1), 1000);
    return () => clearInterval(t);
  }, [calling]);

  /* Hard-stop any in-flight call on unmount. */
  React.useEffect(() => () => {
    try { clientRef.current?.stopCall(); } catch (e) {}
    clientRef.current = null;
  }, []);

  const start = async () => {
    if (calling) return;
    setError("");
    setTranscript([]);
    setSeconds(0);
    try {
      if (!window.RetellWebClient) {
        throw new Error("Retell SDK not loaded (check <script> tag in Wastafy.html)");
      }
      const agent_id = AGENT_MAP[voiceId] || AGENT_MAP.default;
      const res = await fetch(RETELL_TOKEN_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ voiceId, lang, agent_id }),
      });
      if (!res.ok) throw new Error(`Token mint failed: ${res.status}`);
      const { access_token } = await res.json();
      if (!access_token) throw new Error("Worker did not return access_token");

      const client = new window.RetellWebClient();
      clientRef.current = client;

      client.on("call_started", () => setCalling(true));
      client.on("call_ended", () => {
        setCalling(false);
        clientRef.current = null;
      });
      client.on("error", (e) => {
        console.error("[Retell]", e);
        const msg = typeof e === "string" ? e : (e?.message || "Call error");
        setError(msg);
        setCalling(false);
      });
      client.on("update", (u) => {
        if (!u?.transcript || !Array.isArray(u.transcript)) return;
        setTranscript(u.transcript.map(line => ({
          who: line.role === "agent" ? "ai" : "lead",
          text: line.content,
        })));
      });

      await client.startCall({ accessToken: access_token });
      setCalling(true);
    } catch (e) {
      console.error("[VoiceDemo.start]", e);
      setError(e.message || "Could not start call");
      setCalling(false);
    }
  };

  const end = () => {
    try { clientRef.current?.stopCall(); } catch (e) {}
    clientRef.current = null;
    setCalling(false);
  };

  const fmtTime = (s) => `${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;

  return (
    <div className="voice-demo">
      <div className="vd-pickers">
        <div className="vd-eye eyebrow">{isAR ? "اختر الصوت" : "Pick a voice"}</div>
        <div className="vd-grid">
          {VOICE_OPTIONS.map(v => {
            const isLocked = !!v.status;
            const statusLbl = isLocked ? (STATUS_LABEL[v.status]?.[isAR ? "ar" : "en"] || "") : "";
            return (
            <button
              key={v.id}
              className={`vd-voice ${voiceId === v.id ? "selected" : ""} ${isLocked ? "locked" : ""}`}
              onClick={() => { if (isLocked) return; setVoiceId(v.id); if (calling) end(); }}
              disabled={isLocked}
              aria-disabled={isLocked}
              title={isLocked ? statusLbl : ""}
            >
              <div className="vd-voice-top">
                <span className="vd-flag">{v.flag}</span>
                <span className="vd-gender mono">{v.gender === "female" ? "F" : "M"}</span>
              </div>
              <div className="vd-name">{v.name}</div>
              <div className="vd-desc">{v.desc}</div>
              {isLocked && <div className="vd-status mono">◐ {statusLbl}</div>}
            </button>
            );
          })}
        </div>

        <div className="vd-langs">
          <div className="vd-langs-title eyebrow">
            {isAR ? "كل وكيل يتحدث ٢٥ لغة" : "Every agent speaks 25 languages"}
          </div>
          <div className="vd-langs-list">
            {LANGUAGES.map(l => (
              <span className="vd-lang" key={l}>{l}</span>
            ))}
          </div>
        </div>
      </div>

      <div className="vd-phone">
        <div className="vd-phone-shell">
          <div className="vd-phone-status mono">
            <span>{calling ? (isAR ? "● مكالمة جارية" : "● In call") : (isAR ? "جاهز" : "Ready")}</span>
            <span>{fmtTime(seconds)}</span>
          </div>

          <div className="vd-call-hero">
            <div className="vd-avatar">
              <div className="vd-avatar-ring" data-active={calling} />
              <div className="vd-avatar-letter">{voice.name[0]}</div>
            </div>
            <div className="vd-caller-name">{voice.name}</div>
            <div className="vd-caller-meta mono">
              {voice.flag} · {voice.accent.toUpperCase()} · {voice.gender === "female" ? (isAR ? "أنثى" : "Female") : (isAR ? "ذكر" : "Male")}
            </div>
          </div>

          <Waveform active={calling} />

          <div className="vd-transcript">
            {error && (
              <div className="vd-error mono">⚠ {error}</div>
            )}
            {!error && transcript.length === 0 && !calling && (
              <div className="vd-empty">{isAR ? "اضغط للاتصال — ستسمع كيف تتحدث وتتفاوض" : "Tap call — hear her qualify, book, and confirm."}</div>
            )}
            {!error && transcript.length === 0 && calling && (
              <div className="vd-empty">{isAR ? "جاري الاتصال…" : "Connecting…"}</div>
            )}
            {transcript.map((line, i) => (
              <div key={i} className={`vd-line ${line.who}`}>
                <div className="vd-line-who mono">{line.who === "ai" ? voice.name : (isAR ? "العميل" : "Lead")}</div>
                <div className="vd-line-text">{line.text}</div>
              </div>
            ))}
          </div>

          <div className="vd-call-controls">
            {!calling ? (
              <button className="vd-call-btn" onClick={start}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z"/></svg>
                {isAR ? "اتصل" : "Call"}
              </button>
            ) : (
              <button className="vd-end-btn" onClick={end}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.37 1.9.72 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0 1 22 16.92z" transform="rotate(135 12 12)"/></svg>
                {isAR ? "إنهاء" : "End"}
              </button>
            )}
          </div>
        </div>
        <div className="vd-disclaimer mono">
          {isAR ? "عرض توضيحي — الإصدار الحقيقي يستخدم صوتك ولغة عميلك." : "Demo only — production version uses your voice and your lead's language."}
        </div>
      </div>

      <style>{`
        .voice-demo {
          display: grid;
          grid-template-columns: 1.2fr 1fr;
          gap: 64px;
          align-items: start;
        }
        .vd-eye { margin-bottom: 16px; }
        .vd-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 0;
          border-top: 1px solid var(--rule);
          border-left: 1px solid var(--rule);
          margin-bottom: 32px;
        }
        .vd-voice {
          all: unset;
          padding: 18px 20px;
          border-right: 1px solid var(--rule);
          border-bottom: 1px solid var(--rule);
          cursor: pointer;
          transition: background .25s var(--ease);
          background: transparent;
          display: flex;
          flex-direction: column;
          gap: 4px;
        }
        .vd-voice:hover { background: var(--bg-2); }
        .vd-voice.selected { background: var(--ink); color: var(--bg); }
        .vd-voice.selected .vd-desc, .vd-voice.selected .vd-gender { color: var(--bg); opacity: .8; }
        .vd-voice.locked {
          opacity: 0.55;
          cursor: not-allowed;
          background: repeating-linear-gradient(
            45deg,
            var(--bg) 0px, var(--bg) 8px,
            color-mix(in oklab, var(--ink) 6%, var(--bg)) 8px,
            color-mix(in oklab, var(--ink) 6%, var(--bg)) 16px
          );
        }
        .vd-voice.locked:hover { background: repeating-linear-gradient(
            45deg,
            var(--bg) 0px, var(--bg) 8px,
            color-mix(in oklab, var(--ink) 6%, var(--bg)) 8px,
            color-mix(in oklab, var(--ink) 6%, var(--bg)) 16px
          ); }
        .vd-status {
          margin-top: 8px;
          font-size: 9px;
          letter-spacing: 0.12em;
          text-transform: uppercase;
          color: var(--muted);
        }
        .vd-voice-top { display: flex; justify-content: space-between; align-items: center; }
        .vd-flag { font-size: 16px; }
        .vd-gender {
          font-size: 10px;
          letter-spacing: 0.15em;
          padding: 2px 8px;
          border: 1px solid var(--rule-2);
          border-radius: 999px;
          color: var(--muted);
        }
        .vd-name { font-size: 18px; letter-spacing: -0.02em; }
        .vd-desc { font-size: 11px; color: var(--muted); line-height: 1.4; }

        .vd-langs { padding-top: 24px; border-top: 1px solid var(--rule); }
        .vd-langs-title { margin-bottom: 12px; }
        .vd-langs-list {
          display: flex;
          flex-wrap: wrap;
          gap: 6px;
        }
        .vd-lang {
          font-family: var(--mono);
          font-size: 10px;
          letter-spacing: 0.08em;
          text-transform: uppercase;
          padding: 5px 10px;
          border: 1px solid var(--rule-2);
          border-radius: 999px;
          color: var(--ink-2);
        }

        .vd-phone-shell {
          background: var(--paper);
          border: 1px solid var(--rule-2);
          border-radius: 28px;
          padding: 24px;
          box-shadow: var(--shadow);
          display: flex;
          flex-direction: column;
          gap: 18px;
          min-height: 540px;
        }
        .vd-phone-status {
          display: flex;
          justify-content: space-between;
          font-size: 10px;
          color: var(--muted);
          letter-spacing: 0.12em;
          text-transform: uppercase;
        }
        .vd-call-hero { text-align: center; padding: 16px 0 8px; }
        .vd-avatar {
          position: relative;
          width: 88px;
          height: 88px;
          margin: 0 auto 14px;
          border-radius: 50%;
          background: linear-gradient(135deg, var(--accent), #ffb088);
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          font-size: 32px;
          font-family: var(--serif);
          font-style: italic;
        }
        .vd-avatar-ring {
          position: absolute;
          inset: -6px;
          border-radius: 50%;
          border: 2px solid var(--accent);
          opacity: 0;
        }
        .vd-avatar-ring[data-active="true"] {
          opacity: 1;
          animation: ringPulse 1.4s var(--ease) infinite;
        }
        @keyframes ringPulse {
          0% { transform: scale(1); opacity: 0.7; }
          100% { transform: scale(1.18); opacity: 0; }
        }
        .vd-caller-name { font-size: 22px; letter-spacing: -0.02em; margin-bottom: 4px; }
        .vd-caller-meta { font-size: 10px; color: var(--muted); letter-spacing: 0.1em; text-transform: uppercase; }

        .vd-transcript {
          background: var(--bg);
          border-radius: 16px;
          padding: 16px;
          flex: 1;
          min-height: 160px;
          max-height: 220px;
          overflow-y: auto;
          font-size: 13px;
          line-height: 1.5;
          display: flex;
          flex-direction: column;
          gap: 12px;
        }
        .vd-empty { color: var(--muted); font-family: var(--serif); font-style: italic; font-size: 14px; text-align: center; padding: 32px 16px; }
        .vd-error {
          color: #dc2626;
          background: rgba(220, 38, 38, 0.08);
          border: 1px solid rgba(220, 38, 38, 0.25);
          border-radius: 8px;
          padding: 10px 12px;
          font-size: 11px;
          letter-spacing: 0.04em;
          line-height: 1.4;
        }
        .vd-line { display: grid; grid-template-columns: 70px 1fr; gap: 12px; align-items: start; animation: lineIn .35s var(--ease); }
        @keyframes lineIn { from { opacity: 0; transform: translateY(6px); } }
        .vd-line-who {
          font-size: 9px;
          letter-spacing: 0.15em;
          text-transform: uppercase;
          color: var(--muted);
          padding-top: 3px;
        }
        .vd-line.ai .vd-line-who { color: var(--accent); }
        .vd-line-text { color: var(--ink-2); }

        .vd-call-controls { display: flex; justify-content: center; }
        .vd-call-btn, .vd-end-btn {
          all: unset;
          display: inline-flex;
          align-items: center;
          gap: 10px;
          padding: 14px 28px;
          border-radius: 999px;
          background: #16a34a;
          color: #fff;
          font-family: var(--mono);
          font-size: 11px;
          letter-spacing: 0.12em;
          text-transform: uppercase;
          cursor: pointer;
          transition: transform .25s var(--ease);
        }
        .vd-call-btn:hover, .vd-end-btn:hover { transform: translateY(-1px); }
        .vd-end-btn { background: #dc2626; }

        .vd-disclaimer {
          margin-top: 12px;
          text-align: center;
          font-size: 10px;
          color: var(--muted);
          letter-spacing: 0.08em;
          text-transform: uppercase;
        }

        @media (max-width: 980px) {
          .voice-demo { grid-template-columns: 1fr; gap: 48px; }
        }
      `}</style>
    </div>
  );
};

window.VoiceDemo = VoiceDemo;
