// Standalone Workshop chatbot — ported from v1.
// Includes its own SVG icon deps so it has zero coupling with v2 components.

const ChatIcon = ({ size = 18 }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
  </svg>
);

const CloseIcon = ({ size = 14 }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2.5"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M18 6L6 18M6 6l12 12" />
  </svg>
);

const FireIcon = ({ size = 14 }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M12 22c-4.97 0-9-2.69-9-6 0-2.5 1.5-4.5 3-6 .5-.5 1.5.5 1 1-.5.5-1 1.5-1 2.5 0 2.5 2.5 4 5 1.5 1.5-1.5 1-4-.5-5.5C9 7 10 4 12 2c1 2 3 3.5 4.5 5.5 1.5 2 2.5 4 2.5 6.5 0 4.5-3 8-7 8z" />
  </svg>
);

const SendIcon = ({ size = 16 }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
  >
    <path d="M22 2L11 13" />
    <path d="M22 2l-7 20-4-9-9-4 20-7z" />
  </svg>
);

const WorkshopChatbot = ({ hasCompareBar = false }) => {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [draft, setDraft] = React.useState("");
  const listRef = React.useRef(null);
  const inputRef = React.useRef(null);

  // Seed greeting on first open
  React.useEffect(() => {
    if (open && messages.length === 0) {
      setMessages([{ from: "bot", text: WORKSHOP_GREETING }]);
    }
  }, [open, messages.length]);

  // Auto-scroll to latest message
  React.useEffect(() => {
    if (listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight;
    }
  }, [messages, open]);

  // Focus input on open
  React.useEffect(() => {
    if (open && inputRef.current) {
      const t = setTimeout(() => inputRef.current.focus(), 50);
      return () => clearTimeout(t);
    }
  }, [open]);

  const [sending, setSending] = React.useState(false);

  const handleSend = async () => {
    const text = draft.trim();
    if (!text || sending) return;
    const userMsg = { from: "user", text };
    setMessages((prev) => [...prev, userMsg].slice(-20));
    setDraft("");
    setSending(true);

    // Add a "thinking..." placeholder
    setMessages((prev) =>
      [...prev, { from: "bot", text: "…", pending: true }].slice(-20),
    );

    try {
      // Build OpenAI-style message history from local state
      const apiMessages = [...messages, userMsg]
        .filter((m) => !m.pending)
        .map((m) => ({
          role: m.from === "user" ? "user" : "assistant",
          content: m.text,
        }));

      const res = await fetch("/api/workshopbrain.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: apiMessages }),
      });
      const data = await res.json();
      const reply = data.reply || data.error || workshopBotReply(text);

      // Replace the pending message
      setMessages((prev) => {
        const next = [...prev];
        const lastIdx = next.length - 1;
        if (lastIdx >= 0 && next[lastIdx].pending) {
          next[lastIdx] = { from: "bot", text: reply };
        } else {
          next.push({ from: "bot", text: reply });
        }
        return next.slice(-20);
      });
    } catch (e) {
      // Network failure → fall back to rule-based
      setMessages((prev) => {
        const next = [...prev];
        const lastIdx = next.length - 1;
        const fallback = workshopBotReply(text);
        if (lastIdx >= 0 && next[lastIdx].pending) {
          next[lastIdx] = { from: "bot", text: fallback };
        } else {
          next.push({ from: "bot", text: fallback });
        }
        return next.slice(-20);
      });
    } finally {
      setSending(false);
    }
  };

  const handleKey = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    } else if (e.key === "Escape") {
      setOpen(false);
    }
  };

  // Shaun is the only FAB now. Sit at the bottom corner.
  const fabBottom = hasCompareBar ? 100 : 24;
  const panelBottom = fabBottom + 68;

  return (
    <>
      {open && (
        <div
          className="workshop-chat-panel"
          style={{ bottom: panelBottom }}
          role="dialog"
          aria-label="Shaun chatbot"
        >
          <div className="workshop-chat-header">
            <div className="workshop-chat-header-title">
              <span className="workshop-chat-badge">AI</span>
              <div>
                <div className="workshop-chat-name">Shaun</div>
                <div className="workshop-chat-status">
                  <span className="workshop-chat-dot" /> Online · internal
                </div>
              </div>
            </div>
            <button
              className="workshop-chat-close"
              onClick={() => setOpen(false)}
              aria-label="Close chatbot"
              type="button"
            >
              <CloseIcon size={14} />
            </button>
          </div>

          <div className="workshop-chat-messages" ref={listRef}>
            {messages.map((m, i) => (
              <div
                key={i}
                className={
                  m.from === "user"
                    ? "workshop-chat-msg-user"
                    : "workshop-chat-msg-bot"
                }
              >
                {m.text}
              </div>
            ))}
          </div>

          <div className="workshop-chat-input-row">
            <input
              ref={inputRef}
              type="text"
              placeholder="Ask about stock, prices, warranty..."
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={handleKey}
              aria-label="Chat message"
            />
            <button
              onClick={handleSend}
              disabled={!draft.trim()}
              aria-label="Send message"
              type="button"
            >
              <SendIcon size={16} />
            </button>
          </div>
        </div>
      )}

      <button
        className="workshop-chat-fab"
        style={{ bottom: fabBottom }}
        onClick={() => setOpen((v) => !v)}
        aria-label={open ? "Close Shaun" : "Open Shaun"}
        aria-expanded={open}
        type="button"
      >
        {open ? <CloseIcon size={18} /> : <ChatIcon size={22} />}
        {!open && <span className="workshop-chat-fab-badge">AI</span>}
      </button>
    </>
  );
};

// ── Quick View Modal ───────────────────────────────────

