// Agent configure panel — change model, edit system instructions, edit specialization.

function fmtUSDMicro(n) {
  if (n < 1) return "$" + n.toFixed(2);
  return "$" + n.toFixed(2);
}
function fmtMs(ms) {
  if (ms >= 1000) return (ms/1000).toFixed(1) + "s";
  return ms + "ms";
}

function ModelRow({ model, selected, onSelect, currentModel }) {
  const isCurrent = currentModel === model.id;
  const cheaper = currentModel ? model.pricing.in + model.pricing.out < window.MODEL_CATALOG.find(m => m.id === currentModel)?.pricing.in + window.MODEL_CATALOG.find(m => m.id === currentModel)?.pricing.out : false;
  return (
    <button
      className={"model-row" + (selected ? " selected" : "") + (isCurrent ? " current" : "")}
      onClick={() => onSelect(model.id)}
      type="button"
    >
      <div className="model-row-head">
        <span className="model-row-id mono">{model.id}</span>
        <span className="model-row-provider">{model.provider}</span>
        {isCurrent && <span className="label-pill" style={{ color: "var(--accent-text)", borderColor: "oklch(from var(--accent) l c h / 0.3)", background: "var(--accent-soft)" }}>current</span>}
        <div style={{ flex: 1 }} />
        {model.tags.map((t) => <span key={t} className="model-tag">{t}</span>)}
      </div>
      <div className="model-row-stats">
        <div className="mr-stat">
          <div className="mr-stat-label">$/M tok</div>
          <div className="mr-stat-value mono">{model.pricing.in.toFixed(2)} <span className="dim">/</span> {model.pricing.out.toFixed(2)}</div>
        </div>
        <div className="mr-stat">
          <div className="mr-stat-label">TTFT</div>
          <div className="mr-stat-value mono">{fmtMs(model.ttftMs)}</div>
        </div>
        <div className="mr-stat">
          <div className="mr-stat-label">TPS</div>
          <div className="mr-stat-value mono">{model.tps}</div>
        </div>
        <div className="mr-stat">
          <div className="mr-stat-label">Context</div>
          <div className="mr-stat-value mono">{model.ctx >= 1e6 ? (model.ctx/1e6).toFixed(1)+"M" : (model.ctx/1000)+"k"}</div>
        </div>
        <div className="mr-stat">
          <div className="mr-stat-label">Intel</div>
          <div className="mr-stat-bar">
            <div className="mr-stat-bar-fill" style={{ width: `${model.intel}%` }} />
          </div>
        </div>
      </div>
    </button>
  );
}

