// ONOGolf — Swing vs Swing · AI swing coach chat
// Uses window.claude.complete when available (Claude artifact env). On our server
// that API is absent, so the coach runs in MOCK PREVIEW mode — believable canned
// responses keyed to the question — until we wire a real swing-analysis backend.
// The live path is preserved untouched for when that backend lands.

const { useState: useChatSt, useRef: useChatRf, useEffect: useChatEf } = React;

function AICoach({ left, right, challengeTitle }) {
  const [messages, setMessages] = useChatSt([
    { role: "coach", text: "I'm watching both swings with you. Ask me anything — tempo, sequencing, why one carries it further, or what you could borrow for your own game." },
  ]);
  const [input, setInput] = useChatSt("");
  const [busy, setBusy] = useChatSt(false);
  const [voiceOn, setVoiceOn] = useChatSt(() => !!(window.OnoVoice && window.OnoVoice.enabled()));
  const bodyRef = useChatRf(null);

  // speak a coach reply aloud (ElevenLabs via session-gated /api/tts);
  // the "— Preview coach…" footer is visual only, never spoken
  const speakReply = (text) => {
    if (!voiceOn || !window.OnoVoice) return;
    window.OnoVoice.speak(String(text).split("\n\n—")[0]);
  };
  const toggleVoice = () => {
    const next = !voiceOn;
    setVoiceOn(next);
    if (window.OnoVoice) { window.OnoVoice.setEnabled(next); if (next) window.OnoVoice.chime(); }
  };

  useChatEf(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, busy]);

  const suggestions = [
    "Who has the faster tempo?",
    "Why does one carry it further?",
    "What can a 15-handicap learn here?",
    "Compare their transitions.",
  ];

  const buildContext = () => {
    const desc = (p, d) => p ? `${p.name} (World #${p.rank}, ${p.country}). ` +
      `Club speed ${p.stats.clubSpeed}mph, ball speed ${p.stats.ballSpeed}mph, smash ${p.stats.smash}, ` +
      `driver carry ${p.stats.driverCarry}yds, 7-iron ${p.stats.ironCarry}yds, apex ${p.stats.apex}ft. ` +
      `Key swing points: ${(d?.points || []).map(x => `${x.t} ${x.label} (${x.note})`).join("; ")}.` : "not selected";
    return `You are ONO, a friendly, concise PGA-level golf swing coach inside the "Swing vs Swing" comparison tool. ` +
      `The user is comparing two swings side by side` + (challengeTitle ? ` in the "${challengeTitle}" matchup` : "") + `.\n` +
      `LEFT player: ${desc(left, left)}\n` +
      `RIGHT player: ${desc(right, right)}\n` +
      `Answer in 2-4 short sentences, plain language, reference the two players by name, and when useful give one practical takeaway an amateur could apply. Do not invent stats beyond what's given.`;
  };

  // MOCK PREVIEW: believable, on-topic canned reply keyed to the question.
  // Used until a real swing-analysis backend is wired (see header).
  const mockReply = (q) => {
    const L = (left && left.name) || "the left swing";
    const R = (right && right.name) || "the right swing";
    const ql = q.toLowerCase();
    let body;
    if (/tempo|fast|slow|rhythm/.test(ql))
      body = `${L} runs a slightly quicker tempo, while ${R} stays smoother into transition. The easier amateur win is ${R}'s unhurried changeover — count "one… and… two" from the top.`;
    else if (/carry|further|distance|far|long/.test(ql))
      body = `${R} carries it further mostly through ball speed and a cleaner strike (higher smash), not just swinging harder. Borrow the setup width, not the effort.`;
    else if (/transition|sequenc|downswing/.test(ql))
      body = `Watch the lower body: ${L} starts the downswing from the ground up, hips leading hands; ${R} is a touch more arms-first. That ground-up sequence is what most amateurs are missing.`;
    else if (/learn|amateur|handicap|borrow|takeaway|apply/.test(ql))
      body = `Steal the tempo and the balanced hold-the-finish from these two. Most mid-handicaps lose strikes by rushing the top — slowing the changeover alone tightens contact.`;
    else
      body = `Comparing ${L} and ${R}, the clearest difference is sequencing and tempo through transition. Pick one cue — slower changeover or fuller turn — and rehearse it in slow motion before adding speed.`;
    return body + "\n\n— Preview coach · live AI swing analysis coming soon";
  };

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || busy) return;
    setMessages((m) => [...m, { role: "user", text: q }]);
    setInput("");
    setBusy(true);
    const live = window.claude && typeof window.claude.complete === "function";
    try {
      if (live) {
        const history = messages.slice(1).map((m) => ({ role: m.role === "user" ? "user" : "assistant", content: m.text }));
        const reply = await window.claude.complete({
          messages: [
            { role: "user", content: buildContext() },
            ...history,
            { role: "user", content: q },
          ],
        });
        const replyText = (reply || "").trim() || "Let me look again — try rephrasing that.";
        setMessages((m) => [...m, { role: "coach", text: replyText }]);
        speakReply(replyText);
      } else {
        // Mock preview mode — simulate the model thinking, then a canned reply.
        await new Promise((r) => setTimeout(r, 650));
        const replyText = mockReply(q);
        setMessages((m) => [...m, { role: "coach", text: replyText }]);
        speakReply(replyText);
      }
    } catch (e) {
      setMessages((m) => [...m, { role: "coach", text: "I couldn't reach the swing model just now. Give it another try in a moment." }]);
    }
    setBusy(false);
  };

  return (
    <section className="section section-tight">
      <div className="wrap svs-ai">
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <div className="svs-sec-eyebrow">Ask the coach</div>
          <div className="display display-md" style={{ marginTop: 12 }}>Questions about <span className="italic-ink">what you're watching?</span></div>
        </div>

        <div className="svs-ai-card">
          <div className="svs-ai-head">
            <div className="svs-ai-mark">O</div>
            <div className="svs-ai-h">
              <h3>ONO Swing Coach</h3>
              <p>{left && right ? `Watching ${left.name} vs ${right.name}` : "Pick two players to begin"}</p>
            </div>
            <button onClick={toggleVoice} aria-label={voiceOn ? "Turn coach voice off" : "Turn coach voice on"}
              title={voiceOn ? "Coach voice on — replies are spoken" : "Coach voice off"}
              style={{ marginLeft: "auto", flexShrink: 0, display: "inline-flex", alignItems: "center", gap: 7,
                fontFamily: "JetBrains Mono,monospace", fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase",
                padding: "6px 12px", borderRadius: 999, cursor: "pointer", transition: "all .14s",
                border: voiceOn ? "1px solid rgb(191 154 56 / .55)" : "1px solid rgb(120 120 104 / .4)",
                background: voiceOn ? "rgb(191 154 56 / .14)" : "transparent",
                color: voiceOn ? "#bf9a38" : "rgb(120 120 104)" }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" fill="currentColor" stroke="none"/>
                {voiceOn ? <><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M18.5 5.5a9 9 0 0 1 0 13"/></> : <line x1="16" y1="9" x2="22" y2="15"/>}
                {voiceOn ? null : <line x1="22" y1="9" x2="16" y2="15"/>}
              </svg>
              {voiceOn ? "Voice on" : "Voice off"}
            </button>
          </div>

          <div className="svs-ai-body" ref={bodyRef}>
            {messages.map((m, i) => (
              <div key={i} className={`svs-msg ${m.role}`}>
                <div className="svs-msg-av">{m.role === "user" ? "You"[0] : "O"}</div>
                <div className="svs-msg-bubble">{m.text}</div>
              </div>
            ))}
            {busy && (
              <div className="svs-msg coach">
                <div className="svs-msg-av">O</div>
                <div className="svs-msg-bubble"><span className="svs-ai-typing"><span></span><span></span><span></span></span></div>
              </div>
            )}
          </div>

          <div className="svs-ai-suggest">
            {suggestions.map((s) => (
              <button key={s} className="svs-ai-sg" onClick={() => send(s)} disabled={busy}>{s}</button>
            ))}
          </div>

          <div className="svs-ai-input">
            <input
              type="text"
              placeholder="Ask about tempo, sequencing, distance…"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") send(); }}
            />
            <button className="svs-ai-send" onClick={() => send()} disabled={busy || !input.trim()} aria-label="Send">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/></svg>
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { AICoach });
