/* EQALL Support Chat - dual-mode (prospect / in-app) */
const { useState: scState, useRef: scRef, useEffect: scEffect } = React;

const PROSPECT_PROMPT = ``;

const INAPP_PROMPT = ``;

const SC_BOTS = {
  prospect: {
    label: "Why EQALL?",
    sublabel: "Learn about EQALL & get started",
    prompt: PROSPECT_PROMPT,
    profile: "eqallprospect",
    greeting: "<p>Hi! I'm here to help you learn about EQALL PRO and get started. How can I help?</p>",
    suggestions: [
    "What is the Seller's Dilemma?",
    "Who are the 10 AI sales experts?",
    "How does EQALL compare to Gong?",
    "How do I start a free trial?",
    "Can I see a demo?"]

  },
  inapp: {
    label: "EQALL Help",
    sublabel: "Get help using EQALL PRO",
    prompt: INAPP_PROMPT,
    profile: "eqallsupport",
    greeting: "<p>Welcome back! Ask me anything about using EQALL PRO, features, integrations, or settings.</p>",
    suggestions: [
    "How do I navigate EQALL?",
    "How do I identify Unknown Attendees?",
    "How do I connect Microsoft or Google?",
    "How do I set up Zoom transcripts?",
    "How do I configure HubSpot?"]

  }
};

function SCAvatar({ role }) {
  const isAi = role === "assistant";
  if (isAi) {
    return (
      <img
        src="assets/eqall-mark.png"
        alt="EQALL"
        style={{
          width: 28, height: 28, borderRadius: "50%",
          flexShrink: 0, objectFit: "cover", display: "block"
        }}
      />
    );
  }
  return (
    <div style={{
      width: 28, height: 28, borderRadius: "50%",
      background: "var(--ink-soft, #f0f0ee)",
      display: "grid", placeItems: "center",
      flexShrink: 0, fontSize: 12, fontWeight: 600,
      color: "var(--ink-2, #555)",
      border: "1px solid var(--line, rgba(0,0,0,0.08))"
    }}>U</div>);

}

function SCMessage({ msg }) {
  const isUser = msg.role === "user";
  return (
    <div style={{
      display: "flex", gap: 10, alignItems: "flex-start",
      flexDirection: isUser ? "row-reverse" : "row",
      marginBottom: 14
    }}>
      <SCAvatar role={msg.role} />
      <div style={{
        maxWidth: "78%",
        background: isUser ? "var(--brand-blue-deep, #1B7FBF)" : "var(--bg-soft, #f7f7f5)",
        color: isUser ? "#fff" : "var(--ink, #111)",
        border: isUser ? "none" : "1px solid var(--line, rgba(0,0,0,0.06))",
        borderRadius: isUser ? "14px 4px 14px 14px" : "4px 14px 14px 14px",
        padding: "10px 14px",
        fontSize: 14, lineHeight: 1.55,
        wordBreak: "break-word"
      }}>
        {msg.loading ?
        <span style={{ opacity: 0.5 }}>▌</span> :
        <span className="sc-msg-html" dangerouslySetInnerHTML={{ __html: msg.content }} />}
      </div>
    </div>);

}

async function sendPrompt({profile,history}) {

  const response = await fetch("https://api.eqall.com/eqall/support", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      profile,
      history
    })
  });

  const data = await response.json();
  return data.message;
  //return Response.json(data);
}

