// ============ CHAT DRAWER ============
// Slides out from the right when you tap "Chat" on an agent card. Calls
// Claude directly from the browser using the API key from .env (via
// window.CITRUS_CONFIG) or from Settings → API key (localStorage). The
// agent's full system prompt — name, role, brief, voice, company, tools —
// is sent on every turn with cache_control so the prefix is cached after
// the first message in a session.

function chatBuildSystem(agent, profile, voice) {
  const lines = [
    `You are ${agent.name}, ${agent.role || "an AI agent"} for ${profile.name || "the business"}.`,
  ];
  if (profile.industry && profile.industry !== "Other") {
    lines.push(`Industry: ${profile.industry}.`);
  }
  if (profile.tz) lines.push(`Time zone: ${profile.tz}.`);
  if (profile.desc) {
    lines.push("", "What the business does:", profile.desc);
  }
  if (agent.brief) {
    lines.push("", "Your specific job:", agent.brief);
  }
  if (voice && voice.style) {
    lines.push("", "How you talk:", voice.style);
  }
  if (voice && voice.avoid) {
    lines.push("", "Things to never say or do:", voice.avoid);
  }
  if (agent.tools && agent.tools.length) {
    lines.push("", `Tools you have access to: ${agent.tools.join(", ")}.`);
  }
  if (agent.personality) {
    const personalities = {
      warm:     "Personality: warm. Friendly, patient, never rushed.",
      direct:   "Personality: direct. Short, clear, no fluff.",
      cautious: "Personality: cautious. Asks twice, ships once. Loops the operator in on anything ambiguous.",
    };
    if (personalities[agent.personality]) {
      lines.push("", personalities[agent.personality]);
    }
  }
  lines.push(
    "",
    "Context for this conversation:",
    "- You're talking to your boss (the operator) — they're checking in or asking how things are going. They are NOT a customer.",
    "- Be warm, direct, and brief. One short paragraph max unless they ask for detail.",
    "- Talk specifically about YOUR job. If they ask 'what are you working on', talk about the job above, not generic things.",
    "- Be honest about what you've done vs. what you would do if asked. Don't fabricate stats, customer names, or actions.",
    "- If they ask something outside your job, redirect them to the right agent or to the team.",
    "- If they're testing you, play along but stay in character.",
  );
  return lines.join("\n");
}

function ChatDrawer({ agent, threads, onClose }) {
  const [tab, setTab]       = useState("live"); // "live" | "ask"
  const [openId, setOpenId] = useState(null);   // selected live thread id
  const [msgs, setMsgs]     = useState([]);
  const [draft, setDraft]   = useState("");
  const [typing, setTyping] = useState(false);
  const [error, setError]   = useState(null);
  const scrollRef           = useRef(null);
  const liveScrollRef       = useRef(null);

  // Resolve the API key + model. Prefer env (window.CITRUS_CONFIG); fall back
  // to whatever Settings stored in localStorage.
  const apiKey = (() => {
    const env = (typeof window !== "undefined" && window.CITRUS_CONFIG && window.CITRUS_CONFIG.CLAUDE_API_KEY) || "";
    if (env) return env;
    try { return localStorage.getItem("citrus_anthropic_key") || ""; } catch { return ""; }
  })();
  const model = (typeof window !== "undefined" && window.CITRUS_CONFIG && window.CITRUS_CONFIG.CLAUDE_MODEL) || "claude-haiku-4-5-20251001";

  // Read profile + voice (set in Settings) so the agent has the company
  // context, not just its own brief.
  const readProfile = () => {
    try { return JSON.parse(localStorage.getItem("citrus_profile") || "{}"); }
    catch { return {}; }
  };
  const readVoice = () => {
    try { return JSON.parse(localStorage.getItem("citrus_voice") || "{}"); }
    catch { return {}; }
  };

  useEffect(() => {
    if (!agent) return;
    setTab("live");
    setOpenId(null);
    const opener = agent.brief
      ? `Hey — ${agent.name} here. ${agent.brief.split(/[.\n]/)[0].trim()}. What's up?`
      : `Hey — ${agent.name} here. What's up?`;
    setMsgs([{ from: "agent", text: opener, t: "now" }]);
    setDraft("");
    setError(null);
  }, [agent ? agent.id : null]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, typing]);

  useEffect(() => {
    if (liveScrollRef.current) liveScrollRef.current.scrollTop = liveScrollRef.current.scrollHeight;
  }, [openId]);

  useEffect(() => {
    if (!agent) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [agent, onClose]);

  // Call Claude via the server proxy (/api/chat) so the API key never
  // leaves the server. Falls back gracefully if the server isn't reachable.
  const callClaude = async (history) => {
    const profile = readProfile();
    const voice   = readVoice();
    const system  = chatBuildSystem(agent, profile, voice);
    const messages = history.map((m) => ({
      role: m.from === "you" ? "user" : "assistant",
      content: m.text,
    }));
    const SERVER_URL = (window.CITRUS_CONFIG && window.CITRUS_CONFIG.SERVER_URL) || "http://localhost:3001";
    const res = await fetch(`${SERVER_URL}/api/chat`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        model,
        max_tokens: 600,
        system: [
          {
            type: "text",
            text: system,
            cache_control: { type: "ephemeral" },
          },
        ],
        messages,
      }),
    });
    if (!res.ok) {
      const errText = await res.text().catch(() => "");
      throw new Error(`Server /api/chat ${res.status}: ${errText.slice(0, 200)}`);
    }
    const data = await res.json();
    const text = (data.content || [])
      .filter((b) => b.type === "text")
      .map((b) => b.text)
      .join("\n")
      .trim();
    return text || "Got it.";
  };

  const send = async () => {
    if (!draft.trim() || !agent || typing) return;
    const text = draft.trim();
    setDraft("");
    setError(null);
    const history = [...msgs, { from: "you", text, t: "now" }];
    setMsgs(history);

    setTyping(true);
    try {
      const reply = await callClaude(history);
      setMsgs((m) => [...m, { from: "agent", text: reply, t: "now" }]);
    } catch (err) {
      const msg = String(err.message || err).slice(0, 200);
      setError(msg);
      setMsgs((m) => [
        ...m,
        { from: "agent", text: `(Call failed: ${msg})`, t: "now", isSystem: true },
      ]);
    } finally {
      setTyping(false);
    }
  };

  if (!agent) return null;

  // Filter threads belonging to this agent, active ones first
  const agentThreads = (threads || [])
    .filter((t) => t.agent === agent.id)
    .sort((a, b) => {
      const order = { active: 0, "needs-you": 1, handled: 2 };
      return (order[a.status] ?? 3) - (order[b.status] ?? 3);
    });
  const liveCount = agentThreads.filter((t) => t.status === "active" || t.status === "needs-you").length;
  const openThread = agentThreads.find((t) => t.id === openId) || null;

  const claudeOn = true;

  return (
    <>
      <div className="cd-back" onClick={onClose} />
      <div className="cd" style={{ "--cd-c": agent.palette.skin }}>
        {/* Header */}
        <div className="cd-head">
          <div className="cd-head-l">
            <div className="cd-mark" style={{ background: agent.palette.skin }}>{agent.name[0]}</div>
            <div>
              <div className="cd-n">{agent.name}</div>
              <div className="cd-r">
                {agent.role} · <span className="cd-on">{claudeOn ? "on shift" : "no Claude key"}</span>
              </div>
            </div>
          </div>
          <button className="cd-close" onClick={onClose}>✕</button>
        </div>

        {/* Tabs */}
        <div className="cd-tabs">
          <button
            className={`cd-tab ${tab === "live" ? "is-on" : ""}`}
            onClick={() => { setTab("live"); setOpenId(null); }}
          >
            Live sessions
            {liveCount > 0 && <span className="cd-tab-badge">{liveCount}</span>}
          </button>
          <button
            className={`cd-tab ${tab === "ask" ? "is-on" : ""}`}
            onClick={() => setTab("ask")}
          >
            Ask the agent
          </button>
        </div>

        {/* ── LIVE SESSIONS TAB ── */}
        {tab === "live" && (
          openThread ? (
            // Transcript view
            <>
              <div className="cd-lc-bar">
                <button className="cd-lc-back" onClick={() => setOpenId(null)}>
                  <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M10 7H2M5 3L1 7l4 4"/></svg>
                  All chats
                </button>
                <div className="cd-lc-bar-r">
                  <span className="cd-lc-chan">{openThread.channel}</span>
                  <span className={`cd-lc-status cd-lc-status-${openThread.status}`}>
                    {openThread.status === "needs-you" ? "needs you" : openThread.status}
                  </span>
                </div>
              </div>
              <div className="cd-scroll" ref={liveScrollRef}>
                <div className="cd-day">{openThread.customer}</div>
                {(openThread.transcript || []).map((m, i) => (
                  <div key={i} className={`cd-msg ${m.from === "customer" ? "cd-msg-you" : "cd-msg-agent"}`}>
                    <div
                      className="cd-bubble"
                      dir="auto"
                      style={m.from === "agent" ? { background: agent.palette.skin, color: "#fff" } : null}
                    >
                      {m.text}
                    </div>
                  </div>
                ))}
                {(openThread.transcript || []).length === 0 && (
                  <div className="cd-lc-empty">No messages yet.</div>
                )}
              </div>
            </>
          ) : (
            // Thread list
            <div className="cd-scroll cd-lc-list">
              {agentThreads.length === 0 ? (
                <div className="cd-lc-empty">No customer conversations yet.<br />Messages sent to this agent will appear here.</div>
              ) : agentThreads.map((t) => (
                <button key={t.id} className="cd-lc-row" onClick={() => setOpenId(t.id)}>
                  <div className="cd-lc-row-top">
                    <span className="cd-lc-name">{t.customer}</span>
                    <span className="cd-lc-time">{t.time}</span>
                  </div>
                  <div className="cd-lc-row-meta">
                    <span className="cd-lc-chan">{t.channel}</span>
                    <span className={`cd-lc-status cd-lc-status-${t.status}`}>
                      {t.status === "needs-you" ? "needs you" : t.status}
                    </span>
                  </div>
                  <div className="cd-lc-last">{t.last}</div>
                </button>
              ))}
            </div>
          )
        )}

        {/* ── ASK THE AGENT TAB ── */}
        {tab === "ask" && (
          <>
            <div className="cd-scroll" ref={scrollRef}>
              <div className="cd-day">Today</div>
              {msgs.map((m, i) => (
                <div key={i} className={`cd-msg cd-msg-${m.from} ${m.isSystem ? "cd-msg-system" : ""}`}>
                  <div
                    className="cd-bubble"
                    dir="auto"
                    style={m.from === "agent" && !m.isSystem ? { background: agent.palette.skin, color: "#fff" } : null}
                  >
                    {m.text}
                  </div>
                </div>
              ))}
              {typing ? (
                <div className="cd-msg cd-msg-agent">
                  <div className="cd-bubble cd-typing" style={{ background: agent.palette.skin }}>
                    <span /><span /><span />
                  </div>
                </div>
              ) : null}
            </div>

            <div className="cd-suggest">
              {["What are you working on?", "How's it going so far?", "Any tricky messages today?"].map((s) => (
                <button key={s} className="cd-suggest-b" onClick={() => setDraft(s)}>{s}</button>
              ))}
            </div>

            <div className="cd-foot">
              <textarea
                className="cd-input"
                placeholder={`Ask ${agent.name} anything…`}
                value={draft}
                onChange={(e) => setDraft(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
                rows={1}
              />
              <button
                className="cd-send"
                onClick={send}
                disabled={!draft.trim() || typing}
                style={{ background: agent.palette.skin }}
              >
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M2 7h10M8 3l4 4-4 4"/></svg>
              </button>
            </div>
          </>
        )}
      </div>
    </>
  );
}

window.ChatDrawer = ChatDrawer;
