// Lead Detail screen -----------------------------------------------------
// Every displayed field carries a provenance chip. A dedicated sources
// panel at the bottom reconciles all facts back to their origins.

function SourceChip({ field, leadId, compact = false }) {
  useLang();
  const src = (SOURCES[leadId] && SOURCES[leadId][field]) || SOURCES.default[field];
  if (!src) return null;
  const kind = SOURCE_KINDS[src.kind];
  const IconCmp = Icon[kind.icon] || Icon.Info;
  const [open, setOpen] = useState(false);
  const kindLabel = t(`src.${src.kind}`);
  return (
    <span
      className="relative inline-flex items-center"
      onMouseEnter={() => setOpen(true)}
      onMouseLeave={() => setOpen(false)}
    >
      <button
        type="button"
        className="inline-flex items-center gap-1 h-[18px] rounded-full border px-1.5 hover:brightness-95 transition"
        style={{ background: kind.bg, borderColor: 'transparent', color: kind.color }}
      >
        <IconCmp size={10}/>
        {!compact && <span className="text-[10px] font-medium leading-none">{kindLabel}</span>}
      </button>
      {open && (
        <span className="absolute left-0 top-full mt-1.5 z-20 w-[260px] bg-white border border-line rounded-md shadow-lg p-2.5 text-left fade-in" style={{animationDuration:'120ms'}}>
          <span className="block text-[10px] uppercase tracking-[0.08em] font-medium" style={{ color: kind.color }}>{kindLabel}</span>
          <span className="block text-[12px] text-ink mt-0.5 leading-snug">{src.label}</span>
          <span className="block text-[11px] text-ink-soft mt-1">{t('det.fetched')} {src.fetchedAt}</span>
        </span>
      )}
    </span>
  );
}

// Small row: label + value + inline source chip — unit used throughout firmenprofil + sources
function SourcedField({ label, value, field, leadId }) {
  return (
    <div className="flex items-start justify-between gap-4 py-2">
      <div className="min-w-0">
        <div className="text-[11px] uppercase tracking-[0.06em] font-medium text-ink-soft">{label}</div>
        <div className="text-[13.5px] text-ink mt-0.5">{value}</div>
      </div>
      <div className="pt-[18px] flex-shrink-0">
        <SourceChip field={field} leadId={leadId}/>
      </div>
    </div>
  );
}

function SourcesPanel({ leadId }) {
  useLang();
  const fields = (SOURCES[leadId] || SOURCES.default);
  const fieldLabels = {
    company: t('det.sector'), sector: t('det.sector'), city: t('det.city'),
    size: t('det.size'), founded: t('det.founded'), website: t('det.website'),
    decider: t('det.decider'), email: 'E-Mail', excerpt: t('det.shortProfile'),
  };
  // Group by (kind + label) so identical sources collapse
  const groups = {};
  Object.entries(fields).forEach(([field, src]) => {
    const key = `${src.kind}::${src.label}`;
    if (!groups[key]) groups[key] = { kind: src.kind, label: src.label, fetchedAt: src.fetchedAt, fields: [] };
    groups[key].fields.push(fieldLabels[field] || field);
  });
  const entries = Object.values(groups).sort((a, b) => {
    const order = ['official','web','directory','news','derived'];
    return order.indexOf(a.kind) - order.indexOf(b.kind);
  });

  return (
    <section className="mt-8">
      <div className="flex items-end justify-between mb-2.5">
        <div>
          <h2 className="text-[15px] font-semibold text-ink">{t('det.sourcesTitle')}</h2>
          <p className="text-[12.5px] text-ink-muted mt-0.5">{t('det.sourcesSub')}</p>
        </div>
        <div className="text-[11px] text-ink-soft">{entries.length} {t('det.sourcesCount')}</div>
      </div>

      <div className="bg-white border border-line rounded-lg overflow-hidden">
        {entries.map((g, i) => {
          const kind = SOURCE_KINDS[g.kind];
          const IconCmp = Icon[kind.icon] || Icon.Info;
          return (
            <div key={i} className={`px-5 py-4 flex items-start gap-4 ${i > 0 ? 'border-t border-line' : ''}`}>
              <div className="w-8 h-8 rounded-md flex-shrink-0 flex items-center justify-center" style={{ background: kind.bg, color: kind.color }}>
                <IconCmp size={15}/>
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="text-[11px] uppercase tracking-[0.08em] font-medium" style={{ color: kind.color }}>{t(`src.${g.kind}`)}</span>
                  <span className="text-[11px] text-ink-soft">· {t('det.fetched')} {g.fetchedAt}</span>
                </div>
                <div className="text-[13.5px] text-ink mt-0.5 font-medium">{g.label}</div>
                <div className="text-[12px] text-ink-muted mt-1">{t('det.delivers')} {g.fields.join(' · ')}</div>
              </div>
              <button className="text-[11.5px] text-ink-muted hover:text-ink flex items-center gap-1 mt-1 flex-shrink-0">
                {t('det.open')} <Icon.ExtLink size={11}/>
              </button>
            </div>
          );
        })}
      </div>

      <div className="mt-3 flex items-start gap-2 text-[12px] text-ink-muted leading-relaxed">
        <Icon.Info size={13} className="text-ink-soft mt-[2px] flex-shrink-0"/>
        <span>{t('det.publicOnly')}</span>
      </div>
    </section>
  );
}

function ScreenDetail({ profile, lead, onBack, feedback, setFeedback, toast }) {
  useLang();
  const state = feedback[lead.id] || 'neutral';
  const memMap = Object.fromEntries(profile.memory.map(m => [m.id, m]));
  const refs = (lead.reasonRefs || []).map(id => memMap[id]).filter(Boolean);

  const accept = () => { setFeedback({ ...feedback, [lead.id]: 'accepted' }); toast.push(`„${lead.company}" als Passt gespeichert.`, 'positive'); };
  const reject = () => { setFeedback({ ...feedback, [lead.id]: 'rejected' }); toast.push(`„${lead.company}" als Passt nicht markiert.`, 'negative'); };

  return (
    <div data-screen-label="Lead Detail" className="max-w-[1200px] mx-auto px-6 py-6">
      <button onClick={onBack} className="inline-flex items-center gap-1.5 text-sm text-ink-muted hover:text-ink mb-5">
        <Icon.ArrowL size={14}/> {t('det.back')}
      </button>

      <div className="grid grid-cols-[1fr_360px] gap-8">
        <div>
          {/* Company header */}
          <div className="flex items-start justify-between gap-6">
            <div className="min-w-0">
              <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{profile.short}</div>
              <div className="flex items-center gap-2 mt-0.5">
                <h1 className="text-[28px] font-semibold text-ink leading-tight">{lead.company}</h1>
                <SourceChip field="company" leadId={lead.id}/>
              </div>
              <div className="mt-1.5 text-[13.5px] text-ink-muted flex flex-wrap items-center gap-x-2 gap-y-1">
                <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>
            </div>
            <div className="flex flex-col gap-2 min-w-[180px]">
              {state === 'neutral' && (
                <>
                  <Button onClick={accept} variant="outline" className="!border-emerald-300 !text-emerald-800 hover:!bg-emerald-50"><Icon.Check size={15}/> {t('det.fits')}</Button>
                  <Button onClick={reject} variant="outline"><Icon.X size={15}/> {t('det.fitsNot')}</Button>
                </>
              )}
              {state === 'accepted' && <div className="text-right text-[13px] text-emerald-700 font-medium">{t('det.markedFit')}</div>}
              {state === 'rejected' && <div className="text-right text-[13px] text-ink-muted font-medium">{t('det.markedNotFit')}</div>}
            </div>
          </div>

          {/* Warum passt das zu dir */}
          <section className="mt-7">
            <div className="flex items-center gap-2 mb-2.5">
              <h2 className="text-[15px] font-semibold text-ink">{t('det.whyFits')}</h2>
              <span className="text-[11px] text-ink-soft">{t('det.whyFitsSub')}</span>
            </div>
            <div className="bg-white border border-line rounded-lg p-5">
              <div className="reason-rail">
                <p className="text-[15.5px] leading-[1.6] text-ink">{lead.reason}</p>
                {lead.uncertainty && (
                  <p className="text-[13px] text-ink-muted mt-2 italic">
                    Leadscraper ist hier {lead.score} — {lead.uncertainty}.
                  </p>
                )}
              </div>

              {refs.length > 0 && (
                <div className="mt-5 pt-4 border-t border-line space-y-2.5">
                  <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('det.patterns')}</div>
                  {refs.map(m => (
                    <div key={m.id} className="flex items-start gap-2.5">
                      <span className={`mt-1.5 h-1.5 w-1.5 rounded-full flex-shrink-0 ${m.strength==='strong'?'bg-ink':m.strength==='medium'?'bg-ink/50':'bg-ink/25'}`}/>
                      <div>
                        <div className="text-[13.5px] text-ink">{m.text}</div>
                        <div className="text-[12px] text-ink-muted">{m.evidence}</div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              <div className="mt-5 pt-4 border-t border-line">
                <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium mb-2.5">{t('det.similar')}</div>
                <div className="grid grid-cols-3 gap-2">
                  {PRIOR_ACCEPTED.map((p, i) => (
                    <div key={i} className="rounded-md border border-line p-3">
                      <div className="text-[13px] font-medium text-ink truncate">{p.company}</div>
                      <div className="text-[11.5px] text-ink-muted truncate">{p.meta}</div>
                      <div className="text-[11px] text-ink-soft mt-1">{t('det.accepted')} {p.whenAccepted}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </section>

          {/* Firmenprofil as structured sourced fields */}
          <section className="mt-7">
            <h2 className="text-[15px] font-semibold text-ink mb-2.5">{t('det.companyProfile')}</h2>
            <div className="bg-white border border-line rounded-lg divide-y divide-line">
              <div className="px-5">
                <SourcedField label={t('det.sector')}   value={lead.sector}  field="sector"  leadId={lead.id}/>
              </div>
              <div className="px-5">
                <SourcedField label={t('det.city')}     value={lead.city}    field="city"    leadId={lead.id}/>
              </div>
              <div className="px-5">
                <SourcedField label={t('det.size')}     value={lead.size}    field="size"    leadId={lead.id}/>
              </div>
              <div className="px-5">
                <SourcedField label={t('det.founded')}  value={lead.founded} field="founded" leadId={lead.id}/>
              </div>
              <div className="px-5">
                <SourcedField label={t('det.website')}  value={lead.website} field="website" leadId={lead.id}/>
              </div>
              <div className="px-5 py-4">
                <div className="flex items-center gap-2 mb-1.5">
                  <div className="text-[11px] uppercase tracking-[0.06em] font-medium text-ink-soft">{t('det.shortProfile')}</div>
                  <SourceChip field="excerpt" leadId={lead.id}/>
                </div>
                <div className="text-[13.5px] text-ink leading-[1.6]">{lead.excerpt}</div>
              </div>
            </div>
          </section>

          {/* Website-Auszüge */}
          <section className="mt-7">
            <h2 className="text-[15px] font-semibold text-ink mb-2.5">{t('det.webExcerpts')}</h2>
            <div className="bg-white border border-line rounded-lg divide-y divide-line">
              {[
                { path: '/ueber-uns', quote: 'Seit drei Generationen im Familienbesitz. Unsere Produktion in NRW steht für Qualität und kurze Wege.' },
                { path: '/produktion', quote: 'Zwei Stanzautomaten und ein 8-Farben-Offsetdruck ermöglichen Faltschachteln in Serienstärken ab 1.000 Stück.' },
                { path: '/nachhaltigkeit', quote: 'FSC-zertifiziert seit 2019. 94 % unseres Kartons stammt aus Recyclingfaser.' },
              ].map((q, i) => (
                <div key={i} className="p-4">
                  <div className="text-[11px] text-ink-soft font-mono mb-1 flex items-center gap-2">
                    {lead.website}{q.path}
                    <SourceChip field="excerpt" leadId={lead.id} compact/>
                  </div>
                  <div className="text-[14px] text-ink leading-[1.55]">„{q.quote}"</div>
                </div>
              ))}
            </div>
          </section>

          {/* The defining transparency section */}
          <SourcesPanel leadId={lead.id}/>
        </div>

        {/* Right rail */}
        <aside className="space-y-5">
          <div className="bg-white border border-line rounded-lg p-4">
            <div className="flex items-center gap-2 mb-3">
              <div className="text-[11px] uppercase tracking-[0.08em] font-medium text-ink-soft">{t('det.decider')}</div>
              <SourceChip field="decider" leadId={lead.id} compact/>
            </div>
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-sm font-semibold text-ink">
                {lead.decider.name.split(' ').map(n => n[0]).slice(0,2).join('')}
              </div>
              <div>
                <div className="text-[14px] font-medium text-ink">{lead.decider.name}</div>
                <div className="text-[12px] text-ink-muted">{lead.decider.role}</div>
              </div>
            </div>
            <div className="mt-3 space-y-1.5 text-[13px]">
              <div className="flex items-center gap-2">
                <a className="flex items-center gap-2 text-ink hover:text-brand-500 flex-1 min-w-0 truncate"><Icon.Mail size={14} className="text-ink-muted flex-shrink-0"/> <span className="truncate">{lead.decider.email}</span></a>
                <SourceChip field="email" leadId={lead.id} compact/>
              </div>
              <div className="flex items-center gap-2">
                <a className="flex items-center gap-2 text-ink hover:text-brand-500 flex-1 min-w-0 truncate"><Icon.Globe size={14} className="text-ink-muted flex-shrink-0"/> <span className="truncate">{lead.website}</span></a>
                <SourceChip field="website" leadId={lead.id} compact/>
              </div>
            </div>
          </div>

          <div className="bg-white border border-line rounded-lg p-4">
            <div className="text-[11px] uppercase tracking-[0.08em] font-medium text-ink-soft mb-2">{t('det.contact')}</div>
            <Button variant="brand" className="w-full">{t('det.draftMail')}</Button>
            <Button variant="outline" className="w-full mt-2">{t('det.toCRM')}</Button>
          </div>

          <div className="rounded-lg bg-surface p-4 text-[12.5px] text-ink-muted leading-relaxed">
            <div className="flex items-center gap-1.5 text-ink font-medium mb-1">
              <Icon.Info size={14} className="text-brand-500"/>
              {t('det.memoryHint')}
            </div>
            {t('det.memoryHintText', { profile: profile.short })}
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenDetail, SourceChip });
