import { useState, useEffect } from "react";
import { Plug, Zap, Package, Dna } from "lucide-react";
import type { CapabilitySecurityReport, QuarantinedImportRecord } from "../../shared/types";
import { getEmojiIcon } from "../utils/emoji-icon-map";
import { MESSAGE_SHORTCUTS_UPDATED_EVENT } from "../utils/message-slash-options";
import { PluginStore } from "./PluginStore";

interface PluginPackData {
  name: string;
  displayName: string;
  version: string;
  description: string;
  icon?: string;
  category?: string;
  scope?: "personal" | "organization";
  personaTemplateId?: string;
  recommendedConnectors?: string[];
  tryAsking?: string[];
  bestFitWorkflows?: ("support_ops" | "it_ops" | "sales_ops")[];
  outcomeExamples?: string[];
  skills: { id: string; name: string; description: string; icon?: string; enabled?: boolean }[];
  slashCommands: { name: string; description: string; skillId: string }[];
  agentRoles: {
    name: string;
    displayName: string;
    description?: string;
    icon: string;
    color: string;
  }[];
  state: string;
  enabled: boolean;
  policyBlocked?: boolean;
  policyRequired?: boolean;
  securityReport?: CapabilitySecurityReport;
}

type DetailTab = "commands" | "skills" | "agents";

interface CustomizePanelProps {
  onNavigateToConnectors?: () => void;
  onNavigateToSkills?: () => void;
  onCreateTask?: (title: string, prompt: string) => void;
}