function SCChatPane({ botKey }) {
  const bot = SC_BOTS[botKey];
  const [messages, setMessages] = scState([{ role: "assistant", content: bot.greeting }]);
  const [input, setInput] = scState("");
  const [loading, setLoading] = scState(false);
  const bottomRef = scRef(null);
  const inputRef = scRef(null);

  scEffect(() => {
    if (bottomRef.current) {
      const parent = bottomRef.current.parentElement;
      if (parent) parent.scrollTop = parent.scrollHeight;
    }
  }, [messages]);

  function resetChat() {
    setMessages([{ role: "assistant", content: bot.greeting }]);
    setInput("");
    setTimeout(() => inputRef.current?.focus(), 30);
  }

  async function sendMessage(text) {
    const userText = (text || input).trim();
    if (!userText || loading) return;

    if (["clear", "bye", "reset"].includes(userText.toLowerCase())) {
      resetChat();
      return;
    }

    setInput("");
    const userMsg = { role: "user", content: userText };
    const history = [...messages, userMsg];
    setMessages([...history, { role: "assistant", content: "", loading: true }]);
    setLoading(true);

    try {
      // Build a single prompt with conversation history for window.claude.complete
      //const convo = history.map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${typeof m.content === "string" ? m.content.replace(/<[^>]+>/g, "") : m.content}`).join("\n\n");
      //const fullPrompt = `${bot.prompt}\n\n---\n\nConversation so far:\n${convo}\n\nReply as Assistant. Output ONLY clean HTML using <p>, <ol>, <ul>, <li>, <strong>, <a> tags. No markdown, no preamble.`;
      const history2=history.map((m)=>({
        role:m.role,
        content: typeof m.content === "string" ? m.content.replace(/<[^>]+>/g, "") : m.content
      }));


      //const reply = await window.claude.complete(fullPrompt);
      const reply = await sendPrompt({profile:bot.profile,history:history2});
      const cleaned = (reply || "").trim() || "<p>Sorry, I couldn't get a response. Please <a href='https://www.eqall.com/contact.html'>Contact Us</a>.</p>";

      setMessages((prev) => {
        const u = [...prev];
        u[u.length - 1] = { role: "assistant", content: cleaned };
        return u;
      });
    } catch (err) {
      setMessages((prev) => {
        const u = [...prev];
        u[u.length - 1] = { role: "assistant", content: "<p>Something went wrong. Please <a href='https://www.eqall.com/contact.html'>Contact Us</a>.</p>" };
        return u;
      });
    } finally {
      setLoading(false);
      setTimeout(() => inputRef.current?.focus(), 30);
    }
  }

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

  const showSuggestions = messages.length <= 1;

  return (
    <>
      <div className="sc-scroll" style={{
        minHeight: 320, maxHeight: 440, overflowY: "auto",
        padding: "8px 4px", marginBottom: 10
      }}>
        {messages.map((m, i) => <SCMessage key={i} msg={m} />)}
        <div ref={bottomRef} />
      </div>

      {showSuggestions &&
      <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-3, #888)", marginBottom: 8, fontWeight: 600 }}>Common questions</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {bot.suggestions.map((q, i) =>
          <button key={i} onClick={() => sendMessage(q)} style={{
            fontSize: 12.5, padding: "6px 12px",
            borderRadius: 999,
            border: "1px solid var(--line, rgba(0,0,0,0.1))",
            background: "#fff",
            color: "var(--ink, #111)",
            cursor: "pointer",
            fontFamily: "inherit"
          }}>{q}</button>
          )}
          </div>
        </div>
      }

      <div style={{
        display: "flex", gap: 8, alignItems: "flex-end",
        border: "1px solid var(--line, rgba(0,0,0,0.12))",
        borderRadius: 14,
        padding: "8px 8px 8px 14px",
        background: "#fff"
      }}>
        <textarea
          ref={inputRef}
          rows={1}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKey}
          placeholder={botKey === "prospect" ? "Ask about EQALL PRO..." : "Ask about using EQALL PRO..."}
          disabled={loading}
          style={{
            flex: 1, border: "none", outline: "none", resize: "none",
            background: "transparent", fontSize: 14, lineHeight: 1.5,
            color: "var(--ink, #111)", fontFamily: "inherit",
            maxHeight: 120, overflow: "auto", padding: "6px 0"
          }} />
        
        <button
          onClick={() => sendMessage()}
          disabled={loading || !input.trim()}
          aria-label="Send"
          style={{
            width: 34, height: 34, borderRadius: "50%", border: "none",
            background: loading || !input.trim() ? "var(--ink-soft, #eee)" : "linear-gradient(135deg, #1DB76E, #00C2E0)",
            color: loading || !input.trim() ? "var(--ink-3, #999)" : "#fff",
            cursor: loading || !input.trim() ? "default" : "pointer",
            display: "grid", placeItems: "center",
            flexShrink: 0, fontSize: 16, fontWeight: 600
          }}>
          ↑</button>
      </div>

      <div style={{ fontSize: 11, color: "var(--ink-3, #888)", marginTop: 10, textAlign: "center" }}>
        Type <strong>clear</strong> or <strong>bye</strong> to reset &nbsp;·&nbsp;
        <a href="schedule.html" style={{ color: "var(--brand-blue-deep, #1B7FBF)" }}>Schedule my Demo</a>
      </div>
    </>);

}

