// Search Results screen — the heart of the product -----------------------
function LeadCard({ lead, profile, state, onAccept, onReject, onOpen, density }) {
  useLang();
  // state: 'neutral' | 'accepted' | 'rejected'
  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);

  return (
    <div className={`fade-in bg-white border rounded-[12px] transition-all ${
      state === 'accepted' ? 'border-emerald-200 bg-emerald-50/30' :
      state === 'rejected' ? 'border-line opacity-55' :
      rejectOpen ? 'border-ink/30' :
      'border-[#EAF0F9] hover:border-brand-500/40'
    } ${density === 'compact' ? 'p-4' : 'p-5'}`}>
      <div className="flex items-start gap-4">
        <div className="flex-1 min-w-0">
          {/* Header row */}
          <div className="flex items-center gap-2 mb-1">
            {lead.isNew && <span className="text-[10px] uppercase tracking-[0.08em] font-semibold text-brand-500 bg-brand-50 px-1.5 py-0.5 rounded">{t('res.new')}</span>}
            <button onClick={onOpen} className="text-[17px] font-semibold text-ink hover:text-brand-500 truncate text-left leading-tight">
              {lead.company}
            </button>
          </div>
          <div className="text-[13px] text-ink-muted flex flex-wrap gap-x-2">
            <span>{lead.sector}</span>
            <span className="text-ink-soft">·</span>
            <span>{lead.city}</span>
            <span className="text-ink-soft">·</span>
            <span>{lead.size}</span>
            <span className="text-ink-soft">·</span>
            <span>{lead.founded}</span>
          </div>

          {/* Reasoning — fließender Satz, ruhig, nicht bunt */}
          <div className="mt-3 reason-rail">
            <p className="text-[14px] leading-[1.55] text-ink">{lead.reason}</p>
            {lead.uncertainty && (
              <p className="text-[12.5px] leading-snug text-ink-muted mt-1.5 italic">
                {t('res.uncertainty', { score: lead.score, text: lead.uncertainty })}
              </p>
            )}
          </div>

          {/* Referenced memory, subtle */}
          {referenced.length > 0 && (
            <div className="mt-2.5 flex flex-wrap gap-x-4 gap-y-1">
              {referenced.map(m => (
                <span key={m.id} className="text-[12px] text-ink-soft inline-flex items-center gap-1.5">
                  <span className={`h-1 w-1 rounded-full ${m.strength==='strong'?'bg-ink':'bg-ink/40'}`}/>
                  {t('res.fromMem', { text: m.text.slice(0, 62) + (m.text.length>62?'…':'') })}
                </span>
              ))}
            </div>
          )}
        </div>

        {/* Feedback block — central, not a side-afterthought */}
        <div className="flex flex-col items-stretch gap-2 pl-4 border-l border-line" style={{minWidth: 172}}>
          {state === 'neutral' && !rejectOpen && (
            <>
              <Button onClick={onAccept} variant="outline" className="!border-emerald-300 !text-emerald-800 hover:!bg-emerald-50">
                <Icon.Check size={15}/> {t('res.fit')}
              </Button>
              <Button onClick={() => setRejectOpen(true)} variant="outline" className="!border-line !text-ink-muted hover:!bg-gray-50">
                <Icon.X size={15}/> {t('res.notFit')}
              </Button>
              <button onClick={onOpen} className="text-[12px] text-ink-muted hover:text-ink text-center pt-0.5">{t('res.openDetails')}</button>
            </>
          )}
          {state === 'neutral' && rejectOpen && (
            <div className="text-center">
              <div className="text-[12px] text-ink-muted leading-snug">{t('res.pickReason')}</div>
            </div>
          )}
          {state === 'accepted' && (
            <div className="text-center">
              <div className="inline-flex items-center gap-1.5 text-[13px] font-medium text-emerald-700"><Icon.Check size={14}/> {t('res.fit')}</div>
              <div className="text-[11px] text-ink-muted mt-1 leading-snug">{t('res.acceptedNote')}</div>
            </div>
          )}
          {state === 'rejected' && (
            <div className="text-center">
              <div className="inline-flex items-center gap-1.5 text-[13px] font-medium text-ink-muted"><Icon.X size={14}/> {t('res.notFit')}</div>
              <div className="text-[11px] text-ink-muted mt-1 leading-snug">{t('res.rejectedNote')}</div>
            </div>
          )}
        </div>
      </div>

      {/* Inline-Expand: Grund-Auswahl direkt in der Karte (statt Modal) */}
      {rejectOpen && state === 'neutral' && (
        <div className="mt-4 pt-4 border-t border-dashed border-line fade-in">
          <div className="flex items-center justify-between mb-2.5">
            <div className="text-[12px] uppercase tracking-[0.08em] font-medium text-ink-soft">
              {t('res.whyNotTitle')}
            </div>
            <button
              onClick={() => setRejectOpen(false)}
              className="text-[12px] text-ink-muted hover:text-ink inline-flex items-center gap-1"
            >
              <Icon.X size={12}/> {t('res.cancel')}
            </button>
          </div>
          <div className="flex flex-wrap gap-1.5">
            {profile.reasons.map(r => (
              <button
                key={r}
                onClick={() => { onReject(r); setRejectOpen(false); }}
                className="px-3 py-1.5 rounded-full border border-line bg-white text-[13px] text-ink hover:border-ink hover:bg-ink hover:text-white transition-colors"
              >
                {r}
              </button>
            ))}
          </div>
          <p className="text-[11.5px] text-ink-soft mt-2.5 leading-snug">
            {t('res.reasonHint')}
          </p>
        </div>
      )}
    </div>
  );
}