export function CustomizePanel({
  onNavigateToConnectors,
  onNavigateToSkills,
  onCreateTask,
}: CustomizePanelProps) {
  const [packs, setPacks] = useState<PluginPackData[]>([]);
  const [selectedPack, setSelectedPack] = useState<string | null>(null);
  const [detailTab, setDetailTab] = useState<DetailTab>("commands");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showStore, setShowStore] = useState(false);
  const [loadKey, setLoadKey] = useState(0);
  const [searchQuery, setSearchQuery] = useState("");
  const [packUpdates, setPackUpdates] = useState<Map<string, string>>(new Map());
  const [quarantinedPacks, setQuarantinedPacks] = useState<QuarantinedImportRecord[]>([]);
  const [actioningRecordId, setActioningRecordId] = useState<string | null>(null);
  const [expandedReportId, setExpandedReportId] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function loadPacks() {
      try {
        setLoading(true);
        const data = await window.electronAPI.listPluginPacks();
        const quarantine = await window.electronAPI.listQuarantinedImports();
        if (cancelled) return;
        setPacks(data);
        setQuarantinedPacks(quarantine.filter((entry) => entry.bundleKind === "plugin-pack"));
        if (data.length > 0 && !selectedPack) {
          setSelectedPack(data[0].name);
        }
        setError(null);
      } catch (err) {
        if (cancelled) return;
        setError(err instanceof Error ? err.message : "Failed to load plugin packs");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    loadPacks();
    return () => {
      cancelled = true;
    };
  }, [loadKey]);

  // Check for pack updates in the background
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const updates = await window.electronAPI.checkPackUpdates();
        if (cancelled) return;
        const map = new Map<string, string>();
        for (const u of updates) {
          map.set(u.name, u.latestVersion);
        }
        setPackUpdates(map);
      } catch {
        // Update check failed silently
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [loadKey]);

  const activePack = packs.find((p) => p.name === selectedPack);

  // Filter packs by search query
  const query = searchQuery.toLowerCase().trim();
  const matchesPack = (p: PluginPackData) => {
    if (!query) return true;
    return (
      p.displayName.toLowerCase().includes(query) ||
      p.name.toLowerCase().includes(query) ||
      (p.description || "").toLowerCase().includes(query) ||
      (p.category || "").toLowerCase().includes(query) ||
      p.skills.some(
        (s) => s.name.toLowerCase().includes(query) || s.id.toLowerCase().includes(query),
      )
    );
  };

  const personalPacks = packs.filter((p) => p.scope === "personal" && matchesPack(p));
  const orgPacks = packs.filter((p) => p.scope === "organization" && matchesPack(p));
  const bundledPacks = packs.filter(
    (p) => (!p.scope || (p.scope !== "personal" && p.scope !== "organization")) && matchesPack(p),
  );

  const handleToggle = async (packName: string, enabled: boolean) => {
    try {
      await window.electronAPI.togglePluginPack(packName, enabled);
      setPacks((prev) =>
        prev.map((p) =>
          p.name === packName ? { ...p, enabled, state: enabled ? "registered" : "disabled" } : p,
        ),
      );
      window.dispatchEvent(new Event(MESSAGE_SHORTCUTS_UPDATED_EVENT));
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to update plugin pack");
    }
  };

  const handleSkillToggle = async (packName: string, skillId: string, enabled: boolean) => {
    try {
      await window.electronAPI.togglePluginPackSkill(packName, skillId, enabled);
      setPacks((prev) =>
        prev.map((p) =>
          p.name === packName
            ? {
                ...p,
                skills: p.skills.map((s) => (s.id === skillId ? { ...s, enabled } : s)),
              }
            : p,
        ),
      );
      window.dispatchEvent(new Event(MESSAGE_SHORTCUTS_UPDATED_EVENT));
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to update plugin skill");
    }
  };

  const handleTryAsking = (prompt: string) => {
    if (onCreateTask) {
      onCreateTask(prompt.slice(0, 60), prompt);
    }
  };

  const getSecurityBadge = (report?: CapabilitySecurityReport) => {
    if (!report || report.verdict === "clean") {
      return null;
    }
    return (
      <span className={`settings-badge ${report.verdict === "quarantined" ? "settings-badge--error" : "settings-badge--warning"}`}>
        {report.verdict === "quarantined" ? "Quarantined" : "Security Warning"}
      </span>
    );
  };

  const handleRetryQuarantined = async (recordId: string) => {
    setActioningRecordId(recordId);
    try {
      await window.electronAPI.retryQuarantinedImport(recordId);
      setLoadKey((k) => k + 1);
    } finally {
      setActioningRecordId(null);
    }
  };

  const handleRemoveQuarantined = async (recordId: string) => {
    setActioningRecordId(recordId);
    try {
      await window.electronAPI.removeQuarantinedImport(recordId);
      setLoadKey((k) => k + 1);
    } finally {
      setActioningRecordId(null);
    }
  };

  // Derive command cards from skills (each skill acts as a /command)
  const commandCards = activePack
    ? [
        ...activePack.slashCommands.map((c) => ({
          name: c.name,
          description: c.description,
        })),
        ...activePack.skills
          .filter((s) => !activePack.slashCommands.some((c) => c.skillId === s.id))
          .map((s) => ({
            name: s.id,
            description: s.description,
          })),
      ]
    : [];

  return (
    <div className="cp-container">
      {/* Sidebar */}
      <div className="cp-sidebar">
        <div className="cp-sidebar-header">
          <h3>Feature Packs</h3>
          <button
            className="cp-store-btn"
            onClick={() => setShowStore(true)}
            title="Browse plugin store"
          >
            +
          </button>
        </div>
        <p className="cp-sidebar-note">
          Enable bundled workflows like Legal, SMB, finance, and other domain packs.
        </p>

        {/* Search */}
        <div className="cp-search-wrapper">
          <input
            type="text"
            className="cp-search-input"
            placeholder="Search packs & skills..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
          {searchQuery && (
            <button className="cp-search-clear" onClick={() => setSearchQuery("")}>
              &times;
            </button>
          )}
        </div>

        {/* Top-level navigation */}
        <div className="cp-sidebar-section">
          <button className="cp-sidebar-item cp-sidebar-item--nav" onClick={onNavigateToConnectors}>
            <span className="cp-sidebar-icon">
              <Plug size={16} strokeWidth={1.5} />
            </span>
            <span>Connectors</span>
          </button>
          <button className="cp-sidebar-item cp-sidebar-item--nav" onClick={onNavigateToSkills}>
            <span className="cp-sidebar-icon">
              <Zap size={16} strokeWidth={1.5} />
            </span>
            <span>Skills</span>
          </button>
        </div>

        {/* Personal plugins */}
        {personalPacks.length > 0 && (
          <>
            <div className="cp-sidebar-group-header">
              <span>Personal plugins</span>
            </div>
            {personalPacks.map((p) => (
              <button
                key={p.name}
                className={`cp-sidebar-item ${selectedPack === p.name ? "cp-sidebar-item--active" : ""}`}
                onClick={() => {
                  setSelectedPack(p.name);
                  setDetailTab("commands");
                }}
              >
                <span className="cp-sidebar-icon">
                  {p.icon || <Package size={16} strokeWidth={1.5} />}
                </span>
                <span>{p.displayName}</span>
              </button>
            ))}
          </>
        )}

        {/* Organization plugins */}
        {orgPacks.length > 0 && (
          <>
            <div className="cp-sidebar-group-header">
              <span>Organization plugins</span>
            </div>
            {orgPacks.map((p) => (
              <button
                key={p.name}
                className={`cp-sidebar-item ${selectedPack === p.name ? "cp-sidebar-item--active" : ""}`}
                onClick={() => {
                  setSelectedPack(p.name);
                  setDetailTab("commands");
                }}
              >
                <span className="cp-sidebar-icon">
                  {p.icon || <Package size={16} strokeWidth={1.5} />}
                </span>
                <span>{p.displayName}</span>
              </button>
            ))}
          </>
        )}

        {/* Bundled packs */}
        {bundledPacks.length > 0 && (
          <>
            <div className="cp-sidebar-group-header">
              <span>Built-in packs</span>
            </div>
            {bundledPacks.map((p) => (
              <button
                key={p.name}
                className={`cp-sidebar-item ${selectedPack === p.name ? "cp-sidebar-item--active" : ""}`}
                onClick={() => {
                  setSelectedPack(p.name);
                  setDetailTab("commands");
                }}
              >
                <span className="cp-sidebar-icon">
                  {p.icon || <Package size={16} strokeWidth={1.5} />}
                </span>
                <span>{p.displayName}</span>
                <span className="cp-pack-indicators">
                  {!p.enabled && <span className="cp-disabled-dot" title="Disabled" />}
                  {packUpdates.has(p.name) && (
                    <span className="cp-update-dot" title="Update available" />
                  )}
                </span>
              </button>
            ))}
          </>
        )}

        {quarantinedPacks.length > 0 && (
          <>
            <div className="cp-sidebar-group-header">
              <span>Quarantined</span>
            </div>
            {quarantinedPacks.map((record) => (
              <button
                key={record.id}
                className="cp-sidebar-item"
                onClick={() => setExpandedReportId((current) => (current === record.id ? null : record.id))}
              >
                <span className="cp-sidebar-icon">🛡️</span>
                <span>{record.displayName || record.bundleId}</span>
              </button>
            ))}
          </>
        )}
      </div>

      {/* Detail Panel */}
      <div className="cp-detail">
        {loading && <div className="cp-empty">Loading plugin packs...</div>}
        {error && <div className="cp-empty cp-error">{error}</div>}
        {!loading && !error && !activePack && (
          <div className="cp-empty">Select a plugin pack from the sidebar</div>
        )}

        {activePack && (
          <>
            {/* Header */}
            <div className="cp-detail-header">
              <div className="cp-detail-title-row">
                <h2>{activePack.displayName}</h2>
                <div className="cp-detail-actions">
                  <label className="cp-toggle">
                    <input
                      type="checkbox"
                      checked={activePack.enabled}
                      disabled={activePack.policyBlocked || (activePack.policyRequired && activePack.enabled)}
                      onChange={(e) => handleToggle(activePack.name, e.target.checked)}
                    />
                    <span className="cp-toggle-slider" />
                  </label>
                </div>
              </div>
              <div className="cp-pack-status-row">
                <span className={`cp-pack-status ${activePack.enabled ? "enabled" : "disabled"}`}>
                  {activePack.policyBlocked
                    ? "Blocked by policy"
                    : activePack.enabled
                      ? "Enabled"
                      : "Disabled"}
                </span>
                {activePack.policyRequired && (
                  <span className="settings-badge">Required by policy</span>
                )}
              </div>
              <p className="cp-detail-description">{activePack.description}</p>
              {getSecurityBadge(activePack.securityReport)}
              {activePack.securityReport?.verdict === "warning" && (
                <div className="cp-update-badge">
                  <span>{activePack.securityReport.summary}</span>
                </div>
              )}
              {packUpdates.has(activePack.name) && (
                <div className="cp-update-badge">
                  <span>Update available: v{packUpdates.get(activePack.name)}</span>
                </div>
              )}
              {activePack.personaTemplateId && (
                <div className="cp-detail-twin-badge">
                  <span>
                    <Dna size={14} strokeWidth={1.5} />
                  </span>
                  <span>Includes Agent Persona</span>
                </div>
              )}
              {activePack.bestFitWorkflows && activePack.bestFitWorkflows.length > 0 && (
                <div className="cp-best-fit-row">
                  <span className="cp-rc-label">Best for:</span>
                  {activePack.bestFitWorkflows.map((lane) => (
                    <span key={lane} className={`cp-best-fit-badge cp-best-fit-badge--${lane}`}>
                      {lane === "support_ops" ? "Support Ops" : lane === "it_ops" ? "IT Ops" : "Sales Ops"}
                    </span>
                  ))}
                </div>
              )}
              {activePack.outcomeExamples && activePack.outcomeExamples.length > 0 && (
                <div className="cp-outcome-examples">
                  <span className="cp-rc-label">Outcome examples:</span>
                  <ul className="cp-outcome-list">
                    {activePack.outcomeExamples.map((ex, i) => (
                      <li key={i} className="cp-outcome-item">{ex}</li>
                    ))}
                  </ul>
                </div>
              )}
              {activePack.recommendedConnectors && activePack.recommendedConnectors.length > 0 && (
                <div className="cp-recommended-connectors">
                  <span className="cp-rc-label">Recommended connectors:</span>
                  {activePack.recommendedConnectors.map((c) => (
                    <button
                      key={c}
                      className="cp-rc-chip"
                      onClick={onNavigateToConnectors}
                      title={`Set up ${c}`}
                    >
                      <span>
                        <Plug size={12} strokeWidth={1.5} />
                      </span>
                      <span>{c}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Tabs */}
            <div className="cp-tabs">
              <button
                className={`cp-tab ${detailTab === "commands" ? "cp-tab--active" : ""}`}
                onClick={() => setDetailTab("commands")}
              >
                Commands
              </button>
              <button
                className={`cp-tab ${detailTab === "skills" ? "cp-tab--active" : ""}`}
                onClick={() => setDetailTab("skills")}
              >
                Skills
              </button>
              <button
                className={`cp-tab ${detailTab === "agents" ? "cp-tab--active" : ""}`}
                onClick={() => setDetailTab("agents")}
              >
                Agents
              </button>
            </div>

            {/* Tab content */}
            <div className="cp-tab-content">
              {detailTab === "commands" && (
                <>
                  <p className="cp-tab-hint">
                    Use these shortcuts to trigger a workflow by name. Search your list of commands
                    at any time by typing / in the chat window.
                  </p>
                  <div className="cp-command-grid">
                    {commandCards.map((c) => (
                      <div key={c.name} className="cp-command-card">
                        <p className="cp-command-desc">{c.description}</p>
                        <span className="cp-command-name">/{c.name}</span>
                      </div>
                    ))}
                  </div>
                  {commandCards.length === 0 && (
                    <p className="cp-tab-empty">No commands in this pack</p>
                  )}
                </>
              )}

              {detailTab === "skills" && (
                <div className="cp-skill-list">
                  {activePack.skills.map((s) => (
                    <div
                      key={s.id}
                      className={`cp-skill-row ${s.enabled === false ? "cp-skill-row--disabled" : ""}`}
                    >
                      <span className="cp-skill-icon">
                        {s.icon || <Zap size={16} strokeWidth={1.5} />}
                      </span>
                      <div className="cp-skill-info">
                        <span className="cp-skill-name">{s.name}</span>
                        <span className="cp-skill-desc">{s.description}</span>
                      </div>
                      <label className="cp-toggle cp-skill-toggle">
                        <input
                          type="checkbox"
                          checked={s.enabled !== false}
                          onChange={(e) =>
                            handleSkillToggle(activePack.name, s.id, e.target.checked)
                          }
                        />
                        <span className="cp-toggle-slider" />
                      </label>
                    </div>
                  ))}
                  {activePack.skills.length === 0 && (
                    <p className="cp-tab-empty">No skills in this pack</p>
                  )}
                </div>
              )}

              {detailTab === "agents" && (
                <div className="cp-agent-list">
                  {activePack.agentRoles.map((a) => (
                    <div key={a.name} className="cp-agent-row">
                      <span className="cp-agent-icon">
                        {a.icon ? (() => {
                          const Icon = getEmojiIcon(a.icon);
                          return <Icon size={18} strokeWidth={2} />;
                        })() : null}
                      </span>
                      <div className="cp-agent-info">
                        <span className="cp-agent-name">{a.displayName}</span>
                        <span className="cp-agent-desc">{a.description || ""}</span>
                      </div>
                    </div>
                  ))}
                  {activePack.personaTemplateId && (
                    <div className="cp-agent-twin">
                      <span className="cp-agent-icon">
                        <Dna size={18} strokeWidth={1.5} />
                      </span>
                      <div className="cp-agent-info">
                        <span className="cp-agent-name">Agent Persona Available</span>
                        <span className="cp-agent-desc">
                          This pack includes an optional digital twin persona. Activate it from
                          Agent Personas as a preset; core automation is configured separately.
                        </span>
                      </div>
                    </div>
                  )}
                  {activePack.agentRoles.length === 0 && !activePack.personaTemplateId && (
                    <p className="cp-tab-empty">No agents in this pack</p>
                  )}
                </div>
              )}
            </div>

            {/* Try asking section */}
            {activePack.tryAsking && activePack.tryAsking.length > 0 && (
              <div className="cp-try-asking">
                <h4>Try asking ..</h4>
                <div className="cp-try-list">
                  {activePack.tryAsking.map((prompt, i) => (
                    <button key={i} className="cp-try-item" onClick={() => handleTryAsking(prompt)}>
                      <span>{prompt}</span>
                      <span className="cp-try-arrow">&rarr;</span>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {quarantinedPacks.length > 0 && (
              <div className="cp-try-asking">
                <h4>Quarantined Imports</h4>
                <div className="cp-try-list">
                  {quarantinedPacks.map((record) => (
                    <div key={record.id} className="cp-try-item" style={{ display: "block", cursor: "default" }}>
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
                        <div>
                          <strong>{record.displayName || record.bundleId}</strong>
                          <div>{record.summary}</div>
                        </div>
                        <div style={{ display: "flex", gap: 8 }}>
                          <button
                            className="button-secondary button-small"
                            onClick={() =>
                              setExpandedReportId((current) => (current === record.id ? null : record.id))
                            }
                          >
                            {expandedReportId === record.id ? "Hide Report" : "View Report"}
                          </button>
                          <button
                            className="button-secondary button-small"
                            onClick={() => handleRetryQuarantined(record.id)}
                            disabled={actioningRecordId === record.id}
                          >
                            {actioningRecordId === record.id ? "Scanning..." : "Retry Scan"}
                          </button>
                          <button
                            className="button-danger button-small"
                            onClick={() => handleRemoveQuarantined(record.id)}
                            disabled={actioningRecordId === record.id}
                          >
                            Remove
                          </button>
                        </div>
                      </div>
                      {expandedReportId === record.id && (
                        <div style={{ marginTop: 8 }}>
                          {record.report.findings.map((finding, index) => (
                            <div key={`${record.id}-${index}`}>
                              <strong>{finding.severity}</strong>: {finding.message}
                              {finding.path ? ` (${finding.path})` : ""}
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {/* Plugin Store Modal */}
      {showStore && (
        <PluginStore
          onClose={() => setShowStore(false)}
          onInstalled={() => setLoadKey((k) => k + 1)}
        />
      )}

      <style>{`
        .cp-container {
          display: flex;
          height: 100%;
          min-height: 0;
          gap: 24px;
          padding: 32px 40px;
          background: transparent;
          color: var(--color-text-primary);
        }

        /* Search */
        .cp-search-wrapper {
          position: relative;
          padding: 0 14px 10px;
        }

        .cp-search-input {
          width: 100%;
          padding: 9px 30px 9px 12px;
          border: 1px solid var(--color-border);
          border-radius: var(--radius-md);
          background: var(--color-bg-glass);
          color: var(--color-text-primary);
          font-size: 13px;
          outline: none;
          box-sizing: border-box;
          transition: border-color 0.18s ease, box-shadow 0.18s ease, background 0.18s ease;
        }

        .cp-search-input:focus {
          border-color: var(--color-accent);
          box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-accent) 14%, transparent);
          background: var(--color-bg-elevated);
        }

        .cp-search-input::placeholder {
          color: var(--color-text-muted);
        }

        .cp-search-clear {
          position: absolute;
          right: 16px;
          top: 50%;
          transform: translateY(calc(-50% - 4px));
          background: none;
          border: none;
          color: var(--color-text-muted);
          font-size: 14px;
          cursor: pointer;
          padding: 0 2px;
          line-height: 1;
        }

        .cp-search-clear:hover {
          color: var(--color-text-primary);
        }

        /* Sidebar */
        .cp-sidebar {
          width: 280px;
          min-width: 280px;
          border: 1px solid var(--color-border-subtle);
          border-radius: var(--radius-xl);
          background: linear-gradient(135deg, var(--color-bg-elevated) 0%, var(--color-bg-glass) 100%);
          box-shadow: var(--shadow-md);
          display: flex;
          flex-direction: column;
          overflow-y: auto;
          padding: 18px 0;
          scrollbar-width: none;
        }

        .cp-sidebar::-webkit-scrollbar {
          width: 0;
          height: 0;
          display: none;
        }

        .cp-sidebar-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 2px 18px 12px;
        }

        .cp-store-btn {
          width: 32px;
          height: 32px;
          border: 1px solid var(--color-border);
          border-radius: 12px;
          background: var(--color-bg-glass);
          color: var(--color-text-secondary);
          font-size: 16px;
          line-height: 1;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.15s;
        }

        .cp-store-btn:hover {
          color: var(--color-accent);
          border-color: var(--color-accent-subtle);
          background: var(--color-accent-subtle);
          transform: translateY(-1px);
        }

        .cp-sidebar-header h3 {
          font-size: 17px;
          font-weight: 600;
          margin: 0;
          color: var(--color-text-primary);
        }

        .cp-sidebar-note {
          margin: -4px 18px 14px;
          color: var(--color-text-muted);
          font-size: 13px;
          line-height: 1.45;
        }

        .cp-sidebar-section {
          padding: 0;
          margin-bottom: 8px;
        }

        .cp-sidebar-group-header {
          padding: 16px 18px 8px;
          font-size: 11px;
          font-weight: 600;
          color: var(--color-text-muted);
          text-transform: uppercase;
          letter-spacing: 0.5px;
        }

        .cp-sidebar-item {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          gap: 10px;
          padding: 10px 12px;
          background: transparent;
          border: 1px solid transparent;
          border-radius: 14px;
          color: var(--color-text-secondary);
          font-size: 13px;
          line-height: 20px;
          cursor: pointer;
          text-align: left;
          margin: 2px 12px;
          width: calc(100% - 24px);
          transition: background 0.18s ease, border-color 0.18s ease, transform 0.18s ease, color 0.18s ease;
        }

        .cp-sidebar-item > span:nth-child(2) {
          flex: 1;
          min-width: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          line-height: 20px;
        }

        .cp-pack-indicators {
          display: inline-flex;
          align-items: center;
          justify-content: flex-end;
          gap: 6px;
          flex: 0 0 auto;
          margin-left: auto;
        }

        .cp-sidebar-item:hover {
          border-color: var(--color-border-light);
          background: var(--color-bg-glass-hover);
          color: var(--color-text-primary);
          transform: translateX(2px);
        }

        .cp-sidebar-item--active {
          border-color: color-mix(in srgb, var(--color-accent) 42%, transparent);
          background: linear-gradient(135deg, color-mix(in srgb, var(--color-accent-subtle) 72%, transparent), var(--color-bg-glass));
          color: var(--color-text-primary);
          font-weight: 600;
        }

        .cp-sidebar-item--nav {
          color: var(--color-text-primary);
        }

        .cp-sidebar-icon {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          line-height: 1;
          width: 26px;
          min-width: 26px;
          height: 26px;
          border-radius: 999px;
          background: color-mix(in srgb, var(--color-accent-subtle) 62%, transparent);
          color: var(--color-accent);
          flex-shrink: 0;
        }

        /* Detail panel */
        .cp-detail {
          flex: 1;
          overflow-y: auto;
          padding: 8px 8px 24px;
          min-width: 0;
          max-width: 1100px;
          scrollbar-width: none;
          animation: dp-fade-in 0.6s ease-out;
        }

        .cp-detail::-webkit-scrollbar {
          width: 0;
          height: 0;
          display: none;
        }

        .cp-empty {
          color: var(--color-text-muted);
          font-size: 14px;
          padding: 40px 0;
          text-align: center;
        }

        .cp-error {
          color: var(--color-text-danger, #ef4444);
        }

        .cp-detail-header {
          margin-bottom: 28px;
          padding: 24px 28px 22px;
          border: 1px solid var(--color-border-light);
          border-radius: var(--radius-xl);
          background: linear-gradient(135deg, var(--color-bg-elevated) 0%, color-mix(in srgb, var(--color-bg-elevated) 80%, var(--color-accent-subtle)) 100%);
          box-shadow: var(--shadow-lg), var(--shadow-glow);
          backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturate));
          -webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturate));
        }

        .cp-detail-title-row {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 8px;
        }

        .cp-detail-title-row h2 {
          font-family: var(--font-ui);
          font-size: 22px;
          font-weight: 600;
          margin: 0;
          color: var(--color-text);
        }

        .cp-detail-description {
          font-size: 15px;
          color: var(--color-text-secondary);
          margin: 0 0 16px;
          line-height: 1.6;
          max-width: 940px;
        }

        .cp-pack-status-row {
          display: flex;
          align-items: center;
          gap: 8px;
          margin: -2px 0 10px;
        }

        .cp-pack-status {
          display: inline-flex;
          align-items: center;
          border-radius: 999px;
          padding: 3px 9px;
          font-size: 11px;
          font-weight: 650;
          border: 1px solid transparent;
        }

        .cp-pack-status.enabled {
          color: var(--color-accent);
          background: var(--color-accent-subtle);
          border-color: color-mix(in srgb, var(--color-accent) 30%, transparent);
        }

        .cp-pack-status.disabled {
          color: var(--color-text-muted);
          background: var(--color-bg-secondary);
          border: 1px solid var(--color-border-subtle);
        }

        .cp-detail-twin-badge {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 4px 10px;
          background: var(--color-accent-subtle, rgba(34, 211, 238, 0.1));
          color: var(--color-accent);
          border-radius: 12px;
          font-size: 12px;
          font-weight: 600;
          border: 1px solid color-mix(in srgb, var(--color-accent) 30%, transparent);
        }

        .cp-detail-actions {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        /* Best-fit workflow badges */
        .cp-best-fit-row {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 6px;
          margin-top: 8px;
        }

        .cp-best-fit-badge {
          display: inline-flex;
          align-items: center;
          padding: 4px 10px;
          border-radius: 12px;
          font-size: 11px;
          font-weight: 600;
          letter-spacing: 0.02em;
          text-transform: uppercase;
        }

        .cp-best-fit-badge--support_ops {
          background: rgba(99, 102, 241, 0.15);
          color: #818cf8;
          border: 1px solid rgba(99, 102, 241, 0.3);
        }

        .cp-best-fit-badge--it_ops {
          background: rgba(239, 68, 68, 0.15);
          color: #f87171;
          border: 1px solid rgba(239, 68, 68, 0.3);
        }

        .cp-best-fit-badge--sales_ops {
          background: rgba(16, 185, 129, 0.15);
          color: #34d399;
          border: 1px solid rgba(16, 185, 129, 0.3);
        }

        /* Outcome examples */
        .cp-outcome-examples {
          margin-top: 14px;
        }

        .cp-outcome-list {
          margin: 6px 0 0 0;
          padding-left: 18px;
          list-style: disc;
        }

        .cp-outcome-item {
          font-size: 13px;
          color: var(--color-text-secondary);
          line-height: 1.6;
          margin-bottom: 2px;
        }

        /* Recommended connectors */
        .cp-recommended-connectors {
          display: flex;
          align-items: center;
          gap: 6px;
          flex-wrap: wrap;
          margin-top: 14px;
        }

        .cp-rc-label {
          font-size: 13px;
          color: var(--color-text-muted);
          margin-right: 2px;
        }

        .cp-rc-chip {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          padding: 6px 10px;
          border: 1px solid var(--color-border-subtle);
          border-radius: 999px;
          background: var(--color-bg-glass);
          color: var(--color-text-secondary);
          font-size: 12px;
          cursor: pointer;
          transition: all 0.15s;
        }

        .cp-rc-chip:hover {
          border-color: var(--color-accent, #22d3ee);
          color: var(--color-accent, #22d3ee);
          background: var(--color-accent-subtle, rgba(34, 211, 238, 0.1));
        }

        /* Update indicators */
        .cp-update-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: var(--color-warning, #f59e0b);
          flex: 0 0 8px;
          min-width: 8px;
          flex-shrink: 0;
        }

        .cp-disabled-dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: var(--color-text-muted);
          flex: 0 0 8px;
          min-width: 8px;
          opacity: 0.7;
        }

        .cp-update-badge {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          padding: 3px 10px;
          background: rgba(245, 158, 11, 0.12);
          color: var(--color-warning, #f59e0b);
          border-radius: 12px;
          font-size: 12px;
          font-weight: 500;
          margin-top: 6px;
        }

        /* Toggle switch */
        .cp-toggle {
          position: relative;
          display: inline-block;
          width: 44px;
          height: 24px;
          cursor: pointer;
        }

        .cp-toggle input {
          opacity: 0;
          width: 0;
          height: 0;
        }

        .cp-toggle-slider {
          position: absolute;
          inset: 0;
          background: var(--color-bg-tertiary);
          border-radius: 999px;
          transition: background 0.2s;
        }

        .cp-toggle-slider::before {
          content: "";
          position: absolute;
          width: 20px;
          height: 20px;
          left: 2px;
          top: 2px;
          background: white;
          border-radius: 50%;
          transition: transform 0.2s;
        }

        .cp-toggle input:checked + .cp-toggle-slider {
          background: var(--color-accent, #22d3ee);
        }

        .cp-toggle input:checked + .cp-toggle-slider::before {
          transform: translateX(20px);
        }

        .cp-toggle input:disabled + .cp-toggle-slider {
          opacity: 0.55;
          cursor: not-allowed;
        }

        /* Tabs */
        .cp-tabs {
          display: flex;
          align-items: center;
          gap: 8px;
          border-bottom: none;
          margin: 0 0 18px;
        }

        .cp-tab {
          padding: 8px 14px;
          background: var(--color-bg-glass);
          border: 1px solid var(--color-border-subtle);
          border-radius: 999px;
          color: var(--color-text-muted);
          font-size: 13px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.15s;
        }

        .cp-tab:hover {
          color: var(--color-text-primary);
          border-color: var(--color-border-light);
          background: var(--color-bg-glass-hover);
        }

        .cp-tab--active {
          color: var(--color-accent);
          border-color: color-mix(in srgb, var(--color-accent) 40%, transparent);
          background: var(--color-accent-subtle);
        }

        .cp-tab-content {
          min-height: 100px;
        }

        .cp-tab-hint {
          font-size: 13px;
          color: var(--color-text-muted);
          margin: 0 0 18px;
          line-height: 1.4;
        }

        .cp-tab-empty {
          color: var(--color-text-muted);
          font-size: 13px;
          font-style: italic;
        }

        /* Command cards */
        .cp-command-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
          gap: 14px;
        }

        .cp-command-card {
          min-height: 156px;
          padding: 22px 24px;
          border: 1px solid var(--color-border-subtle);
          border-radius: var(--radius-lg);
          background: linear-gradient(135deg, var(--color-bg-glass) 0%, var(--color-accent-subtle) 100%);
          cursor: default;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          gap: 18px;
          position: relative;
          overflow: hidden;
          transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
        }

        .cp-command-card::before {
          content: "";
          position: absolute;
          inset: 0;
          background: linear-gradient(135deg, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
          pointer-events: none;
        }

        .cp-command-card:hover {
          border-color: var(--color-accent-subtle);
          background: linear-gradient(135deg, var(--color-bg-glass-hover) 0%, color-mix(in srgb, var(--color-accent-subtle) 80%, white 20%) 100%);
          box-shadow: var(--shadow-lg), 0 10px 20px -10px color-mix(in srgb, var(--color-accent) 20%, transparent);
          transform: translateY(-3px);
        }

        .cp-command-desc {
          font-size: 14px;
          color: var(--color-text-primary);
          margin: 0;
          line-height: 1.5;
        }

        .cp-command-name {
          font-size: 12px;
          color: var(--color-text-muted);
          font-family: var(--font-mono);
          overflow-wrap: anywhere;
        }

        /* Skill list */
        .cp-skill-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .cp-skill-row {
          display: grid;
          grid-template-columns: 44px minmax(0, 1fr) auto;
          align-items: center;
          gap: 16px;
          padding: 18px 20px;
          border: 1px solid var(--color-border-subtle);
          border-radius: var(--radius-lg);
          background: linear-gradient(135deg, var(--color-bg-elevated) 0%, var(--color-bg-glass) 100%);
          transition: all 0.25s ease;
        }

        .cp-skill-row:hover {
          border-color: var(--color-accent-subtle);
          background: linear-gradient(135deg, var(--color-bg-elevated) 0%, var(--color-bg-hover) 100%);
          transform: translateX(4px);
          box-shadow: var(--shadow-md);
        }

        .cp-skill-row--disabled {
          opacity: 0.5;
        }

        .cp-skill-toggle {
          margin-left: auto;
          flex-shrink: 0;
        }

        .cp-skill-icon {
          font-size: 16px;
          width: 44px;
          height: 44px;
          border-radius: var(--radius-lg);
          display: inline-flex;
          align-items: center;
          justify-content: center;
          background: var(--color-bg-glass);
          border: 1px solid var(--color-border-subtle);
          color: var(--color-accent);
          box-shadow: var(--shadow-sm);
          flex-shrink: 0;
        }

        .cp-skill-info {
          display: flex;
          flex-direction: column;
          gap: 2px;
          min-width: 0;
        }

        .cp-skill-name {
          font-size: 15px;
          font-weight: 600;
          color: var(--color-text-primary);
        }

        .cp-skill-desc {
          font-size: 13px;
          color: var(--color-text-muted);
          line-height: 1.45;
        }

        /* Agent list */
        .cp-agent-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .cp-agent-row,
        .cp-agent-twin {
          display: grid;
          grid-template-columns: 44px minmax(0, 1fr);
          align-items: flex-start;
          gap: 16px;
          padding: 18px 20px;
          border: 1px solid var(--color-border-subtle);
          border-radius: var(--radius-lg);
          background: linear-gradient(135deg, var(--color-bg-elevated) 0%, var(--color-bg-glass) 100%);
          transition: all 0.25s ease;
        }

        .cp-agent-row:hover,
        .cp-agent-twin:hover {
          border-color: var(--color-accent-subtle);
          background: linear-gradient(135deg, var(--color-bg-elevated) 0%, var(--color-bg-hover) 100%);
          transform: translateX(4px);
          box-shadow: var(--shadow-md);
        }

        .cp-agent-twin {
          border-style: dashed;
          background: linear-gradient(135deg, var(--color-accent-subtle), var(--color-bg-glass));
        }

        .cp-agent-icon {
          font-size: 18px;
          width: 44px;
          height: 44px;
          border-radius: var(--radius-lg);
          display: inline-flex;
          align-items: center;
          justify-content: center;
          background: var(--color-bg-glass);
          border: 1px solid var(--color-border-subtle);
          color: var(--color-accent);
          box-shadow: var(--shadow-sm);
          flex-shrink: 0;
        }

        .cp-agent-info {
          display: flex;
          flex-direction: column;
          gap: 2px;
          min-width: 0;
        }

        .cp-agent-name {
          font-size: 15px;
          font-weight: 600;
          color: var(--color-text-primary);
        }

        .cp-agent-desc {
          font-size: 13px;
          color: var(--color-text-muted);
          line-height: 1.45;
        }

        /* Try asking section */
        .cp-try-asking {
          margin-top: 24px;
          padding-top: 20px;
          border-top: 1px solid var(--color-border-subtle);
        }

        .cp-try-asking h4 {
          font-size: 14px;
          font-weight: 600;
          margin: 0 0 12px;
          color: var(--color-text-primary);
        }

        .cp-try-list {
          display: flex;
          flex-direction: column;
          gap: 0;
        }

        .cp-try-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 0;
          background: none;
          border: none;
          border-bottom: 1px solid var(--color-border-subtle);
          color: var(--color-text-primary);
          font-size: 14px;
          cursor: pointer;
          text-align: left;
          width: 100%;
          transition: color 0.15s;
        }

        .cp-try-item:last-child {
          border-bottom: none;
        }

        .cp-try-item:hover {
          color: var(--color-accent);
        }

        .cp-try-arrow {
          color: var(--color-text-muted);
          font-size: 16px;
          flex-shrink: 0;
          margin-left: 12px;
          transition: color 0.15s;
        }

        .cp-try-item:hover .cp-try-arrow {
          color: var(--color-accent);
        }

        @media (max-width: 980px) {
          .cp-container {
            flex-direction: column;
            padding: 20px;
            gap: 16px;
          }

          .cp-sidebar {
            width: 100%;
            min-width: 0;
            max-height: 300px;
          }

          .cp-detail {
            max-width: none;
            padding: 0 0 20px;
          }

          .cp-command-grid {
            grid-template-columns: 1fr;
          }
        }

        @media (max-width: 640px) {
          .cp-container {
            padding: 12px;
          }

          .cp-detail-header {
            padding: 20px;
          }

          .cp-detail-title-row,
          .cp-pack-status-row,
          .cp-recommended-connectors {
            align-items: flex-start;
          }

          .cp-detail-title-row {
            gap: 12px;
          }

          .cp-tabs {
            overflow-x: auto;
            padding-bottom: 2px;
          }

          .cp-skill-row {
            grid-template-columns: 38px minmax(0, 1fr);
          }

          .cp-skill-toggle {
            grid-column: 2;
            justify-self: start;
            margin-left: 0;
          }

          .cp-agent-row,
          .cp-agent-twin {
            grid-template-columns: 38px minmax(0, 1fr);
          }

          .cp-skill-icon,
          .cp-agent-icon {
            width: 38px;
            height: 38px;
          }
        }
      `}</style>
    </div>
  );
}
