// CRM Integrations — shared state, catalog, logo marks, connect modal.
// Stored in localStorage so state survives reload. All systems equal-weight.

const CRM_CATALOG = [
  {
    id: 'hubspot',
    name: 'HubSpot',
    domain: 'hubspot.com',
    color: '#FF7A59',
    tagline: 'Marketing, Sales & Service Hub',
    objects: ['Contact', 'Company', 'Deal'],
    defaultObject: 'Deal',
    pipelines: ['Sales Pipeline', 'Partner Pipeline'],
    stages: ['Appointment scheduled', 'Qualified to buy', 'Presentation scheduled', 'Decision maker bought-in'],
  },
  {
    id: 'pipedrive',
    name: 'Pipedrive',
    domain: 'pipedrive.com',
    color: '#1A1A1A',
    tagline: 'Sales CRM',
    objects: ['Lead', 'Deal', 'Person', 'Organization'],
    defaultObject: 'Deal',
    pipelines: ['New Business', 'Upsell'],
    stages: ['Lead In', 'Contact Made', 'Demo Scheduled', 'Proposal Made'],
  },
  {
    id: 'salesforce',
    name: 'Salesforce',
    domain: 'salesforce.com',
    color: '#00A1E0',
    tagline: 'Sales Cloud',
    objects: ['Lead', 'Account', 'Opportunity'],
    defaultObject: 'Lead',
    pipelines: ['Standard Sales Process', 'Enterprise'],
    stages: ['New', 'Working', 'Nurturing', 'Qualified'],
  },
  {
    id: 'close',
    name: 'Close',
    domain: 'close.com',
    color: '#02BE88',
    tagline: 'Inside Sales CRM',
    objects: ['Lead', 'Contact', 'Opportunity'],
    defaultObject: 'Lead',
    pipelines: ['Primary'],
    stages: ['Qualification', 'Demo', 'Negotiation'],
  },
  {
    id: 'zoho',
    name: 'Zoho CRM',
    domain: 'zoho.com',
    color: '#D94444',
    tagline: 'Customer relationship suite',
    objects: ['Lead', 'Contact', 'Account', 'Deal'],
    defaultObject: 'Lead',
    pipelines: ['Standard'],
    stages: ['Qualification', 'Needs Analysis', 'Value Proposition'],
  },
  {
    id: 'attio',
    name: 'Attio',
    domain: 'attio.com',
    color: '#1F1F1F',
    tagline: 'Modern relationship CRM',
    objects: ['Person', 'Company', 'Deal'],
    defaultObject: 'Deal',
    pipelines: ['Sales'],
    stages: ['Lead', 'Contacted', 'Demo', 'Won'],
  },
  {
    id: 'webhook',
    name: 'Webhook / Zapier',
    domain: 'zapier.com',
    color: '#FF4A00',
    tagline: 'Custom endpoint for anything else',
    objects: ['POST'],
    defaultObject: 'POST',
    pipelines: [],
    stages: [],
    isWebhook: true,
  },
];