function ScreenResults({ profile, onOpenLead, density, setDensity, feedback, setFeedback, toast }) {
  useLang();
  const accept = (lead) => {
    setFeedback({ ...feedback, [lead.id]: 'accepted' });
    toast.push(t('res.toast.accepted', { company: lead.company }), 'positive');
  };
  const reject = (lead, reason) => {
    setFeedback({ ...feedback, [lead.id]: 'rejected' });
    toast.push(t('res.toast.rejected', { reason }), 'negative');
  };

  const accepted = Object.values(feedback).filter(s => s === 'accepted').length;
  const rejected = Object.values(feedback).filter(s => s === 'rejected').length;

  return (
    <div className="max-w-[1320px] mx-auto px-6 py-8">
      {/* Title strip */}
      <div className="flex items-end justify-between gap-6 mb-6">
        <div>
          <div className="text-[12px] text-ink-soft uppercase tracking-[0.08em] font-medium">{t('res.breadcrumb', { profile: profile.short })}</div>
          <h1 className="text-[24px] font-semibold text-ink leading-tight mt-0.5">{t('res.title', { profile: profile.short })}</h1>
          <p className="text-[13.5px] text-ink-muted mt-1 max-w-[820px]">
            {t('res.summary', { count: profile.leads.length })}
          </p>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <div className="flex rounded-md border border-line overflow-hidden text-[12px]">
            <button onClick={() => setDensity('comfortable')} className={`px-2.5 py-1.5 ${density==='comfortable'?'bg-ink text-white':'text-ink-muted hover:bg-gray-50'}`}>{t('res.density.comfortable')}</button>
            <button onClick={() => setDensity('compact')} className={`px-2.5 py-1.5 border-l border-line ${density==='compact'?'bg-ink text-white':'text-ink-muted hover:bg-gray-50'}`}>{t('res.density.compact')}</button>
          </div>
          <Button variant="outline"><Icon.Filter size={14}/> {t('res.filter')}</Button>
        </div>
      </div>

      <div className="grid grid-cols-[260px_1fr] gap-8">
        {/* Filter sidebar — minimal, feels like the existing app */}
        <aside className="space-y-5">
          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] font-medium text-ink-soft mb-2">{t('res.fb.status')}</div>
            <div className="bg-white border border-line rounded-lg overflow-hidden text-[13px]">
              {[
                { label: t('res.fb.all'), count: profile.leads.length },
                { label: t('res.fb.new'), count: profile.leads.filter(l => l.isNew).length },
                { label: t('res.fit'), count: accepted },
                { label: t('res.notFit'), count: rejected },
              ].map((r, i) => (
                <div key={i} className={`px-3 py-2 flex items-center justify-between ${i===0?'bg-gray-50':''} ${i>0?'border-t border-line':''}`}>
                  <span className="text-ink">{r.label}</span>
                  <span className="text-ink-muted">{r.count}</span>
                </div>
              ))}
            </div>
          </div>

          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] font-medium text-ink-soft mb-2">{t('res.sector')}</div>
            <div className="space-y-1.5 text-[13px]">
              {['Faltschachtel','Wellpappe','Industrieverpackung','Recyclingkarton','Druckvermittlung'].map((f,i) => (
                <label key={i} className="flex items-center gap-2 text-ink">
                  <input type="checkbox" defaultChecked={i<3} className="accent-brand-500"/> {f}
                </label>
              ))}
            </div>
          </div>

          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] font-medium text-ink-soft mb-2">{t('res.employees')}</div>
            <div className="bg-white border border-line rounded-md px-3 py-2 text-[13px] text-ink flex items-center justify-between">
              <span>50 – 250</span>
              <Icon.ChevDown size={14} className="text-ink-muted"/>
            </div>
          </div>

          <div>
            <div className="text-[11px] uppercase tracking-[0.08em] font-medium text-ink-soft mb-2">{t('res.location')}</div>
            <div className="bg-white border border-line rounded-md px-3 py-2 text-[13px] text-ink flex items-center justify-between">
              <span>NRW</span>
              <Icon.ChevDown size={14} className="text-ink-muted"/>
            </div>
          </div>

          {/* The key differentiator, quietly — */}
          <div className="rounded-lg border border-line bg-surface p-3 text-[12.5px] text-ink-muted leading-relaxed">
            <div className="flex items-center gap-1.5 font-medium text-ink mb-1">
              <Icon.Sparkle size={14} className="text-brand-500"/>
              {t('res.learning.title')}
            </div>
            {t('res.learning.body')}
          </div>
        </aside>

        {/* Results list */}
        <div className="space-y-3">
          {profile.leads.map(lead => (
            <LeadCard
              key={lead.id}
              lead={lead}
              profile={profile}
              density={density}
              state={feedback[lead.id] || 'neutral'}
              onAccept={() => accept(lead)}
              onReject={(reason) => reject(lead, reason)}
              onOpen={() => onOpenLead(lead)}
            />
          ))}

          {/* Footer — honest about sampling */}
          <div className="hair pt-4 text-[12.5px] text-ink-muted">
            {t('res.footer', { count: profile.leads.length })}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenResults });
