// Notifications — smart, calm nudges that guide the user to train the Cortex.
//
// Surfaces: bell-in-header (full list), dashboard inline banner (1 critical),
// cortex pattern cards in Memory view (2-stage confirm), hint chips in Leads table.

// Notification kinds:
//   'review'    — leads waiting for judgement
//   'pattern'   — Cortex has learned a pattern; user should confirm/reject
//   'edge'      — borderline/uncertain leads need a verdict
// severity: 'critical' (dashboard-worthy) | 'normal' | 'low'

function buildNotifications(profiles, feedbackByProfile) {
  const items = [];

  profiles.forEach(p => {
    const fb = feedbackByProfile[p.id] || {};
    const unseenCount = (p.leads || []).filter(l => !fb[l.id] || fb[l.id] === 'neutral').length;
    const uncertainLeads = (p.leads || []).filter(l => (l.score === 'unsicher' || l.uncertainty) && (!fb[l.id] || fb[l.id] === 'neutral'));

    // Review prompt
    if (unseenCount >= 3) {
      items.push({
        id: `rev-${p.id}`,
        kind: 'review',
        severity: unseenCount >= 8 ? 'critical' : 'normal',
        profileId: p.id,
        profileShort: p.short,
        profileInitial: p.initial,
        titleKey: 'notif.review.title',
        bodyKey: 'notif.review.body',
        bodyVars: { n: unseenCount, profile: p.short },
        actionKey: 'notif.review.cta',
        actionTarget: 'results',
        createdRelative: 'gerade eben',
      });
    }

    // Pattern confirmation — use first unconfirmed memory item
    const unconfirmed = (p.memory || []).filter(m => !m.confirmed && !m.uncertain);
    unconfirmed.slice(0, 1).forEach((m) => {
      items.push({
        id: `pat-${p.id}-${m.id}`,
        kind: 'pattern',
        severity: 'normal',
        profileId: p.id,
        profileShort: p.short,
        profileInitial: p.initial,
        patternId: m.id,
        titleKey: 'notif.pattern.title',
        bodyText: m.text,
        evidenceText: m.evidence,
        actionTarget: 'memory',
        createdRelative: 'vor 2 Std.',
      });
    });

    // Edge cases
    if (uncertainLeads.length > 0) {
      items.push({
        id: `edge-${p.id}`,
        kind: 'edge',
        severity: uncertainLeads.length >= 3 ? 'normal' : 'low',
        profileId: p.id,
        profileShort: p.short,
        profileInitial: p.initial,
        titleKey: 'notif.edge.title',
        bodyKey: 'notif.edge.body',
        bodyVars: { n: uncertainLeads.length, profile: p.short },
        actionTarget: 'results',
        createdRelative: 'heute, 09:12',
        leadIds: uncertainLeads.map(l => l.id),
      });
    }
  });

  // Sort: critical first, then normal, then low
  const order = { critical: 0, normal: 1, low: 2 };
  return items.sort((a,b) => order[a.severity] - order[b.severity]);
}

function NotifIcon({ kind, size = 14 }) {
  if (kind === 'review') return <Icon.User size={size}/>;
  if (kind === 'pattern') return <Icon.Brain size={size}/>;
  if (kind === 'edge') return <Icon.Warn size={size}/>;
  return <Icon.Info size={size}/>;
}

function NotifKindBadge({ kind }) {
  useLang();
  const map = {
    review:  { bg: '#EEF2FE', fg: '#3465E3', label: t('notif.kind.review') },
    pattern: { bg: '#EFECFB', fg: '#6B5ED6', label: t('notif.kind.pattern') },
    edge:    { bg: '#FEF7E6', fg: '#B4580C', label: t('notif.kind.edge') },
  };
  const s = map[kind] || map.review;
  return (
    <span className="inline-flex items-center gap-1 text-[10.5px] font-medium px-1.5 py-0.5 rounded" style={{background:s.bg, color:s.fg}}>
      <NotifIcon kind={kind} size={11}/>{s.label}
    </span>
  );
}

// ---- Header bell -------------------------------------------------------

