/* ai-chat.jsx — chat widget, calls /api/chat serverless endpoint */

const SUGGESTIONS = [
  { label: "I have a project in mind", prompt: "I have a project in mind I'd like to discuss." },
  { label: "What do you do?", prompt: "What does Reagan do? Walk me through his services." },
  { label: "Draft me a brief", prompt: "Help me draft a project brief I can email to Reagan." },
  { label: "How much does an AI agent cost?", prompt: "Roughly how much does building an AI WhatsApp concierge cost?" },
];

function SparkIcon({ className = "spark" }) {
  return (
    <svg className={className} viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
      <path d="M10 1l1.8 5.4L17 8l-5.2 1.6L10 15l-1.8-5.4L3 8l5.2-1.6L10 1z" />
    </svg>
  );
}
function ArrowUpIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M12 19V5" />
      <path d="M5 12l7-7 7 7" />
    </svg>
  );
}
function ArrowOutIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M7 17L17 7" />
      <path d="M8 7h9v9" />
    </svg>
  );
}

function CmdBar({ value, onChange, onSubmit, placeholder }) {
  return (
    <form
      className="cmd"
      onSubmit={(e) => { e.preventDefault(); if (value.trim()) onSubmit(value.trim()); }}
    >
      <SparkIcon />
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder || "Ask me anything…"}
        aria-label="Message Reagan's AI"
      />
      <button type="submit" className="cmd-send" aria-label="Send">
        <ArrowUpIcon />
      </button>
    </form>
  );
}

function HeroCmd({ onLaunch }) {
  const [val, setVal] = React.useState("");
  const placeholders = React.useMemo(() => ([
    "Tell me about your project…",
    "What does Reagan actually do?",
    "I need an AI agent for my hotel…",
    "Build me a booking platform…",
    "Draft me a project brief…",
  ]), []);
  const [phIdx, setPhIdx] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setPhIdx(i => (i + 1) % placeholders.length), 3200);
    return () => clearInterval(t);
  }, [placeholders.length]);

  return (
    <div className="cmd-wrap">
      <CmdBar
        value={val}
        onChange={setVal}
        onSubmit={(text) => { onLaunch(text); setVal(""); }}
        placeholder={placeholders[phIdx]}
      />
      <div className="cmd-chips">
        {SUGGESTIONS.slice(0, 3).map((s) => (
          <button key={s.label} className="chip" onClick={() => onLaunch(s.prompt)}>
            {s.label} →
          </button>
        ))}
      </div>
    </div>
  );
}

function parseBrief(text) {
  const m = text.match(/\[\[BRIEF\]\]([\s\S]*?)\[\[\/BRIEF\]\]/);
  if (!m) return { brief: null, rest: text };
  const brief = m[1].trim();
  const rest = (text.slice(0, m.index) + text.slice(m.index + m[0].length)).trim();
  return { brief, rest };
}

function BriefCard({ body }) {
  const mailto = () => {
    const subject = encodeURIComponent("Project brief via reaganpieter.com");
    const lead = "Hi Reagan,\n\nDrafted this with your AI on your site:\n\n";
    const tail = "\n\nLet's talk?\n";
    return `mailto:contact@reaganpieter.com?subject=${subject}&body=${encodeURIComponent(lead + body + tail)}`;
  };
  const copy = async () => {
    try { await navigator.clipboard.writeText(body); } catch (_) {}
  };
  // colorize labels
  const lines = body.split("\n");
  return (
    <div className="brief-card">
      <div style={{ fontFamily: "Archivo, sans-serif", fontWeight: 900, fontSize: 13, letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 10, color: "var(--accent)" }}>
        Project brief, draft
      </div>
      {lines.map((line, i) => {
        const idx = line.indexOf(":");
        if (idx > 0 && idx < 18) {
          return (
            <div key={i}>
              <span className="label">{line.slice(0, idx)}:</span>
              {line.slice(idx + 1)}
            </div>
          );
        }
        return <div key={i}>{line || "\u00A0"}</div>;
      })}
      <div className="brief-actions">
        <a className="brief-btn" href={mailto()}>
          Send to Reagan <ArrowOutIcon />
        </a>
        <button className="brief-btn ghost" onClick={copy}>Copy</button>
      </div>
    </div>
  );
}

