// Cortex screen — was Leadscraper über dich gelernt hat ----------------
function EditMemoryModal({ open, item, onClose, onSave }) {
  useLang();
  const [draft, setDraft] = useState('');
  useEffect(() => { if (item) setDraft(item.text); }, [item]);
  if (!item) return null;
  return (
    <Modal open={open} onClose={onClose} width="max-w-md">
      <div className="p-5">
        <div className="flex items-start justify-between">
          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('mem.editKicker')}</div>
            <div className="text-[15px] font-semibold text-ink mt-1">{t('mem.editTitle')}</div>
          </div>
          <button onClick={onClose} className="text-ink-muted hover:text-ink"><Icon.X/></button>
        </div>
        <textarea value={draft} onChange={e => setDraft(e.target.value)} rows={3}
          className="mt-4 w-full border border-line rounded-md p-3 text-[14px] text-ink resize-none focus:outline-none focus:border-brand-500"/>
        <p className="mt-2 text-[12px] text-ink-muted">{t('mem.editHint')}</p>
        <div className="mt-4 flex justify-end gap-2">
          <Button variant="ghost" onClick={onClose}>{t('mem.cancel')}</Button>
          <Button variant="default" onClick={() => onSave(draft)}>{t('mem.save')}</Button>
        </div>
      </div>
    </Modal>
  );
}

function MemoryCard({ item, onConfirm, onEdit, onRemove }) {
  const tier = item.strength;
  const pillBg = tier === 'strong' ? '#0F1A2D' : tier === 'medium' ? '#3F4B5F' : '#7A8599';
  return (
    <div className="group bg-white border border-line rounded-lg p-5 hover:border-[#C7D3E6] transition-colors">
      <div className="flex items-start justify-between gap-6">
        <div className="flex-1 min-w-0">
          <p className="text-[15.5px] leading-[1.55] text-ink">{item.text}</p>
          <div className="flex items-center gap-3 mt-2.5 text-[12px]">
            {item.confirmed && (
              <span className="inline-flex items-center gap-1 text-emerald-700"><Icon.Check size={12}/> {t('cortex.confirmed')}</span>
            )}
            {item.uncertain && (
              <span className="inline-flex items-center gap-1 text-amber-700"><Icon.Info size={12}/> {t('cortex.uncertain')}</span>
            )}
            <span className="text-ink-muted">{item.evidence}</span>
          </div>
        </div>
        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0">
          {!item.confirmed && (
            <button onClick={onConfirm} title={t('cortex.confirm')} className="h-8 w-8 flex items-center justify-center rounded-md text-emerald-700 hover:bg-emerald-50"><Icon.Check size={14}/></button>
          )}
          <button onClick={onEdit} title={t('cortex.correct')} className="h-8 w-8 flex items-center justify-center rounded-md text-ink-muted hover:bg-gray-50 hover:text-ink"><Icon.Edit size={14}/></button>
          <button onClick={onRemove} title={t('cortex.forget')} className="h-8 w-8 flex items-center justify-center rounded-md text-red-700 hover:bg-red-50"><Icon.Trash size={14}/></button>
        </div>
      </div>
    </div>
  );
}

function TierHeader({ label, count, tone }) {
  const dot = tone === 'strong' ? 'bg-[#0F1A2D]' : tone === 'medium' ? 'bg-[#6B7A93]' : 'bg-[#B6C0D2]';
  return (
    <div className="flex items-center gap-2.5 mb-3 mt-7 first:mt-0">
      <span className={`h-2 w-2 rounded-full ${dot}`}/>
      <h3 className="text-[13px] font-semibold text-ink uppercase tracking-[0.08em]">{label}</h3>
      <span className="text-[12px] text-ink-soft">· {count}</span>
      <div className="flex-1 h-px bg-line ml-2"/>
    </div>
  );
}