// Brand logo marks — clean SVG per CRM, rendered on neutral surface
function CRMLogo({ crm, size = 32 }) {
  const s = size;
  const common = { width: s, height: s, viewBox: '0 0 40 40', xmlns: 'http://www.w3.org/2000/svg' };
  switch (crm.id) {
    case 'hubspot':
      return (
        <svg {...common}>
          <path d="M28.5 17.2V12.4a2.6 2.6 0 1 0-1.6 0v4.8a7.3 7.3 0 0 0-3.5 1.4l-9.5-7.4a2.9 2.9 0 1 0-1 1.3l9.4 7.3a7.3 7.3 0 0 0 .1 8.3l-2.9 2.9a2.4 2.4 0 1 0 1.2 1.2l2.9-2.9a7.3 7.3 0 1 0 4.9-12.1zm-1 11a3.8 3.8 0 1 1 3.8-3.8 3.8 3.8 0 0 1-3.8 3.8z"
                fill="#FF7A59"/>
        </svg>
      );
    case 'pipedrive':
      return (
        <svg {...common}>
          <path d="M21.5 9.5c-3.3 0-5.6 1.7-5.6 1.7-.1-.8-.6-1.3-1.6-1.3h-3.9v3.5h1.6c.3 0 .4.2.4.4v17.2h4.1v-7a6.8 6.8 0 0 0 4.9 1.8c4.5 0 7.9-3.5 7.9-8.2 0-4.8-3.2-8.1-7.8-8.1zm-.9 12.6a4 4 0 0 1-4.2-4.4c0-3.1 2-4.5 4.1-4.5 2.5 0 4.1 2 4.1 4.5 0 3-2 4.4-4 4.4z"
                fill="#1A1A1A"/>
        </svg>
      );
    case 'salesforce':
      return (
        <svg {...common}>
          <path d="M17 13.5a5.8 5.8 0 0 1 4.2-1.8 5.9 5.9 0 0 1 5.1 3 7.1 7.1 0 0 1 2.9-.6 7.2 7.2 0 0 1 3.1 13.7 5.3 5.3 0 0 1-5.2 6.1 5.2 5.2 0 0 1-3-1 6 6 0 0 1-11-.6 4.6 4.6 0 0 1-1 .1 4.7 4.7 0 0 1-2.3-8.7 5.3 5.3 0 0 1 7.2-6.9z"
                fill="#00A1E0"/>
        </svg>
      );
    case 'close':
      return (
        <svg {...common}>
          <rect x="6" y="6" width="28" height="28" rx="7" fill="#02BE88"/>
          <path d="M24.4 16.3a5.8 5.8 0 1 0 0 7.4l-2-1.5a3.3 3.3 0 1 1 0-4.4z" fill="#fff"/>
        </svg>
      );
    case 'zoho':
      return (
        <svg {...common}>
          <rect x="6" y="6" width="28" height="28" rx="5" fill="#fff" stroke="#E8EAF0"/>
          <path d="M12 14h11l-8 10h8v3H11l8-10h-7z" fill="#D94444"/>
          <circle cx="27" cy="27" r="3" fill="#F9B61C"/>
        </svg>
      );
    case 'attio':
      return (
        <svg {...common}>
          <rect x="6" y="6" width="28" height="28" rx="7" fill="#1F1F1F"/>
          <path d="M20 12l7 16h-3.2l-1.3-3.2h-5l-1.3 3.2H13zm0 5.6l-1.7 4.2h3.4z" fill="#fff"/>
        </svg>
      );
    case 'webhook':
      return (
        <svg {...common}>
          <rect x="6" y="6" width="28" height="28" rx="7" fill="#FF4A00"/>
          <path d="M15 17l-3 5 3 5M25 17l3 5-3 5M22 14l-4 12" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
        </svg>
      );
    default:
      return (
        <div className="rounded-lg flex items-center justify-center bg-[#F4F7FD]"
             style={{ width: s, height: s }}>
          <span className="text-ink-soft font-semibold" style={{ fontSize: s * 0.42 }}>
            {crm.name.slice(0, 2).toUpperCase()}
          </span>
        </div>
      );
  }
}

// Legacy wrapper — keeps API for other callers (shows logo on neutral bg tile)
function CRMMark({ crm, size = 32, className = '' }) {
  return (
    <div className={`rounded-lg flex items-center justify-center flex-shrink-0 bg-[#F7F9FC] border border-[#EEF1F6] ${className}`}
         style={{ width: size, height: size }}>
      <CRMLogo crm={crm} size={Math.round(size * 0.72)}/>
    </div>
  );
}

// --- Connections store (localStorage-backed) ----------------------------
const CRM_STORE_KEY = 'ls.crmConnections.v1';
const CRM_PUSHES_KEY = 'ls.crmPushes.v1';

function loadConnections() {
  try {
    const raw = localStorage.getItem(CRM_STORE_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return {}; // { [crmId]: { connectedAt, apiKeyMasked, pipeline, stage, object, autoPush, account } }
}
function saveConnections(c) {
  try { localStorage.setItem(CRM_STORE_KEY, JSON.stringify(c)); } catch (e) {}
}
function loadPushes() {
  try {
    const raw = localStorage.getItem(CRM_PUSHES_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  return {}; // { [leadId]: { crmId, at, url } }
}
function savePushes(p) {
  try { localStorage.setItem(CRM_PUSHES_KEY, JSON.stringify(p)); } catch (e) {}
}

// React hook — returns [conns, setConns, pushes, recordPush]
function useCRM() {
  const [conns, _setConns] = useState(loadConnections);
  const [pushes, _setPushes] = useState(loadPushes);
  const setConns = (next) => { _setConns(next); saveConnections(next); };
  const setPushes = (next) => { _setPushes(next); savePushes(next); };

  const recordPush = (leadId, crmId) => {
    const url = `https://app.${CRM_CATALOG.find(c => c.id === crmId)?.domain || 'example.com'}/leads/${leadId}`;
    const next = { ...pushes, [leadId]: { crmId, at: Date.now(), url } };
    setPushes(next);
    return next[leadId];
  };

  const firstConnectedId = Object.keys(conns)[0] || null;
  const primaryCRM = firstConnectedId ? CRM_CATALOG.find(c => c.id === firstConnectedId) : null;
  const hasAutoPush = firstConnectedId && conns[firstConnectedId]?.autoPush;

  return { conns, setConns, pushes, recordPush, primaryCRM, hasAutoPush };
}

// --- Connect Modal ------------------------------------------------------
function CRMConnectModal({ crm, existing, onClose, onSave, onDisconnect }) {
  useLang();
  const [apiKey, setApiKey] = useState(existing ? '••••••••••••' + (existing.apiKeyMasked || 'ab12') : '');
  const [pipeline, setPipeline] = useState(existing?.pipeline || crm.pipelines[0] || '');
  const [stage, setStage] = useState(existing?.stage || crm.stages[0] || '');
  const [object, setObject] = useState(existing?.object || crm.defaultObject);
  const [autoPush, setAutoPush] = useState(existing?.autoPush || false);
  const [testing, setTesting] = useState(false);

  const handleSave = () => {
    setTesting(true);
    setTimeout(() => {
      const last4 = apiKey.slice(-4);
      onSave({
        connectedAt: existing?.connectedAt || Date.now(),
        apiKeyMasked: last4,
        pipeline, stage, object, autoPush,
        account: existing?.account || 'janik@deimann.com',
      });
      setTesting(false);
    }, 700);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-6 fade-in"
         style={{ background: 'rgba(11,15,25,0.45)' }}
         onClick={onClose}>
      <div onClick={e => e.stopPropagation()}
           className="bg-white rounded-xl shadow-2xl w-full max-w-[560px] max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="px-6 py-5 border-b border-line flex items-center gap-3">
          <CRMMark crm={crm} size={40}/>
          <div className="flex-1">
            <div className="text-[16px] font-semibold text-ink leading-tight">{crm.name}</div>
            <div className="text-[12.5px] text-ink-muted mt-0.5">{crm.tagline}</div>
          </div>
          <button onClick={onClose}
                  className="w-8 h-8 rounded-md text-ink-soft hover:bg-gray-100 hover:text-ink inline-flex items-center justify-center transition-colors">
            <Icon.X size={16}/>
          </button>
        </div>

        {/* Body */}
        <div className="px-6 py-5 space-y-5 overflow-y-auto">
          <div>
            <label className="block text-[11.5px] text-ink-muted mb-1.5">{t('acct.int.apiKey')}</label>
            <input type="text" value={apiKey} onChange={e => setApiKey(e.target.value)}
                   placeholder={t('acct.int.apiKeyP')}
                   className="w-full h-[38px] px-3 rounded-md border border-line bg-white text-[13px] text-ink font-mono focus:outline-none focus:border-[#3465E3] focus:ring-2 focus:ring-[#3465E3]/15 transition-all"/>
          </div>

          {!crm.isWebhook && (
            <>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-[11.5px] text-ink-muted mb-1.5">{t('acct.int.object')}</label>
                  <Select value={object} onChange={setObject} options={crm.objects}/>
                </div>
                <div>
                  <label className="block text-[11.5px] text-ink-muted mb-1.5">{t('acct.int.pipeline')}</label>
                  <Select value={pipeline} onChange={setPipeline} options={crm.pipelines}/>
                </div>
              </div>
              <div>
                <label className="block text-[11.5px] text-ink-muted mb-1.5">{t('acct.int.stage')}</label>
                <Select value={stage} onChange={setStage} options={crm.stages}/>
              </div>

              {/* Field mapping preview */}
              <div>
                <div className="text-[11.5px] text-ink-muted mb-2">{t('acct.int.mapping')}</div>
                <div className="border border-line rounded-md divide-y divide-[#F0F4FA] overflow-hidden">
                  {[
                    ['Firma', 'Company Name'],
                    ['Website', 'Domain'],
                    ['Branche', 'Industry'],
                    ['Standort', 'City / Region'],
                    ['Entscheider', 'Primary Contact'],
                    ['Match-Score', 'Custom: leadscraper_score'],
                  ].map(([src, dst]) => (
                    <div key={src} className="flex items-center px-3 py-2 text-[12.5px]">
                      <span className="text-ink-muted w-[110px]">{src}</span>
                      <span className="text-ink-soft mx-2">→</span>
                      <span className="text-ink">{dst}</span>
                    </div>
                  ))}
                </div>
                <div className="text-[11px] text-ink-soft mt-1.5">{t('acct.int.mappingSub')}</div>
              </div>
            </>
          )}

          {/* Auto-push toggle */}
          <div className="flex items-start gap-3 p-3.5 rounded-md bg-[#FAFBFD] border border-line">
            <button onClick={() => setAutoPush(v => !v)}
                    className="mt-0.5 w-9 h-[22px] rounded-full relative transition-colors flex-shrink-0"
                    style={{ background: autoPush ? '#0B0F19' : '#D1D5DB' }}>
              <span className="absolute top-0.5 w-[18px] h-[18px] rounded-full bg-white shadow transition-transform"
                    style={{ transform: autoPush ? 'translateX(18px)' : 'translateX(2px)' }}/>
            </button>
            <div className="flex-1">
              <div className="text-[13px] font-medium text-ink">{t('acct.int.autoPush')}</div>
              <div className="text-[12px] text-ink-muted mt-0.5 leading-snug">{t('acct.int.autoPushSub')}</div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="px-6 py-4 border-t border-line flex items-center justify-between bg-[#FAFBFD]">
          {existing ? (
            <button onClick={onDisconnect}
                    className="text-[12.5px] text-[#D03B3B] font-medium hover:underline">
              {t('acct.int.disconnect')}
            </button>
          ) : <span/>}
          <div className="flex items-center gap-2">
            <button onClick={onClose}
                    className="px-4 h-[34px] rounded-md border border-line text-[12.5px] font-medium text-ink-muted hover:bg-gray-50 transition-colors">
              {t('acct.int.cancel')}
            </button>
            <button onClick={handleSave} disabled={!apiKey || testing}
                    className="px-4 h-[34px] rounded-md text-[12.5px] font-medium text-white transition-all disabled:opacity-50"
                    style={{ background: apiKey && !testing ? '#0B0F19' : '#9CA3AF' }}>
              {testing ? t('acct.int.testing') : t('acct.int.save')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function Select({ value, onChange, options }) {
  return (
    <select value={value} onChange={e => onChange(e.target.value)}
            className="w-full h-[38px] px-3 pr-8 rounded-md border border-line bg-white text-[13px] text-ink hover:border-[#C5D2EC] focus:outline-none focus:border-[#3465E3] focus:ring-2 focus:ring-[#3465E3]/15 transition-all cursor-pointer"
            style={{ backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6' fill='none'><path d='M1 1L5 5L9 1' stroke='%236B7280' stroke-width='1.5' stroke-linecap='round'/></svg>\")",
                     backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center',
                     appearance: 'none', WebkitAppearance: 'none' }}>
      {(options || []).map(o => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

// --- Integrations Panel (inside Account screen) ------------------------
function IntegrationsPanel({ toast }) {
  useLang();
  const [conns, setConns] = useState(loadConnections);
  const [activeCRM, setActiveCRM] = useState(null);

  const refreshConns = () => setConns(loadConnections());

  const handleSave = (crm, cfg) => {
    const next = { ...conns, [crm.id]: cfg };
    setConns(next); saveConnections(next);
    setActiveCRM(null);
    toast && toast.push(t('acct.int.connectSuccess', { name: crm.name }), 'positive');
  };

  const handleDisconnect = (crm) => {
    const next = { ...conns }; delete next[crm.id];
    setConns(next); saveConnections(next);
    setActiveCRM(null);
    toast && toast.push(t('acct.int.disconnectSuccess', { name: crm.name }), 'default');
  };

  return (
    <>
      {/* MCP integration — Leadscraper as MCP server for AI tools */}
      <div className="bg-white border border-line rounded-xl overflow-hidden">
        <div className="px-6 py-4 border-b border-[#F0F4FA] flex items-start justify-between gap-4">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <span className="text-[14.5px] font-semibold text-ink">Leadscraper als MCP-Server</span>
              <span className="inline-flex items-center gap-1 px-1.5 py-[2px] rounded text-[10px] font-medium bg-[#EEF2FE] text-[#3465E3] tracking-wide">BETA</span>
            </div>
            <div className="text-[12.5px] text-ink-muted mt-1 max-w-[620px] leading-snug">
              Verbinde Leadscraper direkt mit Claude, ChatGPT, Cursor oder deinem eigenen Agenten via Model Context Protocol. Deine Leads, Profile & Memory werden nativ als Tools verfügbar.
            </div>
          </div>
          <button
            onClick={() => {
              navigator.clipboard?.writeText('https://mcp.leadscraper.de/v1/sse');
              toast && toast.push('MCP-Endpoint kopiert.', 'positive');
            }}
            className="px-3 h-[30px] rounded-md border border-line text-[12px] font-medium text-ink hover:bg-gray-50 transition-colors flex-shrink-0 inline-flex items-center gap-1.5">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>
            Endpoint kopieren
          </button>
        </div>

        {/* MCP clients grid */}
        <div className="grid grid-cols-4 divide-x divide-[#F0F4FA]">
          {[
            { id: 'claude', name: 'Claude', sub: 'Desktop & Web', logo: (
              <svg width="20" height="20" viewBox="0 0 40 40"><path d="M10 8h6l4 24h-6zm14 0h6l-8 24h-6z" fill="#D97757"/></svg>
            )},
            { id: 'chatgpt', name: 'ChatGPT', sub: 'Custom GPTs', logo: (
              <svg width="20" height="20" viewBox="0 0 40 40"><path d="M20 6a14 14 0 1 0 0 28 14 14 0 0 0 0-28zm0 4.5a9.5 9.5 0 0 1 9.5 9.5 9.5 9.5 0 0 1-9.5 9.5 9.5 9.5 0 0 1-9.5-9.5 9.5 9.5 0 0 1 9.5-9.5z" fill="#10A37F"/></svg>
            )},
            { id: 'cursor', name: 'Cursor', sub: 'IDE', logo: (
              <svg width="20" height="20" viewBox="0 0 40 40"><path d="M20 6L6 14v12l14 8 14-8V14z" fill="#1F1F1F"/><path d="M20 6v28M6 14l28 12M34 14L6 26" stroke="#fff" strokeWidth="1" opacity="0.4"/></svg>
            )},
            { id: 'custom', name: 'Eigener Agent', sub: 'SDK · TS/Py', logo: (
              <svg width="20" height="20" viewBox="0 0 40 40" fill="none" stroke="#6B7280" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 12 8 20 15 28"/><polyline points="25 12 32 20 25 28"/></svg>
            )},
          ].map(c => (
            <div key={c.id} className="px-4 py-3.5 flex items-center gap-3 hover:bg-[#FAFBFD] transition-colors">
              <div className="w-9 h-9 rounded-lg bg-[#F7F9FC] border border-[#EEF1F6] flex items-center justify-center flex-shrink-0">
                {c.logo}
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-[13px] font-medium text-ink truncate">{c.name}</div>
                <div className="text-[11.5px] text-ink-muted truncate">{c.sub}</div>
              </div>
            </div>
          ))}
        </div>

        {/* Endpoint + tools */}
        <div className="px-6 py-4 border-t border-[#F0F4FA] bg-[#FAFBFD] grid grid-cols-[1fr_auto] items-center gap-4">
          <div className="font-mono text-[12px] text-ink-muted truncate">
            <span className="text-ink-soft">https://</span><span className="text-ink">mcp.leadscraper.de</span><span className="text-ink-soft">/v1/sse</span>
          </div>
          <div className="text-[11.5px] text-ink-soft tabular-nums flex items-center gap-3">
            <span><span className="text-ink font-medium">12</span> Tools</span>
            <span className="w-1 h-1 rounded-full bg-[#D4DAE6]"/>
            <span><span className="text-ink font-medium">4</span> Resources</span>
            <span className="w-1 h-1 rounded-full bg-[#D4DAE6]"/>
            <span className="inline-flex items-center gap-1 text-emerald-700">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"/> Live
            </span>
          </div>
        </div>
      </div>

      {/* CRM integrations */}
      <div className="bg-white border border-line rounded-xl overflow-hidden">
        <div className="px-6 py-4 border-b border-[#F0F4FA]">
          <div className="text-[14.5px] font-semibold text-ink">{t('acct.int.title')}</div>
          <div className="text-[12.5px] text-ink-muted mt-0.5 max-w-[620px]">{t('acct.int.sub')}</div>
        </div>

        <div className="grid grid-cols-2 divide-x divide-[#F0F4FA]">
          {CRM_CATALOG.map((crm, i) => {
            const conn = conns[crm.id];
            const connected = !!conn;
            const isBottomRow = i >= CRM_CATALOG.length - 2;
            return (
              <div key={crm.id}
                   className={`px-5 py-4 flex items-center gap-3.5 hover:bg-[#FAFBFD] transition-colors ${!isBottomRow ? 'border-b border-[#F0F4FA]' : ''}`}>
                <CRMMark crm={crm} size={40}/>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-[13.5px] font-medium text-ink truncate">{crm.name}</span>
                    {connected && (
                      <span className="inline-flex items-center gap-1 text-[11px] text-emerald-700 font-medium">
                        <span className="w-1 h-1 rounded-full bg-emerald-600"/>
                        {t('acct.int.connected')}
                      </span>
                    )}
                  </div>
                  <div className="text-[12px] text-ink-muted truncate">
                    {connected
                      ? `${conn.object}${conn.pipeline ? ' · ' + conn.pipeline : ''}${conn.autoPush ? ' · Auto-Push' : ''}`
                      : crm.tagline}
                  </div>
                </div>
                <button onClick={() => setActiveCRM(crm)}
                        className={`px-3 h-[30px] rounded-md text-[12px] font-medium transition-colors flex-shrink-0 ${
                          connected
                            ? 'border border-line text-ink-muted hover:bg-gray-50'
                            : 'border border-line text-ink hover:bg-gray-50'
                        }`}>
                  {connected ? t('acct.int.manage') : t('acct.int.connect')}
                </button>
              </div>
            );
          })}
        </div>
      </div>

      {activeCRM && (
        <CRMConnectModal
          crm={activeCRM}
          existing={conns[activeCRM.id]}
          onClose={() => setActiveCRM(null)}
          onSave={(cfg) => handleSave(activeCRM, cfg)}
          onDisconnect={() => handleDisconnect(activeCRM)}
        />
      )}
    </>
  );
}

// --- CRM Push Chip (for table rows & detail view) ----------------------
function CRMStatusChip({ leadId, pushes, primaryCRM, onPush, compact = false }) {
  useLang();
  const push = pushes[leadId];
  if (push) {
    const crm = CRM_CATALOG.find(c => c.id === push.crmId);
    if (!crm) return null;
    return (
      <a href={push.url} target="_blank" rel="noreferrer"
         onClick={e => e.stopPropagation()}
         className="inline-flex items-center gap-1.5 text-[11.5px] text-ink-muted hover:text-ink transition-colors">
        <span className="w-3.5 h-3.5 rounded flex items-center justify-center flex-shrink-0"
              style={{ background: crm.color }}>
          <span className="text-white font-semibold" style={{ fontSize: 7, letterSpacing: '-0.02em' }}>
            {crm.name.slice(0, 2).toUpperCase()}
          </span>
        </span>
        {compact ? crm.name : t('acct.int.pushedTo', { name: crm.name })}
      </a>
    );
  }
  if (!primaryCRM) return null;
  return (
    <button onClick={e => { e.stopPropagation(); onPush(); }}
            className="inline-flex items-center gap-1 text-[11.5px] text-ink-soft hover:text-ink transition-colors">
      <Icon.ExtLink size={10}/>
      {compact ? '→ ' + primaryCRM.name : t('acct.int.pushToCRM')}
    </button>
  );
}

Object.assign(window, {
  CRM_CATALOG, CRMMark, useCRM, CRMConnectModal, IntegrationsPanel, CRMStatusChip,
  loadConnections, loadPushes, saveConnections, savePushes,
});