function ChatSection({ initial, onClearInitial }) {
  const [messages, setMessages] = React.useState([
    {
      role: "ai",
      content:
        "Hey, I'm Reagan's AI. I know his work, his services, and the kind of projects he takes on.\n\nTell me what you're trying to build, or pick one of the prompts below.",
    },
  ]);
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [showSuggest, setShowSuggest] = React.useState(true);
  const bodyRef = React.useRef(null);
  const seededRef = React.useRef(false);

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

  const send = React.useCallback(async (text) => {
    if (!text || busy) return;
    setShowSuggest(false);
    const nextMsgs = [...messages, { role: "user", content: text }];
    setMessages(nextMsgs);
    setInput("");
    setBusy(true);

    const apiMessages = nextMsgs.map(m => ({
      role: m.role === "ai" ? "assistant" : "user",
      content: m.content,
    }));

    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: apiMessages }),
      });
      if (!res.ok) throw new Error("api failed");
      const { reply } = await res.json();
      setMessages(prev => [...prev, { role: "ai", content: reply }]);
    } catch (err) {
      setMessages(prev => [...prev, {
        role: "ai",
        content: "Hmm, I couldn't reach the AI just now. Try again in a moment, or email contact@reaganpieter.com directly.",
      }]);
    } finally {
      setBusy(false);
    }
  }, [busy, messages]);

  // Handle initial prompt from hero
  React.useEffect(() => {
    if (initial && !seededRef.current) {
      seededRef.current = true;
      // Scroll to chat first
      const el = document.getElementById("chat");
      if (el) el.scrollIntoView ? window.scrollTo({ top: el.offsetTop - 20, behavior: "smooth" }) : null;
      send(initial);
      if (onClearInitial) onClearInitial();
    }
  }, [initial, send, onClearInitial]);

  return (
    <section id="chat" className="section ai-section">
      <div className="container">
        <div className="ai-head">
          <div>
            <div className="eyebrow on-light"><span className="num">03</span> · TALK TO MY AI</div>
            <h2 className="display ai-title" style={{ marginTop: 18 }}>
              Discuss your<br/>project<span className="blink"></span>
            </h2>
          </div>
          <p className="ai-lede">
            Trained on what I do, how I work, and what I charge. Ask for a rough scope, a service breakdown,
            or have it draft a brief you can send straight to my inbox.
          </p>
        </div>

        <div className="chat-shell">
          <div className="chat-top">
            <div className="chat-id">
              <div className="av">RP</div>
              <div>
                <strong>Reagan's AI</strong>
                <span>powered by Claude · trained on Reagan's work</span>
              </div>
            </div>
            <div className="chat-status">Online</div>
          </div>

          <div className="chat-body" ref={bodyRef}>
            {messages.map((m, i) => {
              if (m.role === "ai") {
                const { brief, rest } = parseBrief(m.content);
                return (
                  <React.Fragment key={i}>
                    {rest && <div className="msg ai">{rest}</div>}
                    {brief && <BriefCard body={brief} />}
                  </React.Fragment>
                );
              }
              return <div key={i} className="msg user">{m.content}</div>;
            })}
            {busy && (
              <div className="msg ai thinking" aria-label="Thinking">
                <span></span><span></span><span></span>
              </div>
            )}
          </div>

          {showSuggest && (
            <div className="chat-suggest">
              {SUGGESTIONS.map(s => (
                <button key={s.label} className="chip" onClick={() => send(s.prompt)}>{s.label}</button>
              ))}
            </div>
          )}

          <form
            className="chat-input-row"
            onSubmit={(e) => { e.preventDefault(); send(input.trim()); }}
          >
            <SparkIcon />
            <input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Type a message…"
              aria-label="Type a message"
              disabled={busy}
            />
            <button type="submit" className="cmd-send" disabled={busy || !input.trim()} aria-label="Send">
              <ArrowUpIcon />
            </button>
          </form>
        </div>

        <div className="chat-hint">
          <span className="kbd">↵</span> to send · responses are AI-generated, not legal/binding quotes
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { HeroCmd, ChatSection, SparkIcon, ArrowUpIcon });
