// Leads Table — clean, export-style overview. Primary leads view.
// Inline-expand for "Gedanken" preview; "Details" opens the full 360° page.

function MatchDot({ score }) {
  const pct = Math.round(score * 100);
  // Minimal: just the number, monospaced, slightly weighted. Premium = restraint.
  // Subtle tier indicator via a single dot color, no bar.
  const tone = score >= 0.75 ? '#0B0F19' : score >= 0.5 ? '#6B7280' : '#B7A26A';
  return (
    <span className="inline-flex items-center gap-1.5">
      <span className="w-1 h-1 rounded-full" style={{background:tone}}/>
      <span className="text-[13px] font-medium tabular-nums text-ink">{pct}</span>
    </span>
  );
}

function StatusPill({ state }) {
  useLang();
  // Minimal: tiny dot + text, no pill background. Pills were too loud.
  if (state === 'accepted') return <span className="inline-flex items-center gap-1.5 text-[12px] text-emerald-700"><span className="w-1 h-1 rounded-full bg-emerald-600"/>{t('leads.status.accepted')}</span>;
  if (state === 'rejected') return <span className="inline-flex items-center gap-1.5 text-[12px] text-ink-soft"><span className="w-1 h-1 rounded-full bg-gray-400"/>{t('leads.status.rejected')}</span>;
  return <span className="inline-flex items-center gap-1.5 text-[12px] text-ink-muted"><span className="w-1 h-1 rounded-full bg-[#3465E3]"/>{t('leads.status.unseen')}</span>;
}

// Column definitions — id, labelKey, default visibility, renderer
const COLUMNS = [
  { id: 'company',  labelKey: 'leads.col.company',  default: true,  always: true,  width: '260px' },
  { id: 'profile',  labelKey: 'leads.col.profile',  default: true,  width: '170px' },
  { id: 'sector',   labelKey: 'leads.col.sector',   default: true,  width: '200px' },
  { id: 'city',     labelKey: 'leads.col.city',     default: true,  width: '140px' },
  { id: 'size',     labelKey: 'leads.col.size',     default: true,  width: '72px',  align: 'right' },
  { id: 'match',    labelKey: 'leads.col.match',    default: true,  width: '110px' },
  { id: 'status',   labelKey: 'leads.col.status',   default: true,  width: '120px' },
  { id: 'decider',  labelKey: 'leads.col.decider',  default: true,  width: '170px' },
  // Optional — hidden by default
  { id: 'founded',  labelKey: 'leads.col.founded',  default: false, width: '90px',  align: 'right' },
  { id: 'website',  labelKey: 'leads.col.website',  default: false, width: '160px' },
  { id: 'phone',    labelKey: 'leads.col.phone',    default: false, width: '140px' },
  { id: 'revenue',  labelKey: 'leads.col.revenue',  default: false, width: '120px', align: 'right' },
  { id: 'lastActivity', labelKey: 'leads.col.lastActivity', default: false, width: '130px' },
  { id: 'crm',      labelKey: 'leads.col.crm',      default: true,  width: '130px' },
];

function ColumnSettings({ visible, setVisible, onClose }) {
  useLang();
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [onClose]);
  const toggle = (id) => setVisible({ ...visible, [id]: !visible[id] });
  return (
    <div ref={ref} className="absolute right-0 top-full mt-1.5 bg-white border border-line rounded-lg shadow-xl z-30 fade-in overflow-hidden w-[260px]">
      <div className="px-3.5 py-2.5 border-b border-line">
        <div className="text-[13px] font-medium text-ink">{t('leads.cols.title')}</div>
        <div className="text-[11px] text-ink-muted mt-0.5">{t('leads.cols.sub')}</div>
      </div>
      <div className="max-h-[320px] overflow-y-auto py-1">
        {COLUMNS.map(col => (
          <label key={col.id} className={`flex items-center gap-2.5 px-3.5 py-1.5 text-[13px] ${col.always ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-gray-50'}`}>
            <input
              type="checkbox"
              checked={col.always || !!visible[col.id]}
              disabled={col.always}
              onChange={() => !col.always && toggle(col.id)}
              className="accent-brand-500"
            />
            <span className="text-ink flex-1">{t(col.labelKey)}</span>
            {col.always && <span className="text-[10px] text-ink-soft uppercase tracking-wider">{t('leads.cols.fixed')}</span>}
          </label>
        ))}
      </div>
      <div className="hair"/>
      <button
        onClick={() => setVisible(Object.fromEntries(COLUMNS.map(c => [c.id, c.default])))}
        className="w-full px-3.5 py-2 text-left text-[12px] text-ink-muted hover:bg-gray-50">
        {t('leads.cols.reset')}
      </button>
    </div>
  );
}

