// Training-Progress-Ring — füllt sich je nach Trefferquote,
// Farbe interpoliert grau → blau → grün
function TrainingRing({ rate = 0, size = 22, active = false }) {
  const stroke = 2;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const offset = c - c * rate;
  // Color mix: <35% muted, 35–65% brand blue, >65% emerald
  const color = rate >= 0.65 ? '#10B981' : rate >= 0.35 ? '#3465E3' : '#94A3B8';
  const trackColor = '#E6ECF5';
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="flex-shrink-0">
      <circle cx={size/2} cy={size/2} r={r} stroke={trackColor} strokeWidth={stroke} fill="none"/>
      <circle
        cx={size/2} cy={size/2} r={r}
        stroke={color} strokeWidth={stroke} fill="none"
        strokeLinecap="round"
        strokeDasharray={c}
        strokeDashoffset={offset}
        transform={`rotate(-90 ${size/2} ${size/2})`}
        style={{ transition: 'stroke-dashoffset .4s ease, stroke .3s ease' }}
      />
      {active && (
        <circle cx={size/2} cy={size/2} r={2.2} fill={color}/>
      )}
    </svg>
  );
}

// NavHeader — logo, nav tabs, credits, CTA, language switch, profile switcher
function LanguageSwitch() {
  const lang = useLang();
  return (
    <div className="inline-flex items-center rounded-md border border-line overflow-hidden h-[28px] text-[11.5px] font-medium">
      {['de','en'].map(l => (
        <button key={l}
          onClick={() => LangStore.set(l)}
          className={`px-2.5 h-full transition-colors ${
            lang === l ? 'bg-[#0B0F19] text-white' : 'bg-white text-ink-muted hover:text-ink'
          }`}>
          {l.toUpperCase()}
        </button>
      ))}
    </div>
  );
}

