// Dashboard screen — mirrors app.leadscraper.de/dashboard --------------
function StatCard({ label, value, tone = 'ink', locked = true }) {
  const toneClass = tone === 'positive' ? 'text-emerald-600'
                  : tone === 'violet'   ? 'text-[#B880FC]'
                  : tone === 'brand'    ? 'text-[#3465E3]'
                  : 'text-ink';
  return (
    <div className="bg-white border border-line rounded-lg px-4 py-3 relative">
      <div className="text-[12px] text-ink-muted truncate">{label}</div>
      <div className="flex items-end justify-between mt-1">
        <div className={`text-[24px] font-semibold leading-none tracking-tight ${toneClass}`}>{value}</div>
        {locked && (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#C7CFDA" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
        )}
      </div>
    </div>
  );
}

function EmptyChart() {
  useLang();
  const months = t('dash.months').split(',');
  return (
    <div className="mt-4">
      <div className="text-[11px] text-ink-muted mb-1">{t('dash.totalLeads')}</div>
      <div className="text-[16px] font-semibold text-ink mb-2">0</div>
      <div className="relative h-[260px] border-t border-line">
        {[0, 3, 6, 9, 12].map((v, i) => (
          <div key={i} className="absolute left-0 right-0 border-t border-dashed border-[#EEF2F8]" style={{ top: `${100 - (v/12)*100}%` }}>
            <span className="absolute -left-5 -top-2 text-[10px] text-ink-soft">{v}</span>
          </div>
        ))}
        <svg className="absolute inset-0 w-full h-full" preserveAspectRatio="none" viewBox="0 0 100 100">
          <line x1="0" y1="100" x2="100" y2="100" stroke="#3465E3" strokeWidth="0.6" vectorEffect="non-scaling-stroke"/>
        </svg>
      </div>
      <div className="flex justify-between text-[10px] text-ink-soft mt-1">
        {months.map(m => <span key={m}>{m}</span>)}
      </div>
    </div>
  );
}

function ProfileDropdown({ profiles, selectedId, onSelect, onCreateProfile }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const sel = profiles.find(p => p.id === selectedId) || profiles[0];
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)}
        className="w-full flex items-center gap-2.5 border border-[#3465E3] bg-[#F5F8FE] rounded-md px-3 py-2 text-left hover:bg-[#EEF2FE] transition-colors">
        <div className="w-6 h-6 rounded flex items-center justify-center text-[11px] font-semibold bg-[#3465E3] text-white">{sel.initial}</div>
        <div className="flex-1 min-w-0">
          <div className="text-[13px] font-medium text-ink truncate">{sel.name}</div>
          <div className="text-[11px] text-ink-muted truncate">{sel.query}</div>
        </div>
        <Icon.ChevDown size={14} className="text-ink-muted flex-shrink-0"/>
      </button>
      {open && (
        <div className="absolute left-0 right-0 top-full mt-1 bg-white border border-line rounded-lg shadow-xl z-30 fade-in overflow-hidden">
          {profiles.map(p => (
            <button key={p.id} onClick={() => { onSelect(p.id); setOpen(false); }}
              className={`w-full text-left px-3 py-2 flex items-center gap-2.5 hover:bg-gray-50 ${p.id === selectedId ? 'bg-brand-50/40' : ''}`}>
              <div className={`w-6 h-6 rounded flex items-center justify-center text-[11px] font-semibold ${p.id===selectedId ? 'bg-brand-500 text-white':'bg-gray-100 text-ink'}`}>{p.initial}</div>
              <div className="flex-1 min-w-0">
                <div className="text-[12.5px] font-medium text-ink truncate">{p.name}</div>
                <div className="text-[10.5px] text-ink-muted truncate">{p.feedbackCount} {t('nav.feedbacks')} · {Math.round(p.matchRateNow*100)} % {t('nav.matchRate')}</div>
              </div>
              {p.id === selectedId && <Icon.Check size={14} className="text-brand-500"/>}
            </button>
          ))}
          <div className="hair"/>
          <button onClick={() => { setOpen(false); onCreateProfile && onCreateProfile(); }} className="w-full text-left px-3 py-2 flex items-center gap-2 text-[12.5px] text-ink-muted hover:bg-gray-50">
            <Icon.Plus size={12}/> {t('nav.newProfile')}
          </button>
        </div>
      )}
    </div>
  );
}

function NewLeadsForm({ onStart, profiles, activeProfileId, setActiveProfileId, onCreateProfile, embedded = false }) {
  const [schedule, setSchedule] = useState({ frequency: 'once', time: '08:00', weekday: 1, dayOfMonth: 1, autoPush: false });
  const crm = useCRM();
  const crmConnected = Object.keys(crm.conns || {}).length > 0;

  const handleStart = () => {
    // If recurring, persist a scheduled run for the active profile
    if (schedule.frequency !== 'once' && activeProfileId) {
      const all = loadSchedules();
      const newEntry = {
        id: `sched-${Date.now()}`,
        profileId: activeProfileId,
        query: {
          businessType: 'Custom',
          location: '—',
          contact: '—',
          extras: '',
          amount: 20,
        },
        frequency: schedule.frequency,
        time: schedule.time,
        weekday: schedule.weekday,
        dayOfMonth: schedule.dayOfMonth,
        autoPush: !!(schedule.autoPush && crmConnected),
        active: true,
        createdAt: Date.now(),
      };
      saveSchedules([newEntry, ...all]);
      if (window.__toastRef) window.__toastRef.push(t('sched.toast.created'), 'positive');
    }
    if (onStart) onStart();
  };

  const inner = (
    <>
      {!embedded && <div className="text-[15px] font-semibold text-ink mb-4">{t('find.title')}</div>}

      {/* Profile picker — prominent, first */}
      <div className="mb-4 pb-4 border-b border-line">
        <label className="block text-[12px] font-medium text-ink mb-1.5">{t('find.forProfile')}</label>
        <ProfileDropdown profiles={profiles} selectedId={activeProfileId} onSelect={setActiveProfileId} onCreateProfile={onCreateProfile}/>
        <div className="mt-2 flex items-start gap-1.5 text-[11.5px] text-[#3465E3] leading-snug">
          <Icon.Brain size={13} className="flex-shrink-0 mt-0.5"/>
          <span>{t('find.forProfileHint')}</span>
        </div>
      </div>

      <div className="space-y-3.5">
        <div>
          <label className="block text-[12px] text-ink-muted mb-1.5">{t('find.businessType')}</label>
          <input className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]" placeholder={t('find.businessTypeP')}/>
        </div>
        <div>
          <label className="block text-[12px] text-ink-muted mb-1.5">{t('find.location')}</label>
          <input className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]" placeholder={t('find.locationP')}/>
        </div>
        <div>
          <label className="block text-[12px] text-ink-muted mb-1.5">{t('find.contact')}</label>
          <input className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3]" placeholder={t('find.contactP')}/>
        </div>
        <div>
          <label className="block text-[12px] text-ink-muted mb-1.5">
            {t('find.amount')} <span className="text-[#3465E3]">{t('find.creditNote')}</span>
          </label>
          <div className="text-[10.5px] text-ink-soft mb-1">{t('find.amountHint')}</div>
          <input type="number" defaultValue={1} className="w-full border border-line rounded-md px-3 py-2 text-[13px] focus:outline-none focus:border-[#3465E3]"/>
        </div>
        <div>
          <label className="block text-[12px] text-ink-muted mb-1.5">{t('find.extras')}</label>
          <textarea rows={3} className="w-full border border-line rounded-md px-3 py-2 text-[13px] placeholder:text-ink-soft focus:outline-none focus:border-[#3465E3] resize-none" placeholder={t('find.extrasP')}/>
        </div>

        {/* Scheduling — recurring search runs */}
        <ScheduleConfig value={schedule} onChange={setSchedule} crmConnected={crmConnected}/>

        <button onClick={handleStart} className="w-full flex items-center justify-center gap-2 rounded-full text-white font-medium text-[13px] py-2.5 mt-1"
          style={{background:'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)'}}>
          <Icon.Search size={14}/> {schedule.frequency === 'once' ? t('find.start') : t('sched.startRecurring') || t('find.start')}
        </button>
      </div>
    </>
  );
  if (embedded) return <div>{inner}</div>;
  return (
    <div className="bg-white border border-line rounded-lg p-5 sticky top-4">
      {inner}
    </div>
  );
}