function ScreenMemory({ profile, coldStart, memory, setMemory, onGoToResults, toast, onConfirmPattern, onRejectPattern }) {
  useLang();
  const [editing, setEditing] = useState(null);
  const [dismissedPatterns, setDismissedPatterns] = useState(new Set());

  // Pending patterns: unconfirmed, not uncertain, not dismissed
  const pendingPatterns = memory.filter(m => !m.confirmed && !m.uncertain && !dismissedPatterns.has(m.id));

  const now = profile.matchRateNow;
  const delta = now - profile.matchRateStart;

  const confirm = (item) => {
    setMemory(memory.map(m => m.id === item.id ? { ...m, confirmed: true, uncertain: false } : m));
    toast.push(t('mem.toast.confirmed'), 'positive');
  };
  const remove = (item) => {
    setMemory(memory.filter(m => m.id !== item.id));
    toast.push(t('mem.toast.forgotten'), 'negative');
  };
  const save = (text) => {
    setMemory(memory.map(m => m.id === editing.id ? { ...m, text, confirmed: true } : m));
    setEditing(null);
    toast.push(t('mem.toast.corrected'), 'positive');
  };

  // --- Cold-start variant -----------------------------------------
  if (coldStart) {
    return (
      <div data-screen-label={t('mem.screenLabelEmpty')} className="max-w-[960px] mx-auto px-6 py-14">
        <div className="text-[12px] text-ink-soft uppercase tracking-[0.08em] font-medium">{t('cortex.title')} · {profile.short}</div>
        <h1 className="text-[32px] font-semibold text-ink mt-1 leading-[1.1] tracking-tight max-w-[640px]">{t('cortex.heroEmpty')}</h1>
        <p className="text-[14.5px] text-ink-muted mt-3 max-w-[640px] leading-[1.6]">{t('cortex.heroEmptySub')}</p>

        <div className="mt-9 grid grid-cols-3 gap-4">
          {[
            { n: 1, key: 'step1' },
            { n: 2, key: 'step2' },
            { n: 3, key: 'step3' },
          ].map(s => (
            <div key={s.n} className="border border-line rounded-lg p-5 bg-white">
              <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('cortex.step')} {s.n}</div>
              <div className="text-[15px] font-semibold text-ink mt-1">{t(`cortex.${s.key}`)}</div>
              <p className="text-[13px] text-ink-muted mt-2 leading-[1.6]">{t(`cortex.${s.key}d`)}</p>
            </div>
          ))}
        </div>

        <div className="mt-9 flex items-center gap-3">
          <Button variant="brand" onClick={onGoToResults}>{t('cortex.ctaRate')}</Button>
          <span className="text-[12px] text-ink-soft">{t('cortex.activeSince')} {profile.createdAt} · 0 {t('cortex.feedbacks')}</span>
        </div>
      </div>
    );
  }

  // --- Learned variant -----------------------------------------
  const grouped = {
    strong: memory.filter(m => m.strength === 'strong'),
    medium: memory.filter(m => m.strength === 'medium'),
    weak:   memory.filter(m => m.strength === 'weak'),
  };

  return (
    <div data-screen-label={t('mem.screenLabel')} className="max-w-[1100px] mx-auto px-6 py-10">
      {/* Hero: a single clear statement */}
      <div className="text-[12px] text-ink-soft uppercase tracking-[0.08em] font-medium">{t('cortex.title')} · {profile.short}</div>
      <h1 className="text-[32px] font-semibold text-ink mt-1 leading-[1.1] tracking-tight max-w-[820px]">
        {t('cortex.hero', { n: profile.feedbackCount })}
      </h1>
      <p className="text-[14.5px] text-ink-muted mt-3 max-w-[720px] leading-[1.6]">
        {t('cortex.heroSub')}
      </p>

      {/* Compact stats strip — no more three heavy cards */}
      <div className="mt-8 bg-white border border-line rounded-lg overflow-hidden">
        <div className="grid grid-cols-[1.8fr_1fr_1fr] divide-x divide-line">
          <div className="p-5">
            <div className="flex items-baseline justify-between">
              <div>
                <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('cortex.matchRate')}</div>
                <div className="flex items-baseline gap-2 mt-1">
                  <div className="text-[28px] font-semibold text-ink leading-none tracking-tight">{Math.round(now*100)}&thinsp;%</div>
                  <div className="text-[12.5px] text-emerald-700 font-medium">+{Math.round(delta*100)}&thinsp;% {t('cortex.sinceStart')}</div>
                </div>
              </div>
            </div>
            <div className="mt-3">
              <Sparkline values={profile.matchHistory} width={560} height={72}/>
            </div>
            <div className="flex justify-between text-[10.5px] text-ink-soft mt-1.5">
              <span>{profile.createdAt}</span>
              <span>{t('mem.today')}</span>
            </div>
          </div>
          <div className="p-5">
            <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('cortex.feedbacks')}</div>
            <div className="text-[28px] font-semibold text-ink mt-1 leading-none tracking-tight">{profile.feedbackCount}</div>
            <div className="text-[12px] text-ink-muted mt-1">{profile.acceptedCount} {t('cortex.fits')} · {profile.rejectedCount} {t('cortex.fitsNot')}</div>
            <div className="mt-4">
              <BarSeries values={profile.feedbackHistory} width={220} height={36}/>
              <div className="text-[10.5px] text-ink-soft mt-1">{t('cortex.perWeek')}</div>
            </div>
          </div>
          <div className="p-5">
            <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('cortex.patterns')}</div>
            <div className="text-[28px] font-semibold text-ink mt-1 leading-none tracking-tight">{memory.length}</div>
            <div className="text-[12px] text-ink-muted mt-1">
              {grouped.strong.length} {t('cortex.strong')} · {grouped.medium.length} {t('cortex.medium')} · {grouped.weak.length} {t('cortex.weak')}
            </div>
          </div>
        </div>
      </div>

      {/* Runs — query history per profile */}
      <RunsHistory runs={profile.runs || []} profile={profile} toast={toast}/>

      {/* ROI-Mini — collapsible potential snapshot */}
      <RoiMini feedbackCount={profile.feedbackCount} matchRate={profile.matchRateNow}/>

      {/* Learned facts — grouped, clean, no overloading */}
      <div className="mt-12">
        {pendingPatterns.length > 0 && (
          <div className="mb-8">
            <div className="flex items-center gap-2 mb-3">
              <Icon.Brain size={16} className="text-[#6B5ED6]"/>
              <h2 className="text-[16px] font-semibold text-ink tracking-tight">{t('cortex.patternsPending')}</h2>
              <span className="text-[11.5px] text-ink-muted">· {pendingPatterns.length}</span>
            </div>
            <div className="space-y-3">
              {pendingPatterns.map(p => (
                <PatternConfirmCard
                  key={p.id}
                  pattern={p}
                  onConfirm={(id, why) => {
                    if (onConfirmPattern) onConfirmPattern(id, why);
                    else { setMemory(memory.map(m => m.id===id?{...m,confirmed:true}:m)); toast.push(t('notif.pattern.confirmedLabel'),'positive'); }
                  }}
                  onReject={(id, why) => {
                    if (onRejectPattern) onRejectPattern(id, why);
                    else { setMemory(memory.filter(m => m.id!==id)); toast.push(t('notif.pattern.rejectedLabel'),'default'); }
                  }}
                  onDismiss={() => setDismissedPatterns(s => new Set([...s, p.id]))}/>
              ))}
            </div>
          </div>
        )}

        <div className="flex items-end justify-between">
          <h2 className="text-[22px] font-semibold text-ink tracking-tight">{t('cortex.learned')}</h2>
          <div className="text-[12px] text-ink-soft">{t('cortex.plain')}</div>
        </div>

        {grouped.strong.length > 0 && (
          <>
            <TierHeader label={t('cortex.tierStrong')} count={`${grouped.strong.length} ${t('cortex.strongNote')}`} tone="strong"/>
            <div className="space-y-2">
              {grouped.strong.map(m => <MemoryCard key={m.id} item={m} onConfirm={() => confirm(m)} onEdit={() => setEditing(m)} onRemove={() => remove(m)}/>)}
            </div>
          </>
        )}

        {grouped.medium.length > 0 && (
          <>
            <TierHeader label={t('cortex.tierMedium')} count={`${grouped.medium.length} · ${t('cortex.mediumNote')}`} tone="medium"/>
            <div className="space-y-2">
              {grouped.medium.map(m => <MemoryCard key={m.id} item={m} onConfirm={() => confirm(m)} onEdit={() => setEditing(m)} onRemove={() => remove(m)}/>)}
            </div>
          </>
        )}

        {grouped.weak.length > 0 && (
          <>
            <TierHeader label={t('cortex.tierWeak')} count={`${grouped.weak.length} · ${t('cortex.weakNote')}`} tone="weak"/>
            <div className="space-y-2">
              {grouped.weak.map(m => <MemoryCard key={m.id} item={m} onConfirm={() => confirm(m)} onEdit={() => setEditing(m)} onRemove={() => remove(m)}/>)}
            </div>
          </>
        )}
      </div>

      <div className="hair mt-10 pt-5 text-[12.5px] text-ink-muted leading-relaxed max-w-[780px]">
        {t('cortex.footer')}
      </div>

      <EditMemoryModal open={!!editing} item={editing} onClose={() => setEditing(null)} onSave={save}/>
    </div>
  );
}

