/* MCA — Atlas: floating AI chat assistant */

const { useState: useStateChat, useEffect: useEffectChat, useRef: useRefChat } = React;

const ATLAS_GREETING =
  "Hey there! I'm Atlas, MCA's AI assistant. Whether you're exploring AI automation, M&A, or capital markets, I can help point you in the right direction. What brings you here today?";

const ATLAS_CHIPS = [
  "AI automation",
  "M&A advisory",
  "Capital markets",
  "Book a call",
];

const ATLAS_SYSTEM = `You are Atlas, the friendly AI assistant for MultiChain Advisors (MCA) — a global advisory firm.
MCA helps companies with three core areas:
1. AI-Powered Solutions — intelligent systems across sales, marketing, operations and finance.
2. Strategy, Growth & Scale — GTM, positioning, ecosystem and community growth, M&A advisory.
3. Capital Markets — fundraising and capital strategy.
MCA operates across North America, Asia, Europe and Australia.
Keep replies warm, concise (2-4 sentences), and helpful. Guide visitors toward the right service and, when they show intent, suggest booking a free consultation. Never invent specific pricing or guarantees. Use plain language, no markdown headers.`;

/* simple paragraph renderer */
function AtlasText({ text }) {
  const parts = String(text).split(/\n{2,}|\n/).filter(Boolean);
  return parts.map((p, i) => <p key={i}>{p}</p>);
}

function AtlasSpark({ size = 16 }) {
  // MCA-inspired ring-of-links mark — evokes the brand's interlinked chain motif
  const links = [];
  const N = 11;
  const cx = 12, cy = 12, r = 7.1;
  for (let i = 0; i < N; i++) {
    const a = (i / N) * Math.PI * 2 - Math.PI / 2;
    const x = cx + Math.cos(a) * r;
    const y = cy + Math.sin(a) * r;
    const rot = (a * 180) / Math.PI + 90;
    links.push(
      <rect key={i} x={x - 1.55} y={y - 2.5} width="3.1" height="5"
        rx="1.45" ry="1.45"
        fill="none" stroke="url(#atlasMarkGrad)" strokeWidth="1.25"
        transform={`rotate(${rot} ${x} ${y})`} />
    );
  }
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <defs>
        <linearGradient id="atlasMarkGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#5fd6cf" />
          <stop offset="55%" stopColor="#19a8a3" />
          <stop offset="100%" stopColor="#0d5566" />
        </linearGradient>
      </defs>
      {links}
    </svg>);
}

function AtlasChat() {
  const [open, setOpen] = useStateChat(false);
  const [messages, setMessages] = useStateChat([{ role: "bot", text: ATLAS_GREETING }]);
  const [showChips, setShowChips] = useStateChat(true);
  const [input, setInput] = useStateChat("");
  const [typing, setTyping] = useStateChat(false);
  const [focused, setFocused] = useStateChat(false);

  const bodyRef = useRefChat(null);
  const inputRef = useRefChat(null);

  useEffectChat(() => {
    if (bodyRef.current) {
      bodyRef.current.scrollTo({ top: bodyRef.current.scrollHeight, behavior: "smooth" });
    }
  }, [messages, typing, open]);

  useEffectChat(() => {
    if (open && inputRef.current) {
      const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 360);
      return () => clearTimeout(t);
    }
  }, [open]);

  // esc to close
  useEffectChat(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const autoGrow = (el) => {
    if (!el) return;
    el.style.height = "auto";
    el.style.height = Math.min(el.scrollHeight, 96) + "px";
  };

  async function sendMessage(textArg) {
    const text = (textArg != null ? textArg : input).trim();
    if (!text || typing) return;

    setShowChips(false);
    setInput("");
    if (inputRef.current) inputRef.current.style.height = "auto";

    const history = [...messages, { role: "user", text }];
    setMessages(history);
    setTyping(true);

    let reply = "";
    try {
      const convo = history
        .map((m) => `${m.role === "user" ? "Visitor" : "Atlas"}: ${m.text}`)
        .join("\n");
      const prompt = `${ATLAS_SYSTEM}\n\nConversation so far:\n${convo}\n\nWrite Atlas's next reply only.`;
      if (window.claude && window.claude.complete) {
        reply = await window.claude.complete(prompt);
      }
    } catch (e) {
      reply = "";
    }

    if (!reply || !reply.trim()) {
      reply = "Thanks for reaching out! I'd love to point you to the right team at MCA. You can tell me a bit more about what you're working on, or book a free consultation and we'll take it from there.";
    }

    // small natural delay
    await new Promise((r) => setTimeout(r, 250));
    setTyping(false);
    setMessages((prev) => [...prev, { role: "bot", text: reply.trim() }]);
  }

  const onChipClick = (label) => {
    if (label === "Book a call") {
      window.open("https://form.typeform.com/to/j6nKhXw5", "_blank", "noopener");
      return;
    }
    const map = {
      "AI automation": "I'd like to learn about your AI automation solutions.",
      "M&A advisory": "Can you tell me about MCA's M&A advisory work?",
      "Capital markets": "I'm interested in capital markets and fundraising support.",
    };
    sendMessage(map[label] || label);
  };

  const onKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div className={`atlas ${open ? "atlas--open" : ""}`}>
      {/* Launcher */}
      <button className="atlas__launcher" onClick={() => setOpen(true)} aria-label="Chat with MCA">
        <span className="atlas__orb">
          <span className="atlas__orb-glyph"><AtlasSpark size={24} /></span>
          <span className="atlas__orb-status"></span>
        </span>
        <span className="atlas__label">
          <span className="atlas__label-top">Chat with MCA</span>
          <span className="atlas__label-sub">Ask Atlas · AI</span>
        </span>
      </button>

      {/* Panel */}
      <div className="atlas__panel" role="dialog" aria-label="Chat with MCA">
        <div className="atlas__head">
          <span className="atlas__head-orb">
            <AtlasSpark size={20} />
            <span className="atlas__head-status"></span>
          </span>
          <div className="atlas__head-text">
            <div className="atlas__head-name">Atlas <span className="atlas__tag">MCA · AI</span></div>
            <div className="atlas__head-sub"><span className="dot"></span> Online · replies in seconds</div>
          </div>
          <button className="atlas__close" onClick={() => setOpen(false)} aria-label="Close chat">
            <svg width="15" height="15" viewBox="0 0 15 15" fill="none">
              <path d="M2 2L13 13M13 2L2 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
            </svg>
          </button>
        </div>

        <div className="atlas__body" ref={bodyRef}>
          {messages.map((m, i) => (
            <div key={i} className={`atlas__msg atlas__msg--${m.role === "user" ? "user" : "bot"}`}>
              {m.role === "bot" && (
                <span className="atlas__avatar"><AtlasSpark size={15} /></span>
              )}
              <div className="atlas__bubble"><AtlasText text={m.text} /></div>
            </div>
          ))}

          {typing && (
            <div className="atlas__msg atlas__msg--bot">
              <span className="atlas__avatar"><AtlasSpark size={15} /></span>
              <div className="atlas__bubble atlas__typing"><span></span><span></span><span></span></div>
            </div>
          )}

          {showChips && !typing && (
            <div className="atlas__chips">
              {ATLAS_CHIPS.map((c) => (
                <button key={c} className="atlas__chip" onClick={() => onChipClick(c)}>{c}</button>
              ))}
            </div>
          )}
        </div>

        <div className="atlas__foot">
          <div className={`atlas__inputwrap ${focused ? "atlas__inputwrap--focus" : ""}`}>
            <textarea
              ref={inputRef}
              className="atlas__input"
              rows={1}
              placeholder="Ask Atlas anything…"
              value={input}
              onFocus={() => setFocused(true)}
              onBlur={() => setFocused(false)}
              onChange={(e) => { setInput(e.target.value); autoGrow(e.target); }}
              onKeyDown={onKeyDown} />
            <button
              className="atlas__send"
              onClick={() => sendMessage()}
              disabled={!input.trim() || typing}
              aria-label="Send message">
              <svg width="17" height="17" viewBox="0 0 17 17" fill="none">
                <path d="M8.5 14.5V3M8.5 3L3.5 8M8.5 3L13.5 8"
                  stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          </div>
          <p className="atlas__disclaimer">Powered by <span className="accent">MCA AI</span></p>
        </div>
      </div>
    </div>);
}

window.AtlasChat = AtlasChat;