function NavHeader({ profile, profiles, onSwitchProfile, onCreateProfile, tab, onTab, credits = 142, notifItems = [], notifDismissed, onNotifAct, onNotifDismiss, notifRead, onNotifMarkRead, accountStatus = 'subscribed', trialCreditsLeft = 0, trialCreditsTotal = 0, currentPlan, onOpenPricing }) {
  useLang(); // re-render on lang change
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);

  const tabs = [
    { id: 'dashboard', label: t('nav.dashboard') },
    { id: 'results',   label: t('nav.leads') },
    { id: 'memory',    label: t('nav.cortex') },
  ];

  return (
    <div className="bg-white border-b border-line">
      {/* Row 1 */}
      <div className="px-6 h-[60px] flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button onClick={() => onTab('dashboard')} className="focus:outline-none flex items-center">
            <img src="./logo-blue.svg" alt="LeadScraper" className="h-8 w-auto"/>
          </button>
        </div>

        <nav className="flex gap-1 items-center">
          {tabs.map(tb => {
            const active = tab === tb.id || (tb.id === 'results' && tab === 'detail');
            return (
              <button key={tb.id} onClick={() => onTab(tb.id)}
                className={`px-4 py-1.5 text-[14px] font-medium rounded-md transition-colors whitespace-nowrap ${
                  active ? 'bg-[#EEF2FE] text-[#3465E3]' : 'text-ink-muted hover:text-ink'
                }`}>
                {tb.label}
              </button>
            );
          })}
        </nav>

        <div className="flex items-center gap-3">
          <LanguageSwitch/>
          <NotifBell
            items={notifItems}
            dismissedIds={notifDismissed || new Set()}
            onAct={onNotifAct}
            onDismiss={onNotifDismiss}
            readIds={notifRead || new Set()}
            onMarkRead={onNotifMarkRead}/>
          <div className="hidden lg:flex items-center gap-2 rounded-full px-4 py-1.5 bg-[#F4F7FD]">
            <span className="text-[13px] font-medium text-ink">{t('nav.credits')}</span>
            {accountStatus === 'trial' ? (
              <span className="inline-flex items-center justify-center min-w-[24px] px-2 h-5 rounded-full bg-ink text-white text-[11px] font-semibold tabular-nums">
                {trialCreditsLeft}/{trialCreditsTotal}
              </span>
            ) : (
              <span className="inline-flex items-center justify-center min-w-[24px] px-2 h-5 rounded-full bg-[#3465E3] text-white text-[11px] font-semibold">{credits}</span>
            )}
          </div>
          <button onClick={() => onOpenPricing && onOpenPricing(accountStatus === 'trial' ? 'sub' : 'oneoff')}
                  className="btn-brand text-[13px] whitespace-nowrap">
            {accountStatus === 'trial' ? 'Abo starten' : t('nav.buyLeads')}
          </button>
          <AvatarMenu onOpenAccount={() => onTab('account')}/>
        </div>
      </div>

      {/* Row 2: Active profile */}
      <div className={`px-6 pb-3 pt-2 border-t border-[#F0F4FA] flex items-center gap-3 bg-[#FAFCFF] ${tab === 'account' ? 'hidden' : ''}`}>
        <span className="text-[11px] font-medium uppercase tracking-[0.08em] text-ink-soft">{t('nav.activeProfile')}</span>
        <div className="relative" ref={ref}>
          <button onClick={() => setOpen(o => !o)}
            className="flex items-center gap-2.5 pl-2 pr-3 py-1.5 rounded-md border border-line hover:bg-gray-50">
            <div className="w-6 h-6 rounded flex items-center justify-center text-[11px] font-semibold bg-brand-50 text-brand-500">{profile.initial}</div>
            <div className="text-left leading-tight">
              <div className="text-sm font-medium text-ink">{profile.name}</div>
              <div className="text-[11px] text-ink-muted">{profile.feedbackCount} {t('nav.feedbacks')} · {Math.round(profile.matchRateNow*100)} % {t('nav.matchRate')}</div>
            </div>
            <Icon.ChevDown size={14} className="text-ink-muted"/>
          </button>
          {open && (
            <div className="absolute top-full mt-1 left-0 w-[420px] bg-white border border-line rounded-lg shadow-xl z-40 fade-in overflow-hidden">
              <div className="px-3 pt-3 pb-1 text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('nav.switchProfiles')}</div>
              {profiles.map(p => (
                <button key={p.id} onClick={() => { onSwitchProfile(p.id); setOpen(false); }}
                  className={`w-full text-left px-3 py-2.5 flex items-center gap-3 hover:bg-gray-50 ${p.id === profile.id ? 'bg-brand-50/40' : ''}`}>
                  <div className={`w-7 h-7 rounded flex items-center justify-center text-[12px] font-semibold ${p.id===profile.id ? 'bg-brand-500 text-white':'bg-gray-100 text-ink'}`}>{p.initial}</div>
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-ink truncate">{p.name}</div>
                    <div className="text-[12px] text-ink-muted truncate">{p.query}</div>
                  </div>
                  <div className="text-right">
                    <div className="text-[13px] font-medium text-ink">{Math.round(p.matchRateNow*100)} %</div>
                    <div className="text-[10px] text-ink-soft">{p.feedbackCount} {t('nav.feedbacks')}</div>
                  </div>
                  {p.id === profile.id
                    ? <TrainingRing rate={p.matchRateNow} active/>
                    : <TrainingRing rate={p.matchRateNow}/>
                  }
                </button>
              ))}
              <div className="hair"/>
              <button onClick={onCreateProfile} className="w-full flex items-center gap-2 px-3 py-2.5 text-sm text-ink-muted hover:bg-gray-50">
                <Icon.Plus size={14}/> {t('nav.newProfile')}
              </button>
            </div>
          )}
        </div>
        <span className="text-[12px] text-ink-soft truncate min-w-0 flex-1">{profile.query}</span>
      </div>
    </div>
  );
}

Object.assign(window, { NavHeader, LanguageSwitch, TrainingRing });

// --- Avatar menu dropdown ------------------------------------------------
function AvatarMenu({ onOpenAccount }) {
  useLang();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen(o => !o)}
              className="w-8 h-8 rounded-full flex items-center justify-center text-[11px] font-semibold text-white hover:scale-[1.05] transition-transform"
              style={{background:'linear-gradient(135deg, #3465E3 0%, #6D4FE6 55%, #8B5CF6 100%)'}}>
        JD
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-1.5 w-[220px] bg-white border border-line rounded-lg shadow-xl z-40 fade-in overflow-hidden">
          <div className="px-3 py-3 border-b border-[#F0F4FA]">
            <div className="text-[13px] font-semibold text-ink leading-tight">Janik Deimann</div>
            <div className="text-[11.5px] text-ink-muted mt-0.5 truncate">janik.dmann@gmail.com</div>
          </div>
          <button onClick={() => { setOpen(false); onOpenAccount && onOpenAccount(); }}
                  className="w-full text-left flex items-center gap-2 px-3 py-2 text-[13px] text-ink hover:bg-gray-50 transition-colors">
            <Icon.User size={13} className="text-ink-soft"/> {t('acct.menu.settings')}
          </button>
          <div className="border-t border-[#F0F4FA]"/>
          <button className="w-full text-left flex items-center gap-2 px-3 py-2 text-[13px] text-ink-muted hover:bg-gray-50 transition-colors">
            <Icon.X size={13} className="text-ink-soft"/> {t('acct.menu.logout')}
          </button>
        </div>
      )}
    </div>
  );
}