function RunsHistory({ runs, profile, toast }) {
  useLang();
  const [repeatRun, setRepeatRun] = useState(null);
  if (!runs || runs.length === 0) return null;
  return (
    <div className="mt-10">
      <div className="flex items-end justify-between mb-3">
        <div>
          <h2 className="text-[18px] font-semibold text-ink tracking-tight">{t('cortex.runs.title')}</h2>
          <p className="text-[12px] text-ink-muted mt-0.5">{t('cortex.runs.sub')}</p>
        </div>
        <span className="text-[11px] text-ink-soft tabular-nums">{runs.length} {t('cortex.runs.count')}</span>
      </div>
      <div className="bg-white border border-line rounded-lg overflow-hidden">
        <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('cortex.runs.col.date')}</th>
              <th className="px-3 py-2.5 font-medium">{t('cortex.runs.col.params')}</th>
              <th className="px-3 py-2.5 font-medium text-right">{t('cortex.runs.col.leads')}</th>
              <th className="px-3 py-2.5 font-medium text-right">{t('cortex.runs.col.matchrate')}</th>
              <th className="px-5 py-2.5 font-medium text-right">{t('cortex.runs.col.action')}</th>
            </tr>
          </thead>
          <tbody>
            {runs.slice().reverse().map(r => (
              <tr key={r.id} className="border-t border-line hover:bg-[#FAFCFF] transition-colors">
                <td className="px-5 py-3.5 whitespace-nowrap">
                  <div className="text-[13px] text-ink">{r.date}</div>
                  <div className="text-[11px] text-ink-soft">{r.dateRelative}</div>
                </td>
                <td className="px-3 py-3.5">
                  <div className="text-[13px] text-ink truncate max-w-[380px]">{r.businessType} · {r.location}</div>
                  <div className="text-[11px] text-ink-soft truncate max-w-[380px]">
                    {r.contact}{r.extras ? ` · ${r.extras}` : ''}
                  </div>
                </td>
                <td className="px-3 py-3.5 text-right">
                  <span className="text-[14px] font-semibold text-ink tabular-nums">{r.leadCount}</span>
                </td>
                <td className="px-3 py-3.5 text-right">
                  <div className="inline-flex items-center gap-1.5">
                    <div className="w-[40px] h-1.5 rounded-full bg-gray-100 overflow-hidden">
                      <div className="h-full bg-[#3465E3]" style={{width:`${Math.round(r.matchRateAtRun*100)}%`}}/>
                    </div>
                    <span className="text-[12px] text-ink tabular-nums">{Math.round(r.matchRateAtRun*100)}%</span>
                  </div>
                </td>
                <td className="px-5 py-3.5 text-right">
                  <button
                    onClick={() => setRepeatRun(r)}
                    className="text-[12px] text-[#3465E3] font-medium hover:underline inline-flex items-center gap-1">
                    <Icon.Search size={11}/> {t('cortex.runs.repeat')}
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {repeatRun && (
        <RepeatRunModal
          run={repeatRun}
          profile={profile}
          onClose={() => setRepeatRun(null)}
          onStart={(count) => {
            setRepeatRun(null);
            if (toast) toast.push(t('repeat.toast'), 'positive');
          }}/>
      )}
    </div>
  );
}

function RepeatRunModal({ run, profile, onClose, onStart }) {
  useLang();
  const [count, setCount] = useState(run.leadCount || 40);
  const matchRate = profile?.matchRateNow || 0.5;
  const expectedMatches = Math.round(count * matchRate);
  const runtimeMin = Math.max(1, Math.round(count * 0.08));
  const credits = count * 2;
  const presets = [25, 50, 100, 200];
  const fmt = (n) => new Intl.NumberFormat('de-DE').format(n);

  // Close on ESC
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 fade-in"
         style={{background: 'rgba(15,23,42,0.55)', backdropFilter: 'blur(6px)'}}
         onClick={onClose}>
      <div
        onClick={(e) => e.stopPropagation()}
        className="bg-white rounded-2xl w-full max-w-[560px] overflow-hidden"
        style={{boxShadow:'0 32px 80px -20px rgba(15,23,42,0.35)'}}>
        {/* Header */}
        <div className="relative px-6 pt-6 pb-5 text-white"
             style={{background:'linear-gradient(135deg, #3465E3 0%, #6D4FE6 55%, #8B5CF6 100%)'}}>
          <button onClick={onClose}
                  className="absolute top-4 right-4 w-8 h-8 rounded-md hover:bg-white/15 flex items-center justify-center text-white/85 hover:text-white transition-colors">
            <Icon.X size={16}/>
          </button>
          <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.1em] text-white/80 font-medium">
            <Icon.Search size={12}/> {profile?.short || t('mem.profile')}
          </div>
          <h2 className="text-[22px] font-semibold mt-1.5 leading-tight tracking-tight">{t('repeat.title')}</h2>
          <p className="text-[13px] text-white/85 mt-1 leading-snug max-w-[420px]">{t('repeat.sub')}</p>
        </div>

        {/* Body */}
        <div className="p-6 space-y-6">
          {/* Params block — readonly summary */}
          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium mb-2">{t('repeat.paramsLabel')}</div>
            <div className="rounded-lg border border-line bg-[#FAFCFF] px-4 py-2 divide-y divide-[#E8ECF4]">
              <ParamRow label={t('mem.param.sector')} value={run.businessType}/>
              <ParamRow label={t('mem.param.location')} value={run.location}/>
              <ParamRow label={t('mem.param.contact')} value={run.contact}/>
              {run.extras && <ParamRow label={t('mem.param.extras')} value={run.extras}/>}
            </div>
          </div>

          {/* Amount selector */}
          <div>
            <div className="flex items-end justify-between mb-2">
              <div>
                <div className="text-[13px] font-medium text-ink">{t('repeat.amountLabel')}</div>
                <div className="text-[11px] text-ink-soft mt-0.5">{t('repeat.amountHint')}</div>
              </div>
              <div className="text-right">
                <div className="text-[28px] font-semibold text-ink leading-none tabular-nums">{count}</div>
                <div className="text-[10.5px] text-ink-soft uppercase tracking-[0.08em]">{t('mem.param.leads')}</div>
              </div>
            </div>

            {/* Slider */}
            <div className="mt-3">
              <input
                type="range"
                min={5}
                max={250}
                step={5}
                value={count}
                onChange={(e) => setCount(Number(e.target.value))}
                className="repeat-slider w-full"
                style={{
                  background: `linear-gradient(to right, #3465E3 0%, #8B5CF6 ${(count/250)*100}%, #E5E7EB ${(count/250)*100}%, #E5E7EB 100%)`
                }}/>
              <div className="flex justify-between text-[10.5px] text-ink-soft mt-1.5 tabular-nums">
                <span>5</span>
                <span>125</span>
                <span>250</span>
              </div>
            </div>

            {/* Presets */}
            <div className="mt-3 flex items-center gap-1.5">
              <span className="text-[11px] text-ink-soft mr-1">{t('repeat.preset')}:</span>
              {presets.map(p => (
                <button key={p}
                        onClick={() => setCount(p)}
                        className={`px-2.5 py-1 rounded-md text-[12px] font-medium transition-colors ${
                          count === p
                            ? 'bg-[#3465E3] text-white'
                            : 'bg-white text-ink-muted border border-line hover:bg-gray-50'
                        }`}>
                  {p}
                </button>
              ))}
            </div>
          </div>

          {/* Prediction tile */}
          <div className="rounded-lg p-4"
               style={{background:'linear-gradient(135deg, #F4F7FD 0%, #EFECFB 100%)', border:'1px solid #E4D9F7'}}>
            <div className="flex items-center gap-1.5 text-[11px] uppercase tracking-[0.08em] text-[#6B5ED6] font-medium mb-2.5">
              <Icon.Sparkle size={11}/> {t('repeat.prediction.title')}
            </div>
            <div className="grid grid-cols-3 gap-3">
              <PredictTile
                big={expectedMatches}
                label={t('repeat.prediction.matches')}
                sub={`${Math.round(matchRate*100)} % · ${t('repeat.prediction.basedOn')}`}
                accent/>
              <PredictTile
                big={`~${runtimeMin} min`}
                label={t('repeat.prediction.time')}/>
              <PredictTile
                big={fmt(credits)}
                label={t('repeat.prediction.credits')}/>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-line bg-white">
          <button onClick={onClose}
                  className="px-4 py-2 rounded-md text-[13px] font-medium text-ink-muted hover:bg-gray-50 transition-colors">
            {t('repeat.cancel')}
          </button>
          <button onClick={() => onStart(count)}
                  className="px-5 py-2 rounded-md text-[13px] font-medium text-white inline-flex items-center gap-2 transition-transform hover:scale-[1.02] whitespace-nowrap"
                  style={{background:'linear-gradient(107.45deg, #1479FC 18.94%, #B880FC 123.42%)', boxShadow:'0 6px 16px -4px rgba(20,121,252,0.4)'}}>
            <Icon.Search size={13}/> {t('repeat.start')} <span className="opacity-70">·</span> <span className="tabular-nums">{count}</span>
          </button>
        </div>
      </div>
    </div>
  );
}

function ParamRow({ label, value }) {
  return (
    <div className="flex items-start gap-3 text-[12.5px] py-1.5">
      <div className="text-ink-soft w-[110px] flex-shrink-0 leading-[1.5] pt-px">{label}</div>
      <div className="text-ink font-medium leading-[1.5] flex-1 min-w-0">{value}</div>
    </div>
  );
}

function PredictTile({ big, label, sub, accent }) {
  return (
    <div>
      <div className={`text-[22px] font-semibold tabular-nums leading-none ${accent ? 'text-[#6B5ED6]' : 'text-ink'}`}>{big}</div>
      <div className="text-[11px] text-ink-muted mt-1 leading-tight">{label}</div>
      {sub && <div className="text-[10px] text-ink-soft mt-0.5 leading-tight">{sub}</div>}
    </div>
  );
}

function RoiMini({ feedbackCount = 0, matchRate = 0 }) {
  useLang();
  const [open, setOpen] = useState(false);
  const [leads, setLeads] = useState(100);
  const [winRate, setWinRate] = useState(3);
  const [avgOrder, setAvgOrder] = useState(10000);
  const expectedFits = Math.round(leads * matchRate);
  const newCustomers = Math.round(expectedFits * (winRate / 100));
  const revenue = newCustomers * avgOrder;
  const fmt = (n) => new Intl.NumberFormat('de-DE').format(n);
  return (
    <div className="mt-8 border border-line rounded-lg bg-white overflow-hidden">
      <button onClick={() => setOpen(o => !o)} className="w-full flex items-center justify-between px-5 py-3.5 hover:bg-[#FAFCFF] transition-colors">
        <div className="flex items-center gap-2.5">
          <Icon.Sparkle size={14} className="text-[#B880FC]"/>
          <div className="text-left">
            <div className="text-[13.5px] font-medium text-ink">{t('cortex.roi.title')}</div>
            <div className="text-[11.5px] text-ink-muted">{t('cortex.roi.sub')}</div>
          </div>
        </div>
        <Icon.ChevDown size={14} className={`text-ink-muted transition-transform ${open ? 'rotate-180' : ''}`}/>
      </button>
      {open && (
        <div className="px-5 pb-5 pt-2 border-t border-line fade-in">
          <div className="grid grid-cols-3 gap-4 mb-4">
            <div>
              <label className="block text-[11px] uppercase tracking-[0.06em] text-ink-soft font-medium mb-1">{t('cortex.roi.leads')}</label>
              <input type="number" value={leads} onChange={(e) => setLeads(parseInt(e.target.value)||0)}
                className="w-full border border-line rounded-md px-2.5 py-1.5 text-[13px] tabular-nums focus:outline-none focus:border-[#3465E3]"/>
            </div>
            <div>
              <label className="block text-[11px] uppercase tracking-[0.06em] text-ink-soft font-medium mb-1">{t('cortex.roi.winRate')}</label>
              <div className="relative">
                <input type="number" value={winRate} onChange={(e) => setWinRate(parseFloat(e.target.value)||0)}
                  className="w-full border border-line rounded-md px-2.5 py-1.5 pr-7 text-[13px] tabular-nums focus:outline-none focus:border-[#3465E3]"/>
                <span className="absolute right-2.5 top-1/2 -translate-y-1/2 text-[12px] text-ink-soft">%</span>
              </div>
            </div>
            <div>
              <label className="block text-[11px] uppercase tracking-[0.06em] text-ink-soft font-medium mb-1">{t('cortex.roi.avgOrder')}</label>
              <div className="relative">
                <input type="number" value={avgOrder} onChange={(e) => setAvgOrder(parseInt(e.target.value)||0)}
                  className="w-full border border-line rounded-md px-2.5 py-1.5 pr-7 text-[13px] tabular-nums focus:outline-none focus:border-[#3465E3]"/>
                <span className="absolute right-2.5 top-1/2 -translate-y-1/2 text-[12px] text-ink-soft">€</span>
              </div>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4 pt-4 border-t border-line">
            <div>
              <div className="text-[11px] uppercase tracking-[0.06em] text-ink-soft font-medium">{t('cortex.roi.expectedFits')}</div>
              <div className="text-[22px] font-semibold text-ink tabular-nums mt-0.5 leading-tight">{fmt(expectedFits)}</div>
              <div className="text-[11px] text-ink-muted">{Math.round(matchRate*100)}% · {t('cortex.roi.viaRate')}</div>
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-[0.06em] text-ink-soft font-medium">{t('cortex.roi.newCustomers')}</div>
              <div className="text-[22px] font-semibold text-ink tabular-nums mt-0.5 leading-tight">{fmt(newCustomers)}</div>
              <div className="text-[11px] text-ink-muted">{winRate}% {t('cortex.roi.winLabel')}</div>
            </div>
            <div>
              <div className="text-[11px] uppercase tracking-[0.06em] text-ink-soft font-medium">{t('cortex.roi.revenue')}</div>
              <div className="text-[22px] font-semibold text-emerald-700 tabular-nums mt-0.5 leading-tight">{fmt(revenue)}&thinsp;€</div>
              <div className="text-[11px] text-ink-muted">{t('cortex.roi.revenueSub')}</div>
            </div>
          </div>
          <div className="text-[11px] text-ink-soft mt-4 leading-snug">{t('cortex.roi.disclaimer')}</div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ScreenMemory });