// Profile 360° detail screen — hero, performance, memory, runs, leads preview
// Opens when user clicks a profile in the dashboard or "Mein Profil" tab.

function ScreenProfileDetail({ profile, memory, setMemory, onGoToResults, toast, onConfirmPattern, onRejectPattern }) {
  useLang();
  const [schedules, setSchedules] = useSchedules();
  const crm = useCRM();
  const crmConnected = Object.keys(crm.conns || {}).length > 0;
  // toast prop here is a function in this screen; ScheduledRunsSection expects {push}. Wrap it:
  const toastShim = React.useMemo(() => ({
    push: (msg) => (typeof toast === 'function' ? toast(msg) : null),
  }), [toast]);

  if (!profile) return null;

  const now = profile.matchRateNow || 0;
  const start = profile.matchRateStart || 0;
  const delta = now - start;
  const grouped = {
    strong: (memory || []).filter(m => m.strength === 'strong'),
    medium: (memory || []).filter(m => m.strength === 'medium'),
    weak:   (memory || []).filter(m => m.strength === 'weak'),
  };
  const topLeads = (profile.leads || []).slice(0, 4);
  const runsCount = (profile.runs || []).length;
  const lastRun = (profile.runs && profile.runs[profile.runs.length - 1]) || null;

  return (
    <div data-screen-label={t('pd.screenLabel')} className="pb-16 fade-in">
      {/* Header — clean white, matches rest of app */}
      <div className="border-b border-line bg-white">
        <div className="max-w-[1180px] mx-auto px-6 pt-8 pb-6">
          <div className="flex items-start gap-4">
            <div className="w-[52px] h-[52px] rounded-lg bg-brand/10 border border-brand/20 flex items-center justify-center text-[20px] font-semibold text-brand flex-shrink-0">
              {profile.initial}
            </div>
            <div className="flex-1 min-w-0">
              <h1 className="text-[26px] font-semibold text-ink tracking-tight leading-[1.15]">{profile.name}</h1>
              <div className="text-[13px] text-ink-soft mt-1">{profile.query}</div>
              <div className="mt-2 flex items-center gap-2.5 text-[11.5px] text-ink-soft">
                <span>{t('pd.activeSince', { date: profile.createdAt })}</span>
                <span className="w-0.5 h-0.5 rounded-full bg-ink-soft/50"/>
                <span>{t('pd.ratings', { n: profile.feedbackCount })}</span>
                <span className="w-0.5 h-0.5 rounded-full bg-ink-soft/50"/>
                <span>{t('pd.runs', { n: runsCount })}</span>
              </div>
            </div>
            <button onClick={onGoToResults}
              className="px-3.5 h-[34px] rounded-md text-[13px] font-medium text-white bg-brand hover:bg-brand-dark transition-colors inline-flex items-center gap-1.5">
              {t('pd.openLeads')} <Icon.ChevRight size={13}/>
            </button>
          </div>

          {/* Stats row — compact, on white */}
        </div>
      </div>

      {/* Body */}
      <div className="max-w-[1180px] mx-auto px-6 mt-8 grid grid-cols-[1fr_340px] gap-8">
        {/* Main column */}
        <div className="min-w-0 space-y-10">
          {/* Performance card */}
          <section>
            <SectionTitle title={t('pd.curve.title')} sub={t('pd.curve.sub')}/>
            <div className="bg-white border border-line rounded-xl p-5 mt-3">
              <LearningCurve profile={profile} now={now} start={start}/>
            </div>
          </section>

          {/* Learned patterns — compact */}
          <section>
            <SectionTitle title={t('pd.patterns.title')}
                          sub={t('pd.patterns.sub')}/>
            <div className="mt-3 space-y-4">
              {grouped.strong.length > 0 && (
                <PatternGroup tone="strong" label={t('pd.patterns.strong')} items={grouped.strong}
                  setMemory={setMemory} toast={toast}/>
              )}
              {grouped.medium.length > 0 && (
                <PatternGroup tone="medium" label={t('pd.patterns.medium')} items={grouped.medium}
                  setMemory={setMemory} toast={toast}/>
              )}
              {grouped.weak.length > 0 && (
                <PatternGroup tone="weak" label={t('pd.patterns.weak')} items={grouped.weak}
                  setMemory={setMemory} toast={toast}/>
              )}
            </div>
          </section>

          {/* Runs */}
          {typeof RunsHistory !== 'undefined' && (
            <section>
              <RunsHistory runs={profile.runs || []} profile={profile} toast={toast}/>
            </section>
          )}

          {/* Scheduled (recurring) runs */}
          <section>
            <ScheduledRunsSection profile={profile} schedules={schedules} setSchedules={setSchedules}
                                  toast={toastShim} crmConnected={crmConnected}/>
          </section>

          {/* Top leads preview */}
          {topLeads.length > 0 && (
            <section>
              <div className="flex items-end justify-between">
                <SectionTitle title={t('pd.leads.title')} sub={t('pd.leads.sub')}/>
                <button onClick={onGoToResults}
                        className="text-[12px] text-[#3465E3] font-medium hover:underline inline-flex items-center gap-1">
                  {t('pd.leads.viewAll')} <Icon.ChevRight size={11}/>
                </button>
              </div>
              <div className="mt-3 bg-white border border-line rounded-xl overflow-hidden">
                {topLeads.map((l, i) => (
                  <div key={l.id} className={`px-5 py-3.5 flex items-center gap-4 ${i>0?'border-t border-line':''} hover:bg-[#FAFCFF] transition-colors`}>
                    <div className="w-8 h-8 rounded-md bg-[#F4F7FD] flex items-center justify-center text-[11px] font-semibold text-[#3465E3] flex-shrink-0">
                      {(l.company || '?').charAt(0)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-[13.5px] font-medium text-ink truncate">{l.company}</div>
                      <div className="text-[11.5px] text-ink-muted truncate">{l.location || l.city || ''}</div>
                    </div>
                    {l.score && (
                      <span className={`text-[10.5px] uppercase tracking-[0.08em] font-medium px-2 py-[3px] rounded-full ${
                        l.score === 'passt' ? 'bg-emerald-50 text-emerald-700' :
                        l.score === 'passt-nicht' ? 'bg-red-50 text-red-700' :
                        'bg-gray-100 text-ink-muted'
                      }`}>
                        {l.score}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            </section>
          )}
        </div>

        {/* Sidebar */}
        <aside className="space-y-5">
          {/* Query summary card */}
          <div className="bg-white border border-line rounded-xl p-5">
            <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('pd.side.focus')}</div>
            <div className="text-[14px] text-ink mt-1.5 leading-relaxed">{profile.query}</div>
            <div className="mt-3 pt-3 border-t border-[#F0F4FA] text-[12px] text-ink-muted leading-relaxed">
              {(profile.reasons || []).length > 0 && (
                <>
                  <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium mb-1.5">{t('pd.side.reasons')}</div>
                  <div className="flex flex-wrap gap-1">
                    {(profile.reasons || []).slice(0, 5).map(r => (
                      <span key={r} className="inline-flex items-center px-2 py-[3px] rounded text-[11px] bg-[#F4F7FD] text-ink-muted">
                        {r}
                      </span>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>

          {/* Next actions */}
          <div className="rounded-xl p-5" 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('pd.side.recommended')}
            </div>
            <ol className="space-y-3 text-[13px] text-ink">
              <NextStep n={1} title={t('pd.side.next1.t')} desc={t('pd.side.next1.d', { pct: Math.round(now*100) })} onClick={onGoToResults}/>
              <NextStep n={2} title={t('pd.side.next2.t')} desc={t('pd.side.next2.d')}/>
              <NextStep n={3} title={t('pd.side.next3.t')} desc={t('pd.side.next3.d')}/>
            </ol>
          </div>

          {/* Snapshot — unified profile data sheet, label left, value right */}
          <div className="bg-white border border-line rounded-xl p-5">
            <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium mb-3">{t('pd.side.snapshot')}</div>
            <div className="space-y-2.5 text-[12.5px]">
              <ActivityRow label={t('pd.side.matchRate')} value={
                <span><span className="text-ink font-semibold tabular-nums">{Math.round(now*100)} %</span>
                <span className="text-emerald-700 ml-1.5 text-[11.5px] font-medium">+{Math.round(delta*100)} %</span></span>
              }/>
              <ActivityRow label={t('pd.side.leadsTotal')} value={
                <span><span className="text-ink font-semibold tabular-nums">{(profile.leads || []).length}</span>
                <span className="text-ink-muted ml-1.5 text-[11.5px]">{t('pd.side.accepted', { n: profile.acceptedCount })}</span></span>
              }/>
              <ActivityRow label={t('pd.side.patterns')} value={
                <span><span className="text-ink font-semibold tabular-nums">{(memory || []).length}</span>
                <span className="text-ink-muted ml-1.5 text-[11.5px]">{t('pd.side.patternsSub', { strong: grouped.strong.length, medium: grouped.medium.length })}</span></span>
              }/>
              <ActivityRow label={t('pd.side.lastRun')} value={
                <span><span className="text-ink font-semibold">{lastRun ? lastRun.dateRelative : '—'}</span>
                {lastRun && <span className="text-ink-muted ml-1.5 text-[11.5px]">{t('pd.side.lastRunLeads', { n: lastRun.leadCount })}</span>}</span>
              }/>
              <div className="pt-2.5 mt-1 border-t border-line space-y-2.5">
                <ActivityRow label={t('pd.side.firstRun')} value={profile.createdAt}/>
                <ActivityRow label={t('pd.side.feedbacks')} value={`${profile.feedbackCount}`}/>
                <ActivityRow label={t('pd.side.matchMiss')} value={`${profile.acceptedCount} / ${profile.rejectedCount}`}/>
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

function HeroStat({ label, big, sub }) {
  return (
    <div className="bg-surface border border-line rounded-lg px-4 py-3">
      <div className="text-[10.5px] uppercase tracking-[0.08em] text-ink-soft font-medium">{label}</div>
      <div className="text-[24px] font-semibold text-ink mt-0.5 leading-none tabular-nums">{big}</div>
      <div className="text-[11px] text-ink-soft mt-1 leading-tight">{sub}</div>
    </div>
  );
}

function SnapshotKPI({ label, big, sub }) {
  return (
    <div>
      <div className="text-[10px] uppercase tracking-[0.08em] text-ink-soft font-medium">{label}</div>
      <div className="text-[18px] font-semibold text-ink mt-1 leading-none tabular-nums">{big}</div>
      <div className="text-[10.5px] text-ink-soft mt-1 leading-tight">{sub}</div>
    </div>
  );
}

function LearningCurve({ profile, now, start }) {
  useLang();
  const values = profile.matchHistory || [];
  const feedbacks = profile.feedbackHistory || [];
  if (values.length < 2) return <div className="text-[12px] text-ink-soft py-6 text-center">{t('pd.curve.noData')}</div>;

  // Geometry — viewBox-based, scales to container
  const W = 1000, H = 200;
  const PAD = { l: 36, r: 16, t: 14, b: 28 };
  const innerW = W - PAD.l - PAD.r;
  const innerH = H - PAD.t - PAD.b;
  const min = 0, max = 1;
  const x = i => PAD.l + (i / (values.length - 1)) * innerW;
  const y = v => PAD.t + (1 - (v - min) / (max - min)) * innerH;

  // Smooth path
  const path = values.map((v, i) => `${i === 0 ? 'M' : 'L'} ${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(' ');
  const area = `${path} L ${x(values.length - 1).toFixed(1)} ${PAD.t + innerH} L ${PAD.l} ${PAD.t + innerH} Z`;

  // Phase markers — synthetic milestones
  const totalFb = feedbacks.reduce((s,n)=>s+n,0);
  const phases = [
    { i: 0, label: t('pd.curve.start'), sub: t('pd.curve.coldSub'), placement: 'right' },
    { i: Math.floor(values.length * 0.35), label: t('pd.curve.milestone50'), sub: t('pd.curve.milestone50Sub'), placement: 'top' },
    { i: Math.floor(values.length * 0.7), label: t('pd.curve.milestone200'), sub: t('pd.curve.milestone200Sub'), placement: 'top' },
    { i: values.length - 1, label: t('pd.curve.today'), sub: t('pd.curve.todaySub', { n: totalFb }), placement: 'left' },
  ];

  // Y-axis ticks at 0, 25, 50, 75, 100 %
  const ticks = [0, 0.25, 0.5, 0.75, 1];
  const lift = Math.round((now - start) * 100);

  return (
    <div>
      {/* Header — different angle than stats strip */}
      <div className="flex items-baseline justify-between mb-1">
        <div>
          <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('pd.curve.liftLabel')}</div>
          <div className="flex items-baseline gap-2 mt-1">
            <div className="text-[28px] font-semibold text-emerald-700 leading-none tabular-nums">+{lift}&thinsp;%</div>
            <div className="text-[12.5px] text-ink-soft">{t('pd.curve.liftSub')}</div>
          </div>
        </div>
        <div className="text-right">
          <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{Math.round(start*100)} % → {Math.round(now*100)} %</div>
          <div className="text-[12px] text-ink-muted mt-1">{t('pd.curve.inWeeks', { n: values.length })}</div>
        </div>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} className="block w-full h-auto mt-3" preserveAspectRatio="none" style={{ maxHeight: 220 }}>
        <defs>
          <linearGradient id="lc-fill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#3465E3" stopOpacity="0.18"/>
            <stop offset="100%" stopColor="#3465E3" stopOpacity="0"/>
          </linearGradient>
        </defs>

        {/* Grid + y-axis */}
        {ticks.map(t => (
          <g key={t}>
            <line x1={PAD.l} x2={W - PAD.r} y1={y(t)} y2={y(t)} stroke="#E8E5DD" strokeWidth="1" strokeDasharray={t === 0 || t === 1 ? '' : '2 3'}/>
            <text x={PAD.l - 8} y={y(t) + 3} fontSize="10" fill="#7C7466" textAnchor="end" fontFamily="inherit">{Math.round(t * 100)}%</text>
          </g>
        ))}

        {/* Area + line */}
        <path d={area} fill="url(#lc-fill)"/>
        <path d={path} fill="none" stroke="#3465E3" strokeWidth="1.75" strokeLinejoin="round" strokeLinecap="round" className="draw-path"/>

        {/* Phase markers */}
        {phases.map((p, idx) => {
          const px = x(p.i), py = y(values[p.i]);
          const above = p.placement === 'top';
          const left = p.placement === 'left';
          const right = p.placement === 'right';
          const tx = left ? px - 6 : right ? px + 6 : px;
          const ty = above ? py - 12 : py + 18;
          const anchor = left ? 'end' : right ? 'start' : 'middle';
          return (
            <g key={idx}>
              <line x1={px} x2={px} y1={PAD.t} y2={PAD.t + innerH} stroke="#C9C2B0" strokeWidth="0.75" strokeDasharray="2 3"/>
              <circle cx={px} cy={py} r="3.5" fill="#3465E3" stroke="white" strokeWidth="1.5"/>
              <text x={tx} y={ty} fontSize="10.5" fontWeight="600" fill="#1A1814" textAnchor={anchor} fontFamily="inherit">{p.label}</text>
              <text x={tx} y={ty + 12} fontSize="9.5" fill="#7C7466" textAnchor={anchor} fontFamily="inherit">{p.sub}</text>
            </g>
          );
        })}
      </svg>

      <div className="flex justify-between text-[10.5px] text-ink-soft mt-1 px-9">
        <span>{profile.createdAt}</span><span>{t('pd.curve.today')}</span>
      </div>
    </div>
  );
}

function SectionTitle({ title, sub }) {
  return (
    <div>
      <h2 className="text-[18px] font-semibold text-ink tracking-tight">{title}</h2>
      {sub && <p className="text-[12.5px] text-ink-muted mt-0.5">{sub}</p>}
    </div>
  );
}

function PatternGroup({ tone, label, items, setMemory, toast }) {
  const dot = tone === 'strong' ? 'bg-emerald-500' : tone === 'medium' ? 'bg-[#3465E3]' : 'bg-amber-500';
  return (
    <div>
      <div className="flex items-center gap-2 mb-2">
        <span className={`w-2 h-2 rounded-full ${dot}`}/>
        <span className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{label}</span>
        <span className="text-[11px] text-ink-soft">· {items.length}</span>
      </div>
      <div className="space-y-2">
        {items.map(m => (
          <PatternRow key={m.id} item={m} tone={tone} setMemory={setMemory} toast={toast}/>
        ))}
      </div>
    </div>
  );
}

function PatternRow({ item, tone, setMemory, toast }) {
  useLang();
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [removed, setRemoved] = React.useState(false);
  const menuRef = React.useRef(null);

  React.useEffect(() => {
    if (!menuOpen) return;
    const onClick = (e) => { if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false); };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, [menuOpen]);

  const promote = () => {
    setMemory && setMemory(prev => prev.map(p => p.id === item.id ? { ...p, strength: 'strong' } : p));
    toast && toast(t('pd.toast.confirmed'));
  };
  const reject = () => {
    setRemoved(true);
    setTimeout(() => {
      setMemory && setMemory(prev => prev.filter(p => p.id !== item.id));
      toast && toast(t('pd.toast.rejected'));
    }, 200);
  };
  const weaken = () => {
    setMemory && setMemory(prev => prev.map(p => p.id === item.id ? { ...p, strength: 'weak' } : p));
    toast && toast(t('pd.toast.weakened'));
    setMenuOpen(false);
  };
  const remove = () => {
    setRemoved(true);
    setTimeout(() => {
      setMemory && setMemory(prev => prev.filter(p => p.id !== item.id));
      toast && toast(t('pd.toast.removed'));
    }, 200);
  };

  return (
    <div className={`bg-white border border-line rounded-lg px-4 py-3 ${removed ? 'swoosh-out' : 'fade-in'}`}>
      <div className="flex items-start gap-3">
        <div className="flex-1 min-w-0">
          <div className="text-[13.5px] text-ink leading-snug">{item.text}</div>
          {item.evidence && <div className="text-[11.5px] text-ink-muted mt-1.5 leading-snug">{item.evidence}</div>}
        </div>

        {tone === 'weak' ? (
          <div className="flex items-center gap-1.5 flex-shrink-0">
            <button onClick={promote}
              title={t('pd.pat.confirmT')}
              className="h-7 px-2.5 rounded-md text-[11.5px] font-medium text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200 transition-colors inline-flex items-center gap-1">
              <Icon.Check size={11}/> {t('pd.pat.confirm')}
            </button>
            <button onClick={reject}
              title={t('pd.pat.rejectT')}
              className="h-7 px-2.5 rounded-md text-[11.5px] font-medium text-rose-700 bg-white hover:bg-rose-50 border border-line hover:border-rose-200 transition-colors inline-flex items-center gap-1">
              <Icon.X size={11}/> {t('pd.pat.reject')}
            </button>
          </div>
        ) : (
          <div className="relative flex-shrink-0" ref={menuRef}>
            <button onClick={() => setMenuOpen(o => !o)}
              className="w-7 h-7 rounded-md text-ink-soft hover:text-ink hover:bg-surface transition-colors inline-flex items-center justify-center"
              title={t('pd.pat.actions')}>
              <span className="text-[16px] leading-none -mt-1">⋯</span>
            </button>
            {menuOpen && (
              <div className="absolute right-0 top-8 z-10 w-[180px] bg-white border border-line rounded-md shadow-lg py-1">
                <button onClick={weaken}
                  className="w-full text-left px-3 py-1.5 text-[12.5px] text-ink hover:bg-surface flex items-center gap-2">
                  <Icon.Warn size={11}/> {t('pd.pat.weaken')}
                </button>
                <button onClick={remove}
                  className="w-full text-left px-3 py-1.5 text-[12.5px] text-rose-700 hover:bg-rose-50 flex items-center gap-2">
                  <Icon.X size={11}/> {t('pd.pat.remove')}
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function NextStep({ n, title, desc, onClick }) {
  return (
    <li onClick={onClick} className={`flex items-start gap-2.5 ${onClick ? 'cursor-pointer group' : ''}`}>
      <span className="w-5 h-5 rounded-full bg-white border border-[#E4D9F7] flex items-center justify-center text-[10.5px] font-semibold text-[#6B5ED6] flex-shrink-0 mt-0.5">{n}</span>
      <div className="flex-1">
        <div className={`text-[13px] font-medium text-ink ${onClick ? 'group-hover:text-[#6B5ED6]' : ''}`}>{title}</div>
        <div className="text-[11.5px] text-ink-muted leading-snug mt-0.5">{desc}</div>
      </div>
    </li>
  );
}

function ActivityRow({ label, value }) {
  return (
    <div className="flex items-baseline justify-between">
      <span className="text-ink-muted">{label}</span>
      <span className="text-ink font-medium tabular-nums">{value}</span>
    </div>
  );
}

Object.assign(window, { ScreenProfileDetail });
