/* eslint-disable */
// Neuron — chatbot. Pre-canned Q&A + free-text fallback.
const { useState, useRef, useEffect } = React;

// Pre-canned Q&A — instant answers, no API
const QA = [
  {
    q: "What does Neuron do?",
    a: "I launch tech and finance memecoins on Solana, end to end. I research a narrative, name the coin, register a domain, ship a single-page site, and mint the token. You sign once. Everything stays in your name.",
  },
  {
    q: "How much does it cost?",
    a: "Free for now — no agent fee while we're early. Domain at cost (~$10–15), Solana network fees at cost (under $1). If a step fails before mint, you don't pay.",
  },
  {
    q: "How long does a launch take?",
    a: "Usually a few minutes start to finish — research, naming, domain registration, site deploy, treasury wiring, and the mint tx. It varies with how much research the narrative needs.",
  },
  {
    q: "Can the coin's fees buy real stocks?",
    a: "Yes. I wire a fee router into the token at deploy. A configurable share of trading fees (typical 1–2%) routes into a tokenized-equity treasury via Printr — S&P basket, T-bills, single names. Held in your wallet's name.",
  },
  {
    q: "Whose coin is it after launch?",
    a: "Yours. Fully. Mint authority, contract, domain, site repo, and treasury are all under your wallet and account. I'm just the agent that does the work.",
  },
  {
    q: "Where does it launch?",
    a: "On Printr — Solana mainnet, omnichain liquidity, configurable fee router. I handle metadata, IPFS, and the deploy tx. You sign with your wallet. I'm the first AI agent built for Printr.",
  },
  {
    q: "Can I edit the website it makes?",
    a: "Yes. The site ships as a static React + Tailwind project deployed to the edge. You get the source repo, the domain, and one-click redeploy from the dashboard. Hand it to a dev whenever.",
  },
  {
    q: "Can I steer it mid-run?",
    a: "Yes. The run pauses at three points — narrative-locked, brand-locked, and pre-mint. You can redirect, regenerate, or cancel. Once the deploy tx fires, it's on-chain and final, in your name.",
  },
  {
    q: "How do I start?",
    a: "Click \"Launch your coin\" in the top right. Connect your wallet, give me a vibe, pick venue and treasury, and approve the launch. A few minutes later your coin is live.",
  },
];

function Chatbot() {
  const [open, setOpen] = useState(false);
  const [messages, setMessages] = useState([
    { role: 'bot', text: "I'm Neuron — the first AI agent for Printr. I launch memecoins end to end on Solana. Pick a question below.", t: nowStamp() },
  ]);
  const [busy, setBusy] = useState(false);
  const [askedSet, setAskedSet] = useState(new Set());
  const bodyRef = useRef(null);

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

  // Pre-canned: instant question + typed answer, no API call
  const askPreset = (item) => {
    if (busy) return;
    const userMsg = { role: 'user', text: item.q, t: nowStamp() };
    setMessages((cur) => [...cur, userMsg]);
    setAskedSet((cur) => new Set(cur).add(item.q));
    setBusy(true);
    // realistic typing delay before answer appears
    setTimeout(() => {
      setMessages((cur) => [...cur, { role: 'bot', text: item.a, t: nowStamp() }]);
      setBusy(false);
    }, 600 + Math.random() * 500);
  };

  const remainingQA = QA.filter((p) => !askedSet.has(p.q));

  if (!open) {
    return (
      <button className="chatbot-fab" onClick={() => setOpen(true)} aria-label="Open chat with Neuron">
        <span className="pulse-ring" />
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
        </svg>
      </button>
    );
  }

  return (
    <div className="chatbot" role="dialog" aria-label="Chat with Neuron">
      <div className="head">
        <div className="avatar" />
        <div className="who">
          <div className="name">Neuron</div>
          <div className="status">online · agent</div>
        </div>
        <button onClick={() => setOpen(false)} aria-label="Close chat">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12"/>
          </svg>
        </button>
      </div>

      <div className="body" ref={bodyRef}>
        {messages.map((m, i) => (
          <div className={`msg ${m.role}`} key={i}>
            <div className="bubble">{m.text}</div>
            <div className="meta">{m.t}</div>
          </div>
        ))}
        {busy && (
          <div className="typing"><span/><span/><span/></div>
        )}
      </div>

      {!busy && remainingQA.length > 0 && (
        <div className="qa-footer">
          <div className="qa-label">{messages.length === 1 ? 'Frequent questions' : 'More you can ask'}</div>
          <div className="qa-list">
            {remainingQA.slice(0, 4).map((p) => (
              <button key={p.q} className="qa-pill" onClick={() => askPreset(p)}>
                {p.q}
                <span className="qa-arrow">→</span>
              </button>
            ))}
          </div>
        </div>
      )}
      {!busy && remainingQA.length === 0 && (
        <div className="qa-footer">
          <a href="/try" className="qa-pill">
            Try a live run
            <span className="qa-arrow">→</span>
          </a>
        </div>
      )}

    </div>
  );
}

function nowStamp() {
  const d = new Date();
  return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}

window.Chatbot = Chatbot;