function NotifBell({ items, onOpen, onAct, dismissedIds, onDismiss, readIds, onMarkRead }) {
  useLang();
  const [open, setOpen] = useState(false);
  const visible = items.filter(i => !dismissedIds.has(i.id));
  const unreadCount = visible.filter(i => !readIds.has(i.id)).length;

  useEffect(() => {
    if (!open) return;
    const close = (e) => { if (!e.target.closest('.notif-root')) setOpen(false); };
    window.addEventListener('mousedown', close);
    return () => window.removeEventListener('mousedown', close);
  }, [open]);

  return (
    <div className="notif-root relative">
      <button
        onClick={() => { setOpen(!open); if (!open) visible.forEach(i => onMarkRead(i.id)); }}
        className="relative w-8 h-8 rounded-md hover:bg-gray-100 flex items-center justify-center text-ink-muted hover:text-ink transition-colors"
        title={t('notif.title')}>
        <Icon.Bell size={16}/>
        {unreadCount > 0 && (
          <span className="absolute top-1 right-1 min-w-[14px] h-[14px] px-1 rounded-full bg-[#3465E3] text-white text-[9.5px] font-semibold flex items-center justify-center ring-2 ring-white">
            {unreadCount}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute top-[calc(100%+6px)] right-0 w-[380px] bg-white border border-line rounded-lg shadow-[0_12px_36px_-12px_rgba(15,23,42,0.18)] z-50 fade-in overflow-hidden">
          <div className="px-4 py-3 border-b border-line flex items-center justify-between">
            <div>
              <div className="text-[13.5px] font-semibold text-ink">{t('notif.title')}</div>
              <div className="text-[11.5px] text-ink-muted mt-0.5">{t('notif.sub')}</div>
            </div>
            {visible.length > 0 && (
              <span className="text-[11px] text-ink-soft tabular-nums">{visible.length}</span>
            )}
          </div>

          <div className="max-h-[440px] overflow-y-auto">
            {visible.length === 0 ? (
              <div className="px-5 py-10 text-center">
                <div className="w-10 h-10 rounded-full bg-emerald-50 text-emerald-600 mx-auto flex items-center justify-center mb-2.5">
                  <Icon.Check size={18}/>
                </div>
                <div className="text-[13px] font-medium text-ink">{t('notif.empty.title')}</div>
                <div className="text-[12px] text-ink-muted mt-1">{t('notif.empty.sub')}</div>
              </div>
            ) : (
              visible.map(item => (
                <NotifItem key={item.id} item={item}
                  onAct={() => { onAct(item); setOpen(false); }}
                  onDismiss={() => onDismiss(item.id)}/>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function NotifItem({ item, onAct, onDismiss }) {
  useLang();
  const body = item.bodyKey ? t(item.bodyKey, item.bodyVars) : item.bodyText;
  return (
    <div className="px-4 py-3 border-b border-line last:border-b-0 hover:bg-[#FAFCFF] transition-colors group">
      <div className="flex items-start gap-2.5">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1 flex-wrap">
            <NotifKindBadge kind={item.kind}/>
            <span className="inline-flex items-center gap-1 text-[10.5px] text-ink-soft">
              <span className="w-3.5 h-3.5 rounded flex items-center justify-center text-[9px] font-semibold bg-gray-100 text-ink">{item.profileInitial}</span>
              {item.profileShort}
            </span>
            <span className="text-[10.5px] text-ink-soft">·</span>
            <span className="text-[10.5px] text-ink-soft">{item.createdRelative}</span>
          </div>
          <div className="text-[12.5px] text-ink leading-snug">{body}</div>
          {item.evidenceText && (
            <div className="text-[11.5px] text-ink-muted mt-1 leading-snug italic">{item.evidenceText}</div>
          )}
          <div className="flex items-center gap-3 mt-2">
            <button onClick={onAct} className="text-[12px] font-medium text-[#3465E3] hover:underline">
              {item.kind === 'pattern' ? t('notif.act.pattern') : item.kind === 'edge' ? t('notif.act.edge') : t('notif.act.review')}
            </button>
            <button onClick={onDismiss} className="text-[11.5px] text-ink-soft hover:text-ink-muted opacity-0 group-hover:opacity-100 transition-opacity">
              {t('notif.dismiss')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- Dashboard inline banner ------------------------------------------

function DashboardNotifBanner({ items, dismissedIds, onAct, onDismiss }) {
  useLang();
  // Show the single most critical item that's not dismissed
  const critical = items.find(i => i.severity === 'critical' && !dismissedIds.has(i.id));
  if (!critical) return null;

  const body = critical.bodyKey ? t(critical.bodyKey, critical.bodyVars) : critical.bodyText;

  return (
    <div className="flex items-start gap-3 p-3.5 rounded-lg border mb-5 fade-in"
         style={{borderColor:'#D7E2F7', background:'linear-gradient(180deg, #F4F7FF 0%, #FFFFFF 100%)'}}>
      <div className="w-9 h-9 rounded-md flex items-center justify-center flex-shrink-0" style={{background:'#3465E3', color:'white'}}>
        <NotifIcon kind={critical.kind} size={16}/>
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 mb-0.5">
          <NotifKindBadge kind={critical.kind}/>
          <span className="inline-flex items-center gap-1 text-[11px] text-ink-soft">
            <span className="w-3.5 h-3.5 rounded flex items-center justify-center text-[9px] font-semibold bg-gray-100 text-ink">{critical.profileInitial}</span>
            {critical.profileShort}
          </span>
        </div>
        <div className="text-[13.5px] text-ink leading-snug">{body}</div>
      </div>
      <div className="flex items-center gap-1.5 flex-shrink-0">
        <button onClick={() => onAct(critical)} className="px-3 py-1.5 text-[12px] font-medium rounded-md bg-[#3465E3] text-white hover:bg-[#2a54c4] transition-colors">
          {critical.kind === 'pattern' ? t('notif.act.pattern') : critical.kind === 'edge' ? t('notif.act.edge') : t('notif.act.review')}
        </button>
        <button onClick={() => onDismiss(critical.id)} className="w-7 h-7 rounded-md hover:bg-white/70 flex items-center justify-center text-ink-soft hover:text-ink-muted transition-colors">
          <Icon.X size={13}/>
        </button>
      </div>
    </div>
  );
}

// ---- Pattern confirmation card (Memory view) -------------------------

function PatternConfirmCard({ pattern, onConfirm, onReject, onDismiss }) {
  useLang();
  const [showWhy, setShowWhy] = useState(false);
  const [why, setWhy] = useState('');
  const [pendingAction, setPendingAction] = useState(null); // 'confirm' | 'reject' | null

  if (!pattern) return null;

  if (pendingAction) {
    // Stage 2 — optional why
    return (
      <div className="p-4 rounded-lg border fade-in" style={{borderColor:'#E4D9F7', background:'linear-gradient(180deg, #FBF8FF 0%, #FFFFFF 100%)'}}>
        <div className="flex items-center gap-2 mb-2">
          <span className="inline-flex items-center gap-1 text-[11px] font-medium px-2 py-0.5 rounded-full" style={{background:'#EFECFB', color:'#6B5ED6'}}>
            <Icon.Brain size={11}/>{t('notif.pattern.stage2')}
          </span>
        </div>
        <div className="text-[13px] text-ink mb-2 leading-snug">{pattern.text}</div>
        <div className="text-[12px] text-ink-muted mb-3 italic">{t(pendingAction === 'confirm' ? 'notif.pattern.confirmedLabel' : 'notif.pattern.rejectedLabel')}</div>
        <div className="text-[11.5px] text-ink-soft uppercase tracking-[0.06em] font-medium mb-1.5">{t('notif.pattern.whyLabel')}</div>
        <textarea
          value={why}
          onChange={e => setWhy(e.target.value)}
          placeholder={t('notif.pattern.whyPlaceholder')}
          rows={2}
          className="w-full text-[13px] text-ink border border-line rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#3465E3]/20 focus:border-[#3465E3]"/>
        <div className="flex items-center justify-end gap-2 mt-3">
          <button onClick={() => setPendingAction(null)} className="text-[12px] text-ink-muted hover:text-ink px-2 py-1">{t('notif.pattern.back')}</button>
          <button
            onClick={() => { pendingAction === 'confirm' ? onConfirm(pattern.id, why) : onReject(pattern.id, why); }}
            className="px-3 py-1.5 text-[12px] font-medium rounded-md bg-[#0B0F19] text-white hover:bg-[#1a2033] transition-colors">
            {t('notif.pattern.saveAndClose')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="p-4 rounded-lg border fade-in relative" style={{borderColor:'#E4D9F7', background:'linear-gradient(180deg, #FBF8FF 0%, #FFFFFF 100%)'}}>
      <button onClick={onDismiss} className="absolute top-2.5 right-2.5 w-6 h-6 rounded hover:bg-white/60 flex items-center justify-center text-ink-soft hover:text-ink-muted">
        <Icon.X size={12}/>
      </button>
      <div className="flex items-center gap-2 mb-2">
        <span className="inline-flex items-center gap-1 text-[11px] font-medium px-2 py-0.5 rounded-full" style={{background:'#EFECFB', color:'#6B5ED6'}}>
          <Icon.Brain size={11}/>{t('notif.pattern.badge')}
        </span>
        <span className="text-[11px] text-ink-soft">{t('notif.pattern.needsConfirm')}</span>
      </div>
      <div className="text-[14px] text-ink leading-snug font-medium pr-6">„{pattern.text}"</div>
      <div className="text-[12px] text-ink-muted mt-1.5 leading-snug">{pattern.evidence}</div>
      <div className="flex items-center gap-2 mt-3">
        <button
          onClick={() => setPendingAction('confirm')}
          className="px-3 py-1.5 text-[12px] font-medium rounded-md text-white transition-colors inline-flex items-center gap-1.5"
          style={{background:'#0E7E4E'}}>
          <Icon.Check size={12}/>{t('notif.pattern.yes')}
        </button>
        <button
          onClick={() => setPendingAction('reject')}
          className="px-3 py-1.5 text-[12px] font-medium rounded-md border border-line text-ink-muted hover:bg-gray-50 transition-colors inline-flex items-center gap-1.5">
          <Icon.X size={12}/>{t('notif.pattern.no')}
        </button>
      </div>
    </div>
  );
}

// Tiny warn icon + bell icon additions (append to Icon if not there yet)
(function extendIcons(){
  if (!window.Icon) return;
  if (!Icon.Bell) {
    Icon.Bell = (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>;
  }
  if (!Icon.Warn) {
    Icon.Warn = (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>;
  }
  if (!Icon.Info) {
    Icon.Info = (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>;
  }
  if (!Icon.User) {
    Icon.User = (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
  }
  if (!Icon.X) {
    Icon.X = (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>;
  }
  if (!Icon.Check) {
    Icon.Check = (p) => <svg width={p.size||16} height={p.size||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...p}><polyline points="20 6 9 17 4 12"/></svg>;
  }
})();

Object.assign(window, {
  buildNotifications,
  NotifBell,
  DashboardNotifBanner,
  PatternConfirmCard,
  NotifKindBadge,
  NotifIcon,
});
