/* ============================================================
   Assistant — the front door. Talk to Claude; it runs prospecting.
   Surfaces target cards, drafts on command, answers pipeline Qs.
   ============================================================ */

// compact target card Claude proposes inline
function SuggestCard({ t, onApprove, onDraft, onDecline, onOpen, done }) {
  const pm = window.PRIORITY_META[t.priority] || { label: t.stage, color: "var(--text-2)", icon: "flag" };
  const contact = t.contacts[0];
  const stop = (fn) => (e) => { e.stopPropagation(); fn(); };
  return (
    <div className="suggest-card lift" data-done={done || undefined} onClick={() => !done && onOpen(t)} style={{ cursor: done ? "default" : "pointer" }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 11 }}>
        <Avatar mono={t.mono} size={38} square />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <span style={{ fontSize: 14, fontWeight: 670, whiteSpace: "nowrap" }}>{t.brand}</span>
            <LaneChip lane={t.lane} small />
            <span style={{ fontSize: 11, fontWeight: 650, color: pm.color, display: "inline-flex", alignItems: "center", gap: 3 }}>
              <Icon name={pm.icon} size={11} />{pm.label}
            </span>
          </div>
          <div style={{ fontSize: 12.5, color: "var(--text-2)", marginTop: 4, lineHeight: 1.5 }}>{t.whyNow}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 8 }}>
            <Avatar name={contact.name} initials={contact.initials} color={contact.color} size={20} />
            <span style={{ fontSize: 12, color: "var(--text-2)" }}>{contact.name} · <span style={{ color: "var(--text-3)" }}>{contact.title}</span></span>
            <span className="num" style={{ marginLeft: "auto", fontSize: 11, color: "var(--text-3)" }}>{t.cadence.label}</span>
          </div>
        </div>
      </div>
      <div className="suggest-actions">
        {done ? (
          <span style={{ fontSize: 12, color: "var(--green)", display: "inline-flex", alignItems: "center", gap: 5 }}>
            <Icon name="check" size={14} /> {done}
          </span>
        ) : (
          <React.Fragment>
            <button className="btn btn--sm btn--ghost" onClick={stop(() => onDecline(t.id))}>Not today</button>
            <button className="btn btn--sm" onClick={stop(() => onOpen(t))}><Icon name="draft" size={13} /> Open draft</button>
            <button className="btn btn--primary btn--sm" onClick={stop(() => onApprove(t))}><Icon name="sparkles" size={13} /> Approve & send</button>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

function Thinking() {
  return (
    <div className="msg-claude">
      <div className="claude-orb"><Icon name="sparkles" size={15} /></div>
      <div className="bubble bubble--claude" style={{ display: "inline-flex", gap: 5, alignItems: "center" }}>
        <span className="think-dot"></span><span className="think-dot"></span><span className="think-dot"></span>
      </div>
    </div>
  );
}

function Assistant({ lane, onApprove, onDraft }) {
  const W = window.WTC;
  const seedCards = W.todayQueue.filter((t) => lane === "all" || t.lane === lane).slice(0, 5).map((t) => t.id);
  const [msgs, setMsgs] = React.useState(() => [{
    role: "claude", live: false,
    text: `Morning, Preston. I'm your prospecting brain — I find targets, draft outreach in your voice, and track the pipeline. Ask me anything, or get your daily round-up to see what's waiting.`,
  }]);
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const [done, setDone] = React.useState({});       // targetId -> label
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [msgs, thinking]);

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || thinking) return;
    setInput("");
    setMsgs((m) => [...m, { role: "me", text: q }]);
    setThinking(true);
    const res = await window.assistantBrain.ask(q);
    setThinking(false);
    const cards = res.targetIds && res.targetIds.length ? res.targetIds : null;
    setMsgs((m) => [...m, { role: "claude", text: res.text, live: res.live, cards, draftTargetId: res.draftTargetId }]);
    // auto-open composer when Claude prepared a specific draft
    if (res.intent === "draft" && res.draftTargetId) setTimeout(() => onDraft(res.draftTargetId), 350);
  };

  const approve = (t) => { setDone((d) => ({ ...d, [t.id]: "Approved" })); onApprove(t); };
  const decline = (id) => setDone((d) => ({ ...d, [id]: "Snoozed" }));
  const draft = (id) => onDraft(id);
  // open the composer; when it closes, auto-mark the card approved
  const open = (t) => onDraft(t.id, t.contacts[0].id, () => setDone((d) => ({ ...d, [t.id]: "Approved" })));

  return (
    <div className="assistant-surface">
      <div className="assistant-head">
        <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
          <div className="claude-orb claude-orb--lg"><Icon name="sparkles" size={19} /></div>
          <div>
            <h1 className="page-title" style={{ display: "flex", alignItems: "center", gap: 9 }}>
              Assistant
              <span className="live-tag"><span className="stagedot" style={{ background: "var(--green)" }}></span>{(window.claude && window.claude.complete) ? "Claude connected" : "Demo brain"}</span>
            </h1>
            <p className="page-sub">Claude runs your prospecting — it finds targets, decides who to reach, and drafts every note. You approve.</p>
          </div>
        </div>
      </div>

      <div className="assistant-thread" ref={scrollRef}>
        <div className="assistant-thread-inner">
          {msgs.map((m, i) => m.role === "me" ? (
            <div key={i} className="msg-me"><div className="bubble bubble--me">{m.text}</div></div>
          ) : (
            <div key={i} className="msg-claude">
              <div className="claude-orb"><Icon name="sparkles" size={15} /></div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="bubble bubble--claude">{m.text}</div>
                {m.cards && (
                  <div className="suggest-grid">
                    {m.cards.map((id) => {
                      const t = W.targets.find((x) => x.id === id);
                      return t ? <SuggestCard key={id} t={t} onApprove={approve} onDecline={decline} onDraft={draft} onOpen={open} done={done[id]} /> : null;
                    })}
                  </div>
                )}
              </div>
            </div>
          ))}
          {thinking && <Thinking />}
        </div>
      </div>

      <div className="assistant-compose">
        <div className="suggest-chips">
          {window.assistantBrain.SUGGESTIONS.map((s) => (
            <button key={s} className="refine-chip" onClick={() => send(s)} disabled={thinking}>{s}</button>
          ))}
        </div>
        <div className="assistant-input">
          <Icon name="sparkles" size={17} style={{ color: "var(--accent)", flex: "none" }} />
          <input placeholder="Ask Claude to find targets, draft outreach, or read your pipeline…"
            value={input} onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && send()} />
          <button className="btn btn--primary btn--icon" onClick={() => send()} disabled={thinking || !input.trim()}>
            <Icon name="send" size={16} />
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Assistant });