function SupportChat() {
  const [activeBot, setActiveBot] = scState("prospect");

  return (
    <div style={{ fontFamily: "inherit" }}>
      <style>{`
        .sc-msg-html p { margin: 0 0 8px; }
        .sc-msg-html p:last-child { margin-bottom: 0; }
        .sc-msg-html ol, .sc-msg-html ul { margin: 4px 0 8px; padding-left: 22px; }
        .sc-msg-html li { margin-bottom: 4px; }
        .sc-msg-html strong { font-weight: 600; }
        .sc-msg-html a { color: inherit; text-decoration: underline; }
        .sc-scroll::-webkit-scrollbar { width: 6px; }
        .sc-scroll::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.15); border-radius: 99px; }
      `}</style>

      {/* Header */}
      <div style={{
        display: "flex", alignItems: "center", gap: 12,
        padding: "14px 18px",
        background: "#fff",
        border: "1px solid var(--line, rgba(0,0,0,0.08))",
        borderRadius: 14,
        marginBottom: 12
      }}>
        <img
          src="assets/eqall-mark.png"
          alt="EQALL"
          style={{
            width: 40, height: 40, borderRadius: "50%",
            flexShrink: 0, objectFit: "cover", display: "block"
          }}
        />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 15, color: "var(--ink, #111)" }}>Ask EQALL</div>
          <div style={{ fontSize: 12, color: "var(--ink-2, #555)" }}>{SC_BOTS[activeBot].sublabel}</div>
        </div>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6 }}>
          <div style={{ width: 8, height: 8, borderRadius: "50%", background: "#1DB76E" }}></div>
          <span style={{ fontSize: 12, color: "var(--ink-2, #555)" }}>Online</span>
        </div>
      </div>

      {/* Bot toggle */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 14 }}>
        {Object.entries(SC_BOTS).map(([key, bot]) => {
          const active = activeBot === key;
          return (
            <button
              key={key}
              onClick={() => setActiveBot(key)}
              style={{
                padding: "12px 14px",
                borderRadius: 12,
                border: active ? "2px solid #1DB76E" : "1px solid var(--line, rgba(0,0,0,0.1))",
                background: active ? "#fff" : "#fafaf8",
                cursor: "pointer",
                textAlign: "left",
                fontFamily: "inherit"
              }}>
              
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink, #111)" }}>{bot.label}</div>
              <div style={{ fontSize: 11.5, color: "var(--ink-2, #555)", marginTop: 2 }}>{bot.sublabel}</div>
            </button>);

        })}
      </div>

      <SCChatPane key={activeBot} botKey={activeBot} />
    </div>);

}

window.SupportChat = SupportChat;

/* ============================ SECURITY CHAT (single-bot) ============================ */

const SECURITY_PROMPT = ``;

const SECURITY_BOT = {
  label: "Ask EQALL Security",
  sublabel: "Security & compliance questions answered",
  prompt: SECURITY_PROMPT,
  profile: "eqallsecurity",
  greeting: "<p>Hi! I'm here to answer your security, privacy, and compliance questions about EQALL PRO. Whether you're completing a vendor risk assessment or evaluating EQALL for your organization, ask me anything.</p>",
  suggestions: [
  "Who can access our data at EQALL?",
  "Is customer data used to train AI models?",
  "What encryption standards does EQALL use?",
  "Is EQALL SOC 2 or ISO 27001 certified?",
  "How does EQALL handle data deletion?",
  "Does EQALL comply with GDPR and CCPA?",
  "What happens to data after a trial ends?",
  "How are OAuth tokens secured?"]

};