function ExpandedRow({ lead, profile, visibleCols, onOpenDetail, onAccept, onReject, state }) {
  useLang();
  const [rejectOpen, setRejectOpen] = useState(false);
  const memMap = Object.fromEntries(profile.memory.map(m => [m.id, m]));
  const referenced = (lead.reasonRefs || []).map(id => memMap[id]).filter(Boolean);

  const colCount = 1 + COLUMNS.filter(c => (c.always || visibleCols[c.id])).length + 1; // +actions

  return (
    <tr className="bg-[#FAFCFF] border-t border-line">
      <td colSpan={colCount} className="px-6 py-5">
        <div className="grid grid-cols-[1fr_260px] gap-8 max-w-full">
          {/* Left: Leadscraper's reasoning */}
          <div>
            <div className="text-[10.5px] uppercase tracking-[0.1em] font-medium text-ink-soft mb-2">
              {t('leads.exp.whyShown')}
            </div>
            <p className="text-[14px] leading-[1.6] text-ink max-w-[640px]">{lead.reason}</p>
            {lead.uncertainty && (
              <p className="text-[12.5px] italic text-ink-muted mt-2 leading-snug">
                {t('leads.exp.uncertain', { score: lead.score, note: lead.uncertainty })}
              </p>
            )}
            {referenced.length > 0 && (
              <div className="mt-3 space-y-1.5">
                <div className="text-[10.5px] uppercase tracking-[0.1em] font-medium text-ink-soft">
                  {t('leads.exp.memoryRefs')}
                </div>
                {referenced.map(m => (
                  <div key={m.id} className="flex items-start gap-2 text-[12.5px] text-ink-muted leading-snug">
                    <span className={`mt-1.5 h-1 w-1 rounded-full flex-shrink-0 ${m.strength==='strong'?'bg-ink':'bg-ink/40'}`}/>
                    <span>„{m.text}"</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Right: actions & quick facts */}
          <div className="flex flex-col gap-2.5">
            {state === 'neutral' && !rejectOpen && (
              <>
                <button onClick={(e) => { e.stopPropagation(); onAccept(); }}
                  className="inline-flex items-center justify-center gap-2 px-3 py-2 rounded-md border border-emerald-300 text-emerald-800 text-[13px] font-medium hover:bg-emerald-50 transition-colors">
                  <Icon.Check size={14}/> {t('leads.act.fits')}
                </button>
                <button onClick={(e) => { e.stopPropagation(); setRejectOpen(true); }}
                  className="inline-flex items-center justify-center gap-2 px-3 py-2 rounded-md border border-line text-ink-muted text-[13px] hover:bg-gray-50 transition-colors">
                  <Icon.X size={14}/> {t('leads.act.fitsNot')}
                </button>
              </>
            )}
            {state === 'neutral' && rejectOpen && (
              <div>
                <div className="text-[10.5px] uppercase tracking-[0.1em] font-medium text-ink-soft mb-1.5">
                  {t('leads.act.reason')}
                </div>
                <div className="flex flex-col gap-1">
                  {profile.reasons.map(r => (
                    <button
                      key={r}
                      onClick={(e) => { e.stopPropagation(); onReject(r); setRejectOpen(false); }}
                      className="text-left text-[12.5px] px-2.5 py-1.5 rounded-md border border-line bg-white text-ink hover:border-ink hover:bg-ink hover:text-white transition-colors">
                      {r}
                    </button>
                  ))}
                </div>
                <button
                  onClick={(e) => { e.stopPropagation(); setRejectOpen(false); }}
                  className="mt-1.5 text-[11px] text-ink-soft hover:text-ink">
                  {t('leads.act.cancel')}
                </button>
              </div>
            )}
            {state === 'accepted' && (
              <div className="px-3 py-2 rounded-md bg-emerald-50 text-emerald-700 text-[12.5px] font-medium inline-flex items-center gap-1.5">
                <Icon.Check size={14}/> {t('leads.act.fitsDone')}
              </div>
            )}
            {state === 'rejected' && (
              <div className="px-3 py-2 rounded-md bg-gray-100 text-ink-muted text-[12.5px] font-medium inline-flex items-center gap-1.5">
                <Icon.X size={14}/> {t('leads.act.fitsNotDone')}
              </div>
            )}

            <button onClick={(e) => { e.stopPropagation(); onOpenDetail(); }}
              className="inline-flex items-center justify-center gap-2 px-3 py-2 rounded-md bg-ink text-white text-[13px] font-medium hover:bg-black transition-colors mt-1">
              {t('leads.act.details')} <Icon.ChevRight size={12}/>
            </button>
          </div>
        </div>
      </td>
    </tr>
  );
}

function LeadsTable({ profiles, feedbackByProfile, setFeedbackByProfile, activeFilter, setActiveFilter, onOpenLead, density, toast }) {
  useLang();

  // Column visibility — default set, persisted in localStorage
  const [visibleCols, setVisibleCols] = useState(() => {
    try {
      const stored = localStorage.getItem('ls.leadsCols');
      if (stored) return JSON.parse(stored);
    } catch (e) {}
    return Object.fromEntries(COLUMNS.map(c => [c.id, c.default]));
  });
  useEffect(() => {
    try { localStorage.setItem('ls.leadsCols', JSON.stringify(visibleCols)); } catch (e) {}
  }, [visibleCols]);

  const [colSettingsOpen, setColSettingsOpen] = useState(false);
  const [expandedId, setExpandedId] = useState(null);
  const [searchQ, setSearchQ] = useState('');

  // Collect all leads across all profiles, attach profile ref + fake match score
  const allRows = useMemo(() => {
    const rows = [];
    profiles.forEach(p => {
      (p.leads || []).forEach((lead, idx) => {
        const score = lead.score === 'unsicher'
          ? 0.38 + (idx * 0.05 % 0.1)
          : 0.58 + ((lead.id.charCodeAt(1) * 7) % 40) / 100;
        // Mock extra data for optional columns — deterministic per lead id
        const seed = lead.id.charCodeAt(1) + lead.id.charCodeAt(2) * 3;
        const phone = `+49 ${200 + (seed % 80)} ${1000 + (seed * 17) % 9000}`;
        const revenueM = 2 + (seed % 45);
        const activityDays = 1 + (seed % 28);
        rows.push({
          lead, profile: p,
          match: Math.min(0.95, score),
          state: (feedbackByProfile[p.id] || {})[lead.id] || 'neutral',
          phone, revenueM, activityDays
        });
      });
    });
    return rows.sort((a, b) => b.match - a.match);
  }, [profiles, feedbackByProfile]);

  const filtered = useMemo(() => {
    let rows = activeFilter === 'all' ? allRows : allRows.filter(r => r.profile.id === activeFilter);
    if (searchQ.trim()) {
      const q = searchQ.toLowerCase();
      rows = rows.filter(r =>
        r.lead.company.toLowerCase().includes(q) ||
        r.lead.sector.toLowerCase().includes(q) ||
        r.lead.city.toLowerCase().includes(q) ||
        (r.lead.decider?.name || '').toLowerCase().includes(q)
      );
    }
    return rows;
  }, [allRows, activeFilter, searchQ]);

  const rowPad = density === 'compact' ? 'py-2.5' : 'py-4';
  const shownCols = COLUMNS.filter(c => c.always || visibleCols[c.id]);

  // CRM integration hook
  const [crmPushes, setCrmPushes] = useState(loadPushes);
  const crmConns = loadConnections();
  const primaryCRMId = Object.keys(crmConns)[0] || null;
  const primaryCRM = primaryCRMId ? CRM_CATALOG.find(c => c.id === primaryCRMId) : null;
  const autoPushEnabled = primaryCRMId && crmConns[primaryCRMId]?.autoPush;

  const pushToCRM = (row, silent = false) => {
    if (!primaryCRM) return;
    const next = { ...crmPushes, [row.lead.id]: {
      crmId: primaryCRM.id,
      at: Date.now(),
      url: `https://app.${primaryCRM.domain}/leads/${row.lead.id}`,
    }};
    setCrmPushes(next); savePushes(next);
    if (!silent) toast && toast.push(t('acct.int.pushSuccess', { n: 1, name: primaryCRM.name }), 'positive');
  };

  const setFeedback = (profileId, leadId, state) => {
    const fb = feedbackByProfile[profileId] || {};
    setFeedbackByProfile({ ...feedbackByProfile, [profileId]: { ...fb, [leadId]: state } });
  };
  const acceptRow = (row) => {
    setFeedback(row.profile.id, row.lead.id, 'accepted');
    // Auto-push when enabled
    if (autoPushEnabled && !crmPushes[row.lead.id]) {
      pushToCRM(row, true);
      toast && toast.push(t('leads.toast.accepted', { c: row.lead.company }) + ' · ' + t('acct.int.pushedTo', { name: primaryCRM.name }), 'positive');
    } else {
      toast && toast.push(t('leads.toast.accepted', { c: row.lead.company }), 'positive');
    }
  };
  const rejectRow = (row, reason) => {
    setFeedback(row.profile.id, row.lead.id, 'rejected');
    toast && toast.push(t('leads.toast.rejected', { r: reason }), 'negative');
  };

  return (
    <div data-screen-label="Leads · Tabelle" className="max-w-[1440px] mx-auto px-6 py-7">
      {/* Header */}
      <div className="flex items-end justify-between gap-6 mb-5">
        <div>
          <div className="text-[12px] text-ink-soft uppercase tracking-[0.08em] font-medium">{t('nav.leads')}</div>
          <h1 className="text-[26px] font-semibold text-ink leading-tight mt-0.5 tracking-tight">{t('leads.title')}</h1>
          <p className="text-[13.5px] text-ink-muted mt-1 max-w-[780px]">{t('leads.sub', { n: allRows.length })}</p>
        </div>
      </div>

      {/* Profile filter — minimal tab-style row, no pill backgrounds */}
      <div className="mb-4 flex items-center gap-5 border-b border-line/60">
        <button
          onClick={() => setActiveFilter('all')}
          className={`relative pb-2.5 text-[13px] font-medium transition-colors ${
            activeFilter === 'all' ? 'text-ink' : 'text-ink-soft hover:text-ink-muted'
          }`}>
          <span className="inline-flex items-center gap-1.5">
            {t('leads.allProfiles')}
            <span className="text-[11px] text-ink-soft tabular-nums font-normal">{allRows.length}</span>
          </span>
          {activeFilter === 'all' && <span className="absolute -bottom-px left-0 right-0 h-[1.5px] bg-ink"/>}
        </button>
        {profiles.map(p => {
          const count = allRows.filter(r => r.profile.id === p.id).length;
          const active = activeFilter === p.id;
          const dot = p.id === 'faltschachtel' ? '#3465E3' : '#8B5CF6';
          return (
            <button key={p.id} onClick={() => setActiveFilter(p.id)}
              className={`relative pb-2.5 text-[13px] font-medium transition-colors ${
                active ? 'text-ink' : 'text-ink-soft hover:text-ink-muted'
              }`}>
              <span className="inline-flex items-center gap-1.5">
                <span className="w-1 h-1 rounded-full flex-shrink-0" style={{background: dot}}/>
                {p.short}
                <span className="text-[11px] text-ink-soft tabular-nums font-normal">{count}</span>
              </span>
              {active && <span className="absolute -bottom-px left-0 right-0 h-[1.5px] bg-ink"/>}
            </button>
          );
        })}
      </div>

      {/* Toolbar: search + column settings + export */}
      <div className="mb-3 flex items-center gap-2">
        <div className="relative flex-1 max-w-[360px]">
          <Icon.Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-soft"/>
          <input
            value={searchQ}
            onChange={e => setSearchQ(e.target.value)}
            placeholder={t('leads.searchP')}
            className="w-full pl-8 pr-3 py-1.5 text-[13px] border border-line rounded-md bg-white placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]"
          />
        </div>
        <div className="flex-1"/>
        <span className="text-[12px] text-ink-muted tabular-nums">
          {t('leads.count', { shown: filtered.length, total: allRows.length })}
        </span>
        <div className="relative">
          <button
            onClick={() => setColSettingsOpen(o => !o)}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border border-line bg-white text-[12.5px] text-ink-muted hover:bg-gray-50 transition-colors">
            <Icon.Columns size={13}/> {t('leads.cols.btn')}
            <span className="text-[10.5px] text-ink-soft tabular-nums">
              {shownCols.length}/{COLUMNS.length}
            </span>
          </button>
          {colSettingsOpen && (
            <ColumnSettings
              visible={visibleCols}
              setVisible={setVisibleCols}
              onClose={() => setColSettingsOpen(false)}
            />
          )}
        </div>
        <button
          onClick={() => toast && toast.push(t('leads.toast.export'), 'default')}
          className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border border-line bg-white text-[12.5px] text-ink-muted hover:bg-gray-50 transition-colors">
          <Icon.Download size={13}/> {t('leads.export')}
        </button>
      </div>

      {/* Table */}
      <div className="bg-white border border-line rounded-lg overflow-hidden">
        {filtered.length === 0 ? (
          <div className="p-12 text-center text-[13px] text-ink-muted">{t('leads.empty')}</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-[13px]" style={{ tableLayout: 'auto' }}>
              <thead>
                <tr className="text-left text-[10.5px] uppercase tracking-[0.1em] text-ink-soft border-b border-line">
                  {shownCols.map((col, i) => (
                    <th key={col.id}
                        className={`${i===0 ? 'px-5' : 'px-3'} py-3 font-medium whitespace-nowrap ${col.align==='right'?'text-right':''}`}
                        style={{ width: col.width }}>
                      {t(col.labelKey)}
                    </th>
                  ))}
                  <th className="px-5 py-3 font-medium text-right whitespace-nowrap" style={{width:'80px'}}></th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((row) => {
                  const { lead, profile, match, state, phone, revenueM, activityDays } = row;
                  const rowKey = profile.id + '-' + lead.id;
                  const isExpanded = expandedId === rowKey;

                  const cellFor = (colId) => {
                    switch (colId) {
                      case 'company':
                        return (
                          <div className="flex items-center gap-2.5 min-w-0">
                            {lead.isNew
                              ? <span className="w-1 h-1 rounded-full bg-[#3465E3] flex-shrink-0" title="Neu"/>
                              : <span className="w-1 h-1 flex-shrink-0"/>}
                            <div className="min-w-0">
                              <div className="text-[14px] font-medium text-ink truncate leading-tight">{lead.company}</div>
                              {(lead.score === 'unsicher' || lead.uncertainty) && state === 'neutral' && (
                                <span className="text-[11px] text-ink-soft mt-0.5 block">
                                  {t('leads.chip.edge')}
                                </span>
                              )}
                            </div>
                          </div>
                        );
                      case 'profile':
                        return (
                          <span className="inline-flex items-center gap-1.5 text-[12px] text-ink-muted max-w-full">
                            <span className="w-1 h-1 rounded-full flex-shrink-0" style={{background: profile.id === 'faltschachtel' ? '#3465E3' : '#8B5CF6'}}/>
                            <span className="truncate">{profile.short}</span>
                          </span>
                        );
                      case 'sector':   return <span className="text-ink-muted truncate block">{lead.sector}</span>;
                      case 'city':     return <span className="text-ink">{lead.city}</span>;
                      case 'size':     return <span className="text-ink tabular-nums">{(lead.size.match(/[\d.]+/) || ['—'])[0]}</span>;
                      case 'founded':  return <span className="text-ink-muted tabular-nums">{(lead.founded.match(/\d{4}/) || ['—'])[0]}</span>;
                      case 'match':    return <MatchDot score={match}/>;
                      case 'status':   return <StatusPill state={state}/>;
                      case 'decider':  return <span className="text-ink-muted truncate block">{lead.decider?.name || '—'}</span>;
                      case 'website':
                        return (
                          <a href={`https://${lead.website}`} onClick={e=>e.stopPropagation()} target="_blank" rel="noreferrer"
                             className="inline-flex items-center gap-1 text-[12.5px] text-[#3465E3] hover:underline truncate max-w-full">
                            <span className="truncate">{lead.website}</span> <Icon.ExtLink size={10} className="flex-shrink-0"/>
                          </a>
                        );
                      case 'phone':    return <span className="text-ink-muted tabular-nums text-[12.5px]">{phone}</span>;
                      case 'revenue':  return <span className="text-ink-muted tabular-nums text-[12.5px]">{revenueM} Mio €</span>;
                      case 'lastActivity':
                        return <span className="text-ink-muted text-[12.5px]">{t('leads.daysAgo', { n: activityDays })}</span>;
                      case 'crm': {
                        const push = crmPushes[lead.id];
                        if (push) {
                          const crm = CRM_CATALOG.find(c => c.id === push.crmId);
                          if (!crm) return <span className="text-ink-soft text-[12px]">—</span>;
                          return (
                            <a href={push.url} target="_blank" rel="noreferrer"
                               onClick={e => e.stopPropagation()}
                               className="inline-flex items-center gap-1.5 text-[12px] 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>
                              {crm.name}
                              <Icon.ExtLink size={9} className="text-ink-soft"/>
                            </a>
                          );
                        }
                        if (!primaryCRM) return <span className="text-ink-soft text-[12px]">—</span>;
                        return (
                          <button onClick={e => { e.stopPropagation(); pushToCRM(row); }}
                                  className="inline-flex items-center gap-1 text-[12px] text-ink-soft hover:text-ink transition-colors">
                            <Icon.ExtLink size={10}/> {t('leads.crm.push')}
                          </button>
                        );
                      }
                      default: return null;
                    }
                  };

                  return (
                    <React.Fragment key={rowKey}>
                      <tr
                          onClick={() => setExpandedId(isExpanded ? null : rowKey)}
                          className={`group border-b border-line/50 last:border-b-0 cursor-pointer hover:bg-[#FAFBFD] transition-colors ${state==='rejected' ? 'opacity-55' : ''} ${isExpanded?'bg-[#FAFBFD]':''}`}>
                        {shownCols.map((col, i) => (
                          <td key={col.id}
                              className={`${i===0?'px-5':'px-3'} ${rowPad} align-middle ${col.align==='right'?'text-right':''}`}>
                            {cellFor(col.id)}
                          </td>
                        ))}
                        <td className={`px-5 ${rowPad} align-middle text-right`}>
                          <div className="inline-flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity" onClick={e => e.stopPropagation()}>
                            {state === 'neutral' && (
                              <>
                                <button
                                  onClick={() => acceptRow(row)}
                                  title={t('leads.act.fits')}
                                  className="w-7 h-7 rounded text-ink-muted hover:bg-emerald-50 hover:text-emerald-700 transition-colors inline-flex items-center justify-center">
                                  <Icon.Check size={13}/>
                                </button>
                                <button
                                  onClick={() => setExpandedId(rowKey)}
                                  title={t('leads.act.fitsNot')}
                                  className="w-7 h-7 rounded text-ink-soft hover:bg-gray-100 hover:text-ink transition-colors inline-flex items-center justify-center">
                                  <Icon.X size={13}/>
                                </button>
                              </>
                            )}
                            <button
                              onClick={() => onOpenLead(lead, profile)}
                              title={t('leads.act.details')}
                              className="w-7 h-7 rounded text-ink-soft hover:bg-gray-100 hover:text-ink transition-colors inline-flex items-center justify-center">
                              <Icon.ChevRight size={13}/>
                            </button>
                          </div>
                          {/* Persistent state indicators (shown always, not just on hover) */}
                          {state === 'accepted' && (
                            <span className="inline-flex items-center justify-center w-7 h-7 text-emerald-600 group-hover:hidden" title={t('leads.act.fitsDone')}>
                              <Icon.Check size={13}/>
                            </span>
                          )}
                          {state === 'rejected' && (
                            <span className="inline-flex items-center justify-center w-7 h-7 text-ink-soft group-hover:hidden" title={t('leads.act.fitsNotDone')}>
                              <Icon.X size={13}/>
                            </span>
                          )}
                        </td>
                      </tr>
                      {isExpanded && (
                        <ExpandedRow
                          lead={lead}
                          profile={profile}
                          visibleCols={visibleCols}
                          state={state}
                          onOpenDetail={() => onOpenLead(lead, profile)}
                          onAccept={() => acceptRow(row)}
                          onReject={(reason) => rejectRow(row, reason)}
                        />
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Footer hint */}
      <div className="mt-3 text-[11.5px] text-ink-soft">
        {t('leads.footerHint')}
      </div>
    </div>
  );
}

Object.assign(window, { LeadsTable });