function DeineLeadsTableBody({ onRowClick, onStartRun, profiles, feedbackByProfile = {} }) {
  useLang();
  return (
    <div className="overflow-x-auto">
        <table className="w-full text-[13px]">
          <thead>
            <tr className="text-left text-[11px] uppercase tracking-[0.06em] text-ink-muted" style={{background:'#EEF2FE'}}>
              <th className="px-5 py-2.5 font-medium">{t('dash.col.profile')}</th>
              <th className="px-3 py-2.5 font-medium">{t('dash.col.query')}</th>
              <th className="px-3 py-2.5 font-medium">{t('dash.col.leads')}</th>
              <th className="px-3 py-2.5 font-medium">{t('dash.col.trained')}</th>
              <th className="px-3 py-2.5 font-medium">{t('dash.col.matchrate')}</th>
              <th className="px-3 py-2.5 font-medium">{t('dash.col.lastRun')}</th>
              <th className="px-5 py-2.5 font-medium text-right">{t('dash.action')}</th>
            </tr>
          </thead>
          <tbody>
            {profiles.map(p => {
              const fb = feedbackByProfile[p.id] || {};
              const unseenCount = (p.leads || []).filter(l => !fb[l.id] || fb[l.id] === 'neutral').length;
              const total = (p.leads || []).length;
              const rate = Math.round(p.matchRateNow * 100);
              const rateStart = Math.round(p.matchRateStart * 100);
              const delta = rate - rateStart;
              const lastRun = p.id === 'falt' ? 'vor 3 Tagen' : 'vor 9 Tagen';
              return (
                <tr key={p.id} onClick={() => onRowClick(p)} className="group border-t border-line hover:bg-[#FAFCFF] cursor-pointer">
                  <td className="px-5 py-3.5">
                    <div className="flex items-center gap-2.5">
                      <div className="w-8 h-8 rounded-md flex items-center justify-center text-[13px] font-semibold bg-[#EEF2FE] text-[#3465E3] flex-shrink-0">{p.initial}</div>
                      <div className="min-w-0">
                        <div className="text-[13.5px] font-medium text-ink truncate">{p.name}</div>
                        <div className="text-[11px] text-ink-soft">{t('cortex.activeSince')} {p.createdAt}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3.5 text-ink-muted truncate max-w-[260px]">{p.query}</td>
                  <td className="px-3 py-3.5">
                    <div className="flex items-baseline gap-1.5">
                      <span className="text-[15px] font-semibold text-ink tabular-nums">{total}</span>
                      {unseenCount > 0 && (
                        <span className="text-[10.5px] font-medium tabular-nums" style={{color:'#3465E3'}}>
                          +{unseenCount} {t('dash.newBadge')}
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-3 py-3.5 whitespace-nowrap">
                    <div className="flex items-center gap-2.5">
                      <TrainingRing rate={Math.min(1, p.feedbackCount / 400)} size={26}/>
                      <div>
                        <div className="text-[13px] text-ink tabular-nums leading-tight">{p.feedbackCount}</div>
                        <div className="text-[11px] text-ink-soft leading-tight">{p.acceptedCount}&nbsp;{t('cortex.fits')} · {p.rejectedCount}&nbsp;{t('cortex.fitsNot')}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-3.5">
                    <div className="flex items-center gap-2">
                      <div className="w-[48px] h-1.5 rounded-full bg-gray-100 overflow-hidden">
                        <div className="h-full bg-[#3465E3]" style={{width:`${rate}%`}}/>
                      </div>
                      <span className="text-[12.5px] font-medium text-ink tabular-nums">{rate}%</span>
                      {delta > 0 && <span className="text-[10.5px] text-emerald-700 font-medium">+{delta}</span>}
                    </div>
                  </td>
                  <td className="px-3 py-3.5 text-ink-muted text-[12px]">{lastRun}</td>
                  <td className="px-5 py-3.5 text-right">
                    <div className="flex items-center justify-end gap-3">
                      <button onClick={(e) => { e.stopPropagation(); if (onStartRun) onStartRun(p); }} className="text-[12px] text-ink-muted font-medium hover:text-ink inline-flex items-center gap-1">
                        <Icon.Search size={11}/> {t('dash.startRun') || 'Suchlauf'}
                      </button>
                      <button onClick={(e) => { e.stopPropagation(); onRowClick(p); }} className="text-[12px] text-[#3465E3] font-medium hover:underline inline-flex items-center gap-1">
                        {t('dash.openProfile')} <Icon.ChevRight size={11} className="arrow-shift"/>
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
    </div>
  );
}

// Hero-Strip — die erste Botschaft: "Leadscraper lernt dich kennen"
function DashboardHero({ profiles }) {
  const totalFeedbacks = profiles.reduce((s, p) => s + (p.feedbackCount || 0), 0);
  const weightedRate = profiles.reduce((s, p) => s + (p.matchRateNow || 0) * (p.feedbackCount || 0), 0) / Math.max(1, totalFeedbacks);
  const weightedStart = profiles.reduce((s, p) => s + (p.matchRateStart || 0) * (p.feedbackCount || 0), 0) / Math.max(1, totalFeedbacks);
  const avgRate = Math.round(weightedRate * 100);
  const delta = Math.round((weightedRate - weightedStart) * 100);

  return (
    <div className="rounded-lg overflow-hidden mb-5 relative"
      style={{
        background: 'linear-gradient(135deg, #0E1629 0%, #1B2547 55%, #2A3A6E 100%)',
      }}>
      {/* Subtle pattern — neuron-like dots */}
      <svg className="absolute inset-0 w-full h-full opacity-[0.08]" preserveAspectRatio="none" viewBox="0 0 400 120">
        <defs>
          <radialGradient id="heroDot" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="#fff" stopOpacity="1"/>
            <stop offset="100%" stopColor="#fff" stopOpacity="0"/>
          </radialGradient>
        </defs>
        {[[30,30],[90,70],[160,25],[220,80],[280,40],[340,85],[380,20]].map(([x,y],i) => (
          <circle key={i} cx={x} cy={y} r="20" fill="url(#heroDot)"/>
        ))}
      </svg>

      <div className="relative px-6 py-5 flex items-center justify-between gap-8">
        <div className="min-w-0">
          <div className="text-[10.5px] uppercase tracking-[0.12em] font-medium text-white/50 mb-1.5">
            {t('hero.eyebrow')}
          </div>
          <div className="text-[22px] font-semibold text-white leading-tight">
            {t('hero.title')}
          </div>
          <div className="text-[13px] text-white/60 mt-1 leading-snug max-w-[540px]">
            {t('hero.sub')}
          </div>
        </div>

        <div className="flex items-stretch gap-5 flex-shrink-0">
          <div className="text-right">
            <div className="text-[28px] font-semibold text-white tabular-nums leading-none">{totalFeedbacks}</div>
            <div className="text-[11px] text-white/60 mt-1.5">{t('hero.stat.feedbacks')}</div>
          </div>
          <div className="w-px bg-white/15"/>
          <div className="text-right">
            <div className="flex items-baseline gap-1.5 justify-end">
              <span className="text-[28px] font-semibold text-white tabular-nums leading-none">{avgRate}%</span>
              {delta > 0 && (
                <span className="text-[12px] font-medium text-emerald-300 tabular-nums">+{delta}</span>
              )}
            </div>
            <div className="text-[11px] text-white/60 mt-1.5">{t('hero.stat.matchrate')}</div>
          </div>
          <div className="w-px bg-white/15"/>
          <div className="text-right">
            <div className="text-[28px] font-semibold text-white tabular-nums leading-none">{profiles.length}</div>
            <div className="text-[11px] text-white/60 mt-1.5">{t('hero.stat.profiles')}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function ScreenDashboard({ onGoToLeads, onStartLeads, profiles, activeProfileId, setActiveProfileId, onCreateProfile, notifItems = [], notifDismissed, onNotifAct, onNotifDismiss, feedbackByProfile = {}, onOpenProfileLeads }) {
  useLang();
  const [runModalOpen, setRunModalOpen] = useState(false);
  const [runProfileId, setRunProfileId] = useState(activeProfileId);
  const inboxItems = useMemo(() => {
    return (notifItems || []).filter(n => !(notifDismissed || new Set()).has(n.id));
  }, [notifItems, notifDismissed]);
  const openRunFor = (p) => { setRunProfileId(p ? p.id : activeProfileId); setRunModalOpen(true); };
  return (
    <div data-screen-label="Dashboard" className="max-w-[1320px] mx-auto px-6 py-6 fade-in">
      {/* Hero-Strip — die erste Botschaft vor allem anderen */}
      <DashboardHero profiles={profiles}/>

      {/* Heute zu erledigen — unified action inbox */}
      {inboxItems.length > 0 && (
        <ActionInbox items={inboxItems} onAct={onNotifAct} onDismiss={onNotifDismiss}/>
      )}

      {/* Profile-Tabelle + Header-CTAs */}
      <div className="mt-5 bg-white border border-line rounded-lg overflow-hidden">
        <div className="px-5 py-4 flex items-center justify-between gap-3">
          <div className="min-w-0">
            <h2 className="text-[16px] font-semibold text-ink">{t('dash.yourProfiles')}</h2>
            <p className="text-[11.5px] text-ink-muted mt-0.5">{t('dash.yourProfilesSub')}</p>
          </div>
          <div className="flex items-center gap-2 flex-shrink-0">
            <button onClick={onCreateProfile} className="text-[12.5px] font-medium text-ink-muted border border-line rounded-md px-3 py-1.5 hover:bg-gray-50 inline-flex items-center gap-1.5 whitespace-nowrap">
              <Icon.Plus size={13}/> {t('nav.newProfile')}
            </button>
            <button onClick={() => openRunFor(null)} className="text-[12.5px] font-medium text-white rounded-md px-3 py-1.5 inline-flex items-center gap-1.5 whitespace-nowrap"
              style={{background:'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)'}}>
              <Icon.Search size={13}/> {t('dash.startRun')}
            </button>
          </div>
        </div>
        <DeineLeadsTableBody profiles={profiles} feedbackByProfile={feedbackByProfile}
          onRowClick={(p) => onOpenProfileLeads ? onOpenProfileLeads(p) : onGoToLeads()}
          onStartRun={(p) => openRunFor(p)}/>
      </div>

      {runModalOpen && (
        <RunModal profiles={profiles} activeProfileId={runProfileId} setActiveProfileId={setRunProfileId}
          onCreateProfile={onCreateProfile}
          onStart={() => { setRunModalOpen(false); if (onStartLeads) onStartLeads(); }}
          onClose={() => setRunModalOpen(false)}/>
      )}
    </div>
  );
}

function ActionInbox({ items, onAct, onDismiss }) {
  useLang();
  const [expanded, setExpanded] = React.useState(false);
  if (!items || items.length === 0) return null;

  const visible = expanded ? items : items.slice(0, 3);
  const hidden = items.length - visible.length;

  // Counts by kind for the header summary
  const reviewCount = items.filter(i => i.kind === 'review').length;
  const patternCount = items.filter(i => i.kind === 'pattern').length;
  const edgeCount = items.filter(i => i.kind === 'edge').length;
  const summaryParts = [];
  if (reviewCount) summaryParts.push(`${reviewCount} Review`);
  if (patternCount) summaryParts.push(`${patternCount} Pattern`);
  if (edgeCount) summaryParts.push(`${edgeCount} Grenzfall`);

  return (
    <div className="mt-4 bg-white border border-line rounded-xl overflow-hidden fade-in-up">
      {/* Header strip */}
      <div className="px-5 pt-4 pb-3 flex items-end justify-between">
        <div>
          <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium flex items-center gap-2">
            <span className="w-1.5 h-1.5 rounded-full bg-[#3465E3] pulse-dot"/>
            Heute zu erledigen
          </div>
          <div className="flex items-baseline gap-2 mt-1">
            <div className="text-[20px] font-semibold text-ink leading-none tabular-nums num-tick" key={items.length}>{items.length}</div>
            <div className="text-[12.5px] text-ink-muted">{summaryParts.join(' · ')}</div>
          </div>
        </div>
        {items.length > 3 && (
          <button onClick={() => setExpanded(e => !e)}
            className="text-[12px] text-ink-muted hover:text-ink font-medium">
            {expanded ? 'Weniger zeigen' : `Alle ${items.length} zeigen`}
          </button>
        )}
      </div>

      {/* Items list */}
      <div className="divide-y divide-line border-t border-line stagger">
        {visible.map((item, idx) => (
          <ActionInboxRow key={item.id} item={item} primary={idx === 0}
            onAct={() => onAct && onAct(item)}
            onDismiss={() => onDismiss && onDismiss(item.id)}/>
        ))}
      </div>

      {!expanded && hidden > 0 && (
        <button onClick={() => setExpanded(true)}
          className="w-full py-2 text-[11.5px] text-ink-soft hover:text-ink hover:bg-surface border-t border-line">
          + {hidden} weitere
        </button>
      )}
    </div>
  );
}

function ActionInboxRow({ item, primary, onAct, onDismiss }) {
  const [removing, setRemoving] = React.useState(false);
  const title = item.titleKey ? t(item.titleKey, item.bodyVars) : (item.title || '');
  const body  = item.bodyKey ? t(item.bodyKey, item.bodyVars) : (item.bodyText || item.body || '');

  // Kind → tint
  const tint = item.kind === 'review'  ? { bg: '#EEF2FE', fg: '#3465E3' }
             : item.kind === 'pattern' ? { bg: '#F4EEFE', fg: '#7B5CD9' }
             : item.kind === 'edge'    ? { bg: '#FEF6E6', fg: '#B7791F' }
             :                            { bg: '#F2F1ED', fg: '#5C5648' };

  const kindLabel = item.kind === 'review'  ? 'Review'
                  : item.kind === 'pattern' ? 'Pattern'
                  : item.kind === 'edge'    ? 'Grenzfall'
                  :                           'Hinweis';

  const handleDismiss = (e) => {
    e.stopPropagation();
    setRemoving(true);
    setTimeout(() => onDismiss(), 280);
  };

  return (
    <div onClick={onAct}
         className={`group row-hover px-5 py-3 flex items-center gap-3.5 hover:bg-surface/60 cursor-pointer ${removing ? 'swoosh-out' : ''}`}>
      <div className="w-8 h-8 rounded-md flex items-center justify-center flex-shrink-0 transition-transform duration-200 group-hover:scale-105"
           style={{ background: tint.bg, color: tint.fg }}>
        <NotifIcon kind={item.kind} size={14}/>
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-0.5">
          <span className="text-[10px] font-semibold uppercase tracking-[0.06em]" style={{ color: tint.fg }}>{kindLabel}</span>
          {item.profileShort && (
            <span className="inline-flex items-center gap-1 text-[10.5px] text-ink-soft">
              <span className="w-3 h-3 rounded-sm flex items-center justify-center text-[8.5px] font-semibold bg-gray-100 text-ink">{item.profileInitial}</span>
              <span className="truncate max-w-[140px]">{item.profileShort}</span>
            </span>
          )}
        </div>
        <div className={`text-[13px] truncate ${primary ? 'font-semibold text-ink' : 'font-medium text-ink'}`}>{title}</div>
        {body && <div className="text-[11.5px] text-ink-muted mt-0.5 truncate">{body}</div>}
      </div>
      <div className="flex items-center gap-0.5 flex-shrink-0">
        <button onClick={handleDismiss}
          className="w-7 h-7 rounded-md flex items-center justify-center text-ink-soft hover:text-ink hover:bg-surface opacity-0 group-hover:opacity-100"
          title="Ausblenden">
          <Icon.X size={12}/>
        </button>
        <div className="row-arrow w-7 h-7 rounded-md flex items-center justify-center text-ink-soft group-hover:text-ink group-hover:bg-white group-hover:shadow-sm">
          <Icon.ChevRight size={14}/>
        </div>
      </div>
    </div>
  );
}

function RunModal({ profiles, activeProfileId, setActiveProfileId, onCreateProfile, onStart, onClose }) {
  useLang();
  return (
    <div className="fixed inset-0 z-50 bg-white fade-in flex flex-col" onClick={onClose}>
      {/* Soft backdrop accent */}
      <div className="absolute inset-0 pointer-events-none"
           style={{background:'radial-gradient(1200px 600px at 50% -10%, #EEF2FE 0%, transparent 60%)'}}/>
      <div onClick={(e) => e.stopPropagation()} className="relative flex flex-col h-full">
        {/* Top bar */}
        <div className="flex-shrink-0 px-8 py-4 border-b border-line flex items-center justify-between bg-white/80 backdrop-blur-sm">
          <div className="flex items-center gap-3">
            <div className="w-7 h-7 rounded-md bg-ink text-white flex items-center justify-center flex-shrink-0">
              <Icon.Search size={13}/>
            </div>
            <div>
              <div className="text-[14px] font-semibold text-ink leading-tight">{t('find.title')}</div>
              <div className="text-[11.5px] text-ink-muted leading-tight mt-0.5">Neuen Suchlauf konfigurieren & starten</div>
            </div>
          </div>
          <button onClick={onClose} className="inline-flex items-center gap-1.5 h-[32px] px-3 rounded-md text-[12.5px] text-ink-muted hover:bg-gray-100 hover:text-ink transition-colors">
            <Icon.X size={14}/> {t('dash.close')}
          </button>
        </div>
        {/* Body */}
        <div className="flex-1 overflow-y-auto">
          <div className="max-w-[780px] mx-auto px-8 py-10">
            <NewLeadsForm onStart={onStart} profiles={profiles} activeProfileId={activeProfileId}
              setActiveProfileId={setActiveProfileId} onCreateProfile={onCreateProfile} embedded/>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenDashboard });
