(function () {
  // Prevent duplicate widget
  if (document.getElementById("pitchy-root")) return;

  // Inject CSS once
  if (!document.getElementById("pf-styles")) {
  // ─── CSS ──────────────────────────────────────────────────────────────────
  var style = document.createElement("style");
  style.id = "pf-styles";
  style.textContent = `
    @keyframes pf-bob {
      0%, 100% { transform: translateY(0); }
      50%       { transform: translateY(-4px); }
    }
    @keyframes pf-bounce {
      0%   { transform: translateY(0) rotate(0deg); }
      20%  { transform: translateY(-12px) rotate(-5deg); }
      40%  { transform: translateY(-6px) rotate(3deg); }
      60%  { transform: translateY(-10px) rotate(-3deg); }
      80%  { transform: translateY(-3px) rotate(2deg); }
      100% { transform: translateY(0) rotate(0deg); }
    }
    @keyframes pf-listen {
      0%, 100% { transform: scale(1); opacity: 1; }
      50%       { transform: scale(1.08); opacity: 0.7; }
    }
    @keyframes pf-dot {
      0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
      40%            { transform: scale(1); opacity: 1; }
    }
    #pitchy-root {
      position: fixed;
      bottom: 20px;
      right: 20px;
      z-index: 500;
      display: flex;
      flex-direction: column;
      align-items: center;
      font-family: var(--font, sans-serif);
    }
    .pf-avatar {
      cursor: pointer;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;
      user-select: none;
    }
    .pf-avatar svg {
      animation: pf-bob 2s ease-in-out infinite;
    }
    .pf-avatar.bouncing svg {
      animation: pf-bounce 0.9s ease-in-out;
    }
    .pf-avatar.listening svg {
      animation: pf-listen 1.2s ease-in-out infinite;
    }
    .pf-label {
      font-size: 10px;
      color: var(--text-3);
      letter-spacing: 0.02em;
    }
    .pf-window {
      position: fixed;
      bottom: 88px;
      right: 20px;
      width: 320px;
      max-height: 420px;
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: 12px;
      box-shadow: var(--shadow);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      z-index: 501;
    }
    .pf-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 14px;
      border-bottom: 1px solid var(--border);
      font-size: 13px;
      font-weight: 600;
      color: var(--text);
      flex-shrink: 0;
    }
    .pf-close {
      cursor: pointer;
      color: var(--text-3);
      font-size: 16px;
      line-height: 1;
      background: none;
      border: none;
      padding: 2px 4px;
    }
    .pf-close:hover { color: var(--text); }
    .pf-messages {
      flex: 1;
      overflow-y: auto;
      padding: 12px;
      display: flex;
      flex-direction: column;
      gap: 8px;
      min-height: 0;
    }
    .pf-bubble {
      max-width: 85%;
      padding: 8px 11px;
      border-radius: 10px;
      font-size: 13px;
      line-height: 1.45;
      white-space: pre-wrap;
      word-break: break-word;
    }
    .pf-bubble.user {
      align-self: flex-end;
      background: var(--accent);
      color: #fff;
      border-bottom-right-radius: 3px;
    }
    .pf-bubble.assistant {
      align-self: flex-start;
      background: var(--bg-2);
      color: var(--text);
      border-bottom-left-radius: 3px;
    }
    .pf-dots {
      display: flex;
      gap: 4px;
      align-items: center;
      height: 18px;
    }
    .pf-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background: var(--text-3);
      animation: pf-dot 1.4s ease-in-out infinite;
    }
    .pf-dot:nth-child(2) { animation-delay: 0.2s; }
    .pf-dot:nth-child(3) { animation-delay: 0.4s; }
    .pf-footer {
      display: flex;
      gap: 6px;
      padding: 10px 12px;
      border-top: 1px solid var(--border);
      flex-shrink: 0;
    }
    .pf-input {
      flex: 1;
      padding: 7px 10px;
      font-size: 13px;
      border: 1px solid var(--border);
      border-radius: 8px;
      background: var(--bg);
      color: var(--text);
      outline: none;
      font-family: inherit;
    }
    .pf-input:focus { border-color: var(--accent); }
    .pf-send {
      padding: 7px 13px;
      font-size: 13px;
      background: var(--accent);
      color: #fff;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-family: inherit;
    }
    .pf-send:disabled { opacity: 0.5; cursor: not-allowed; }
    .pf-send:hover:not(:disabled) { opacity: 0.9; }
  `;
  document.head.appendChild(style);
  } // end CSS once

  // ─── Component ────────────────────────────────────────────────────────────
  const { useState, useEffect, useRef } = React;

  const GREETING = "Hey, I'm Pitchy 🍴 — your MMV assistant! Ask me anything about managing your music catalog.";

  function TuningForkSVG() {
    return (
      <svg width="32" height="60" viewBox="0 0 32 60" fill="none" xmlns="http://www.w3.org/2000/svg">
        {/* Left prong */}
        <rect x="6" y="4" width="7" height="28" rx="3.5" fill="var(--accent)" />
        {/* Right prong */}
        <rect x="19" y="4" width="7" height="28" rx="3.5" fill="var(--accent)" />
        {/* Curved base connecting prongs */}
        <path d="M9.5 28 Q9.5 36 16 36 Q22.5 36 22.5 28" stroke="var(--accent)" strokeWidth="7" fill="none" strokeLinecap="round" />
        {/* Handle */}
        <rect x="12.5" y="36" width="7" height="20" rx="3.5" fill="var(--accent)" />
      </svg>
    );
  }

  function Pitchy() {
    const [open, setOpen]         = useState(false);
    const [messages, setMessages] = useState([{ role: "assistant", content: GREETING }]);
    const [input, setInput]       = useState("");
    const [loading, setLoading]   = useState(false);
    const [bouncing, setBouncing] = useState(false);
    const bottomRef               = useRef(null);
    const inputRef                = useRef(null);

    // Attention-seeking bounce every 15s while closed
    useEffect(() => {
      if (open) return;
      let timeoutId = null;
      const id = setInterval(() => {
        setBouncing(true);
        timeoutId = setTimeout(() => setBouncing(false), 900);
      }, 15000);
      return () => {
        clearInterval(id);
        if (timeoutId) clearTimeout(timeoutId);
      };
    }, [open]);

    // Scroll to bottom when messages change
    useEffect(() => {
      if (bottomRef.current) {
        bottomRef.current.scrollIntoView({ behavior: "smooth" });
      }
    }, [messages, loading]);

    // Focus input when chat opens
    useEffect(() => {
      if (open && inputRef.current) {
        setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
      }
    }, [open]);

    async function send() {
      if (typeof firebase === "undefined" || typeof firebase.functions !== "function") {
        setMessages(prev => [...prev, { role: "assistant", content: "Chat isn't available right now." }]);
        return;
      }
      const text = input.trim();
      if (!text || loading) return;

      const userMsg = { role: "user", content: text };
      const newMessages = [...messages, userMsg];
      setMessages(newMessages);
      setInput("");
      setLoading(true);

      try {
        const callable = firebase.functions().httpsCallable("chatbot");
        // Exclude the initial greeting from conversation history sent to the API
        const history = newMessages.slice(1).map(m => ({ role: m.role, content: m.content }));
        const result = await callable({ messages: history });
        setMessages(prev => [...prev, { role: "assistant", content: result.data.reply }]);
      } catch (err) {
        console.error("Pitchy send error:", err);
        setMessages(prev => [...prev, { role: "assistant", content: "Sorry, something went wrong. Please try again." }]);
      } finally {
        setLoading(false);
      }
    }

    function handleKeyDown(e) {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        send();
      }
    }

    const avatarClass = "pf-avatar" + (bouncing ? " bouncing" : loading && open ? " listening" : "");

    return (
      <>
        {open && (
          <div className="pf-window">
            <div className="pf-header">
              <span>Pitchy 🍴</span>
              <button className="pf-close" onClick={() => setOpen(false)} aria-label="Close chat">×</button>
            </div>
            <div className="pf-messages">
              {messages.map((m, i) => (
                <div key={i} className={"pf-bubble " + m.role}>
                  {m.content}
                </div>
              ))}
              {loading && (
                <div className="pf-bubble assistant">
                  <div className="pf-dots">
                    <div className="pf-dot" />
                    <div className="pf-dot" />
                    <div className="pf-dot" />
                  </div>
                </div>
              )}
              <div ref={bottomRef} />
            </div>
            <div className="pf-footer">
              <input
                ref={inputRef}
                className="pf-input"
                placeholder="Ask me anything…"
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={handleKeyDown}
                disabled={loading}
              />
              <button className="pf-send" onClick={send} disabled={loading || !input.trim()}>
                Send
              </button>
            </div>
          </div>
        )}
        <div
          className={avatarClass}
          onClick={() => setOpen(o => !o)}
          role="button"
          tabIndex={0}
          onKeyDown={e => { if (e.key === "Enter" || e.key === " ") setOpen(o => !o); }}
          aria-label={open ? "Close Pitchy chat" : "Open Pitchy chat"}
          aria-expanded={open}
        >
          <TuningForkSVG />
          <span className="pf-label">Pitchy 🍴</span>
        </div>
      </>
    );
  }

  // ─── Self-mount ────────────────────────────────────────────────────────────
  const container = document.createElement("div");
  container.id = "pitchy-root";
  document.body.appendChild(container);
  if (ReactDOM.createRoot) {
    ReactDOM.createRoot(container).render(React.createElement(Pitchy));
  } else {
    ReactDOM.render(React.createElement(Pitchy), container);
  }
})();