function SecurityChatPane() {
  const bot = SECURITY_BOT;
  const [messages, setMessages] = scState([{ role: "assistant", content: bot.greeting }]);
  const [input, setInput] = scState("");
  const [loading, setLoading] = scState(false);
  const bottomRef = scRef(null);
  const inputRef = scRef(null);

  scEffect(() => {
    if (bottomRef.current) {
      const parent = bottomRef.current.parentElement;
      if (parent) parent.scrollTop = parent.scrollHeight;
    }
  }, [messages]);

  function resetChat() {
    setMessages([{ role: "assistant", content: bot.greeting }]);
    setInput("");
    setTimeout(() => inputRef.current?.focus(), 30);
  }

  async function sendMessage(text) {
    const userText = (text || input).trim();
    if (!userText || loading) return;
    if (["clear", "bye", "reset"].includes(userText.toLowerCase())) {resetChat();return;}

    setInput("");
    const userMsg = { role: "user", content: userText };
    const history = [...messages, userMsg];
    setMessages([...history, { role: "assistant", content: "", loading: true }]);
    setLoading(true);

    try {
      //const convo = history.map((m) => `${m.role === "user" ? "User" : "Assistant"}: ${typeof m.content === "string" ? m.content.replace(/<[^>]+>/g, "") : m.content}`).join("\n\n");
      //const fullPrompt = `${bot.prompt}\n\n---\n\nConversation so far:\n${convo}\n\nReply as Assistant. Output ONLY clean HTML using <p>, <ol>, <ul>, <li>, <strong>, <a> tags. No markdown, no preamble.`;

      const history2=history.map((m)=>({
        role:m.role,
        content: typeof m.content === "string" ? m.content.replace(/<[^>]+>/g, "") : m.content
      }));


      //const reply = await window.claude.complete(fullPrompt);
      const reply = await sendPrompt({profile:bot.profile,history:history2});

      const cleaned = (reply || "").trim() || "<p>Sorry, I couldn't get a response. Please <a href='https://www.eqall.com/contact.html'>Contact Us</a>.</p>";
      setMessages((prev) => {const u = [...prev];u[u.length - 1] = { role: "assistant", content: cleaned };return u;});
    } catch {
      setMessages((prev) => {const u = [...prev];u[u.length - 1] = { role: "assistant", content: "<p>Something went wrong. Please <a href='https://www.eqall.com/contact.html'>Contact Us</a>.</p>" };return u;});
    } finally {
      setLoading(false);
      setTimeout(() => inputRef.current?.focus(), 30);
    }
  }

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

  const showSuggestions = messages.length <= 1;

  return (
    <div style={{ fontFamily: "inherit" }}>
      <style>{`
        .sc-msg-html p { margin: 0 0 8px; }
        .sc-msg-html p:last-child { margin-bottom: 0; }
        .sc-msg-html ol, .sc-msg-html ul { margin: 4px 0 8px; padding-left: 22px; }
        .sc-msg-html li { margin-bottom: 4px; }
        .sc-msg-html strong { font-weight: 600; }
        .sc-msg-html a { color: inherit; text-decoration: underline; }
        .sc-scroll::-webkit-scrollbar { width: 6px; }
        .sc-scroll::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.15); border-radius: 99px; }
      `}</style>

      <div style={{
        display: "flex", alignItems: "center", gap: 12,
        padding: "14px 18px", background: "#fff",
        border: "1px solid var(--line, rgba(0,0,0,0.08))",
        borderRadius: 14, marginBottom: 12
      }}>
        <img
          src="assets/eqall-mark.png"
          alt="EQALL"
          style={{
            width: 40, height: 40, borderRadius: "50%",
            flexShrink: 0, objectFit: "cover", display: "block"
          }}
        />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 15, color: "var(--ink, #111)" }}>Ask EQALL Security</div>
          <div style={{ fontSize: 12, color: "var(--ink-2, #555)" }}>{bot.sublabel}</div>
        </div>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6 }}>
          <div style={{ width: 8, height: 8, borderRadius: "50%", background: "#1DB76E" }}></div>
          <span style={{ fontSize: 12, color: "var(--ink-2, #555)" }}>Online</span>
        </div>
      </div>

      <div className="sc-scroll" style={{
        minHeight: 320, maxHeight: 440, overflowY: "auto",
        padding: "8px 4px", marginBottom: 10
      }}>
        {messages.map((m, i) => <SCMessage key={i} msg={m} />)}
        <div ref={bottomRef} />
      </div>

      {showSuggestions &&
      <div style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--ink-3, #888)", marginBottom: 8, fontWeight: 600 }}>Common questions</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
            {bot.suggestions.map((q, i) =>
          <button key={i} onClick={() => sendMessage(q)} style={{
            fontSize: 12.5, padding: "6px 12px", borderRadius: 999,
            border: "1px solid var(--line, rgba(0,0,0,0.1))",
            background: "#fff", color: "var(--ink, #111)",
            cursor: "pointer", fontFamily: "inherit"
          }}>{q}</button>
          )}
          </div>
        </div>
      }

      <div style={{
        display: "flex", gap: 8, alignItems: "flex-end",
        border: "1px solid var(--line, rgba(0,0,0,0.12))",
        borderRadius: 14, padding: "8px 8px 8px 14px", background: "#fff"
      }}>
        <textarea
          ref={inputRef} rows={1} value={input}
          onChange={(e) => setInput(e.target.value)} onKeyDown={handleKey}
          placeholder="Ask a security or compliance question..."
          disabled={loading}
          style={{
            flex: 1, border: "none", outline: "none", resize: "none",
            background: "transparent", fontSize: 14, lineHeight: 1.5,
            color: "var(--ink, #111)", fontFamily: "inherit",
            maxHeight: 120, overflow: "auto", padding: "6px 0"
          }} />
        
        <button
          onClick={() => sendMessage()} disabled={loading || !input.trim()} aria-label="Send"
          style={{
            width: 34, height: 34, borderRadius: "50%", border: "none",
            background: loading || !input.trim() ? "var(--ink-soft, #eee)" : "linear-gradient(135deg, #1DB76E, #00C2E0)",
            color: loading || !input.trim() ? "var(--ink-3, #999)" : "#fff",
            cursor: loading || !input.trim() ? "default" : "pointer",
            display: "grid", placeItems: "center",
            flexShrink: 0, fontSize: 16, fontWeight: 600
          }}>
          ↑</button>
      </div>

      <div style={{ fontSize: 11, color: "var(--ink-3, #888)", marginTop: 10, textAlign: "center" }}>
        Type <strong>clear</strong> or <strong>bye</strong> to reset &nbsp;·&nbsp;
        <a href="schedule.html?mode=security" style={{ color: "var(--brand-blue-deep, #1B7FBF)" }}>Schedule a security workshop</a>
      </div>
    </div>);

}

window.SecurityChatPane = SecurityChatPane;