function AgentConfigure({ agentId, onClose }) {
  const a = agentId ? window.AGENTS[agentId] : null;
  const open = !!a;

  const [tab, setTab] = React.useState("model"); // model | instructions | tools
  const [filter, setFilter] = React.useState("all");
  const [selectedModel, setSelectedModel] = React.useState(a?.model);
  const [instructions, setInstructions] = React.useState(window.AGENT_INSTRUCTIONS?.[agentId] || "");
  const [specialization, setSpecialization] = React.useState(a?.role || "");
  const [bio, setBio] = React.useState(a?.bio || "");
  const [enabledTools, setEnabledTools] = React.useState(a?.tools || []);

  React.useEffect(() => {
    if (a) {
      setSelectedModel(a.model);
      setInstructions(window.AGENT_INSTRUCTIONS?.[a.id] || "");
      setSpecialization(a.role);
      setBio(a.bio || "");
      setEnabledTools(a.tools || []);
      setTab("model");
    }
  }, [agentId]);

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

  if (!a) return null;

  const providers = ["all", ...Array.from(new Set(window.MODEL_CATALOG.map(m => m.provider)))];
  const visibleModels = window.MODEL_CATALOG.filter(m => filter === "all" || m.provider === filter);

  const currentModelData = window.MODEL_CATALOG.find(m => m.id === a.model);
  const selectedModelData = window.MODEL_CATALOG.find(m => m.id === selectedModel);
  const changed = selectedModel !== a.model || instructions !== (window.AGENT_INSTRUCTIONS?.[a.id] || "") || specialization !== a.role || bio !== a.bio;

  // Estimate delta if model changes — uses today's token volume.
  const todayInM = a.tokens.today.in / 1e6;
  const todayOutM = a.tokens.today.out / 1e6;
  const currentDailyCost = todayInM * (currentModelData?.pricing.in || 0) + todayOutM * (currentModelData?.pricing.out || 0);
  const newDailyCost = selectedModelData ? todayInM * selectedModelData.pricing.in + todayOutM * selectedModelData.pricing.out : currentDailyCost;
  const costDelta = newDailyCost - currentDailyCost;

  const apply = async () => {
    try {
      await window.api.configureAgent(a.id, {
        model: selectedModel,
        instructions,
        tools: enabledTools,
      });
      a.model = selectedModel;
      if (selectedModelData) {
        a.provider = selectedModelData.provider;
        a.pricing = selectedModelData.pricing;
        a.contextWindow = selectedModelData.ctx;
        a.avgLatencyMs = selectedModelData.ttftMs + (1000 / selectedModelData.tps) * 200;
      }
      a.role = specialization;
      a.bio = bio;
      a.tools = enabledTools;
      window.AGENT_INSTRUCTIONS[a.id] = instructions;
    } catch (e) {
      console.error("configure failed", e);
    }
    onClose();
  };

  return (
    <>
      <div className={"agent-modal-wrap" + (open ? " open" : "")} onClick={onClose}>
        <div className="agent-modal cfg-modal" onClick={(e) => e.stopPropagation()}>
          <button className="drawer-close agent-modal-close" onClick={onClose}><window.Icon.Close /></button>

          <div className="cfg-head">
            <div className="cfg-head-row">
              <window.Avatar who={a.id} size={32} />
              <div>
                <div className="cfg-eyebrow">Configure agent</div>
                <h2 className="cfg-title">{a.name}</h2>
              </div>
              <div style={{ flex: 1 }} />
              <div className="cfg-tabs">
                {[
                  { id: "model", label: "Model" },
                  { id: "instructions", label: "Instructions" },
                  { id: "tools", label: "Tools & role" },
                ].map((t) => (
                  <button
                    key={t.id}
                    className={"cfg-tab" + (tab === t.id ? " active" : "")}
                    onClick={() => setTab(t.id)}
                  >
                    {t.label}
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div className="cfg-body">
            {tab === "model" && (
              <>
                <div className="cfg-section-title">Choose a model</div>
                <div className="cfg-section-sub">
                  Other agents read these costs and latencies to decide whether to delegate to <strong>{a.name}</strong>.
                </div>
                <div className="cfg-filter-row">
                  {providers.map((p) => (
                    <button
                      key={p}
                      className={"filter-pill" + (filter === p ? " active" : "")}
                      onClick={() => setFilter(p)}
                    >
                      {p === "all" ? "All providers" : p}
                    </button>
                  ))}
                </div>
                <div className="model-list">
                  {visibleModels.map((m) => (
                    <ModelRow
                      key={m.id}
                      model={m}
                      selected={selectedModel === m.id}
                      onSelect={setSelectedModel}
                      currentModel={a.model}
                    />
                  ))}
                </div>

                {selectedModel !== a.model && selectedModelData && (
                  <div className="cfg-delta">
                    <div className="cfg-delta-title">Estimated impact (based on today's volume)</div>
                    <div className="cfg-delta-grid">
                      <div>
                        <div className="cfg-delta-label">Daily cost</div>
                        <div className="cfg-delta-value mono">
                          ${currentDailyCost.toFixed(2)} <span className="arrow">→</span> ${newDailyCost.toFixed(2)}
                          <span className={"cfg-delta-chip " + (costDelta < 0 ? "good" : costDelta > 0 ? "warn" : "")}>
                            {costDelta >= 0 ? "+" : ""}{costDelta.toFixed(2)}
                          </span>
                        </div>
                      </div>
                      <div>
                        <div className="cfg-delta-label">TTFT</div>
                        <div className="cfg-delta-value mono">
                          {fmtMs(currentModelData.ttftMs)} <span className="arrow">→</span> {fmtMs(selectedModelData.ttftMs)}
                        </div>
                      </div>
                      <div>
                        <div className="cfg-delta-label">Throughput</div>
                        <div className="cfg-delta-value mono">
                          {currentModelData.tps} <span className="arrow">→</span> {selectedModelData.tps} tok/s
                        </div>
                      </div>
                      <div>
                        <div className="cfg-delta-label">Context</div>
                        <div className="cfg-delta-value mono">
                          {(currentModelData.ctx/1000)|0}k <span className="arrow">→</span> {selectedModelData.ctx >= 1e6 ? (selectedModelData.ctx/1e6).toFixed(1)+"M" : (selectedModelData.ctx/1000)+"k"}
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}

            {tab === "instructions" && (
              <>
                <div className="cfg-section-title">System instructions</div>
                <div className="cfg-section-sub">
                  Sent at the start of every {a.name} run. Other agents see this when deciding to delegate.
                </div>
                <textarea
                  className="cfg-textarea mono"
                  value={instructions}
                  onChange={(e) => setInstructions(e.target.value)}
                  rows={16}
                  spellCheck={false}
                />
                <div className="cfg-hint">{instructions.length.toLocaleString()} chars · ~{Math.round(instructions.length / 4).toLocaleString()} tokens · charged on every run</div>
              </>
            )}

            {tab === "tools" && (
              <>
                <div className="cfg-section-title">Specialization</div>
                <div className="cfg-section-sub">A short label other agents use to find {a.name}.</div>
                <input
                  className="cfg-input"
                  value={specialization}
                  onChange={(e) => setSpecialization(e.target.value)}
                />

                <div className="cfg-section-title" style={{ marginTop: 18 }}>Bio</div>
                <textarea
                  className="cfg-textarea"
                  value={bio}
                  onChange={(e) => setBio(e.target.value)}
                  rows={3}
                />

                <div className="cfg-section-title" style={{ marginTop: 18 }}>Tools</div>
                <div className="cfg-section-sub">Toggle tools {a.name} can call.</div>
                <div className="cfg-tool-grid">
                  {["read_file", "edit_file", "shell", "run_tests", "git", "search_web", "read_url", "search_docs", "tts_synthesize", "split_chapters", "encode_mp3", "comment_pr", "read_diff", "ask_human", "create_subtask"].map((t) => {
                    const on = enabledTools.includes(t);
                    return (
                      <button
                        key={t}
                        type="button"
                        className={"cfg-tool" + (on ? " on" : "")}
                        onClick={() => setEnabledTools(on ? enabledTools.filter(x => x !== t) : [...enabledTools, t])}
                      >
                        <span className="cfg-tool-check">{on ? "✓" : ""}</span>
                        <span className="mono">{t}</span>
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>

          <div className="cfg-foot">
            <div className="cfg-foot-summary mono">
              {a.name} · {selectedModel} · {selectedModelData?.provider}
            </div>
            <div style={{ flex: 1 }} />
            <button className="btn ghost" onClick={onClose}>Cancel</button>
            <button className="btn primary" disabled={!changed} style={{ opacity: changed ? 1 : 0.4 }} onClick={apply}>
              Save changes
            </button>
          </div>
        </div>
      </div>
    </>
  );
}

window.AgentConfigure = AgentConfigure;
