// AI Chat Bubble — "Cortex Assistent"
// A proactive 24/7 companion for the Leadscraper system.
// - Watches user's profiles and surfaces insights (unconfirmed patterns, edge cases)
// - Helps compose better search queries
// - Uses window.claude.complete for real answers, grounded in user's data
//
// Design: Intercom-style panel, bottom-right, clean and quiet.
// Only mounted in app shell (after login).

// --- Icons (small set, additive to global Icon) -------------------------
(function extendAIIcons() {
  if (!window.Icon) return;
  if (!Icon.Sparkle) {
    Icon.Sparkle = (p) => (
      <svg width={p.size||14} height={p.size||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
        <path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/>
      </svg>
    );
  }
  if (!Icon.Send) {
    Icon.Send = (p) => (
      <svg width={p.size||14} height={p.size||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
        <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
      </svg>
    );
  }
  if (!Icon.Min) {
    Icon.Min = (p) => (
      <svg width={p.size||14} height={p.size||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}>
        <line x1="5" y1="12" x2="19" y2="12"/>
      </svg>
    );
  }
  if (!Icon.Chat) {
    Icon.Chat = (p) => (
      <svg width={p.size||20} height={p.size||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
        <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
      </svg>
    );
  }
})();

// --- Avatar gradient bubble --------------------------------------------
function AvatarCortex({ size = 28, pulse = false }) {
  return (
    <div
      className="relative rounded-full flex items-center justify-center flex-shrink-0"
      style={{
        width: size, height: size,
        background: 'linear-gradient(135deg, #3465E3 0%, #8B5CF6 55%, #EC4899 100%)',
        boxShadow: '0 2px 8px rgba(52,101,227,0.28), inset 0 1px 1px rgba(255,255,255,0.35)'
      }}>
      <svg width={size*0.55} height={size*0.55} viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/>
      </svg>
      {pulse && (
        <span className="absolute -bottom-0.5 -right-0.5 w-[9px] h-[9px] rounded-full bg-emerald-400 ring-2 ring-white"/>
      )}
    </div>
  );
}

// --- Typing indicator ---------------------------------------------------
function TypingDots() {
  return (
    <div className="flex items-center gap-1 py-2 px-3">
      <span className="w-1.5 h-1.5 rounded-full bg-ink-soft animate-bounce" style={{animationDelay:'0ms'}}/>
      <span className="w-1.5 h-1.5 rounded-full bg-ink-soft animate-bounce" style={{animationDelay:'120ms'}}/>
      <span className="w-1.5 h-1.5 rounded-full bg-ink-soft animate-bounce" style={{animationDelay:'240ms'}}/>
    </div>
  );
}

// --- Build proactive insights based on profile state -------------------
function buildProactiveInsights(profiles, feedbackByProfile) {
  const out = [];
  for (const p of profiles) {
    const unconfirmed = (p.memory || []).find(m => !m.confirmed && (m.strength === 'medium' || m.strength === 'strong') && !m.uncertain);
    if (unconfirmed) {
      out.push({
        id: `pat-${p.id}-${unconfirmed.id}`,
        profileId: p.id,
        kind: 'pattern',
        title: t('ai.ins.pattern.title', { profile: p.short }),
        body: unconfirmed.text,
        cta: t('ai.ins.pattern.cta'),
        target: 'memory',
      });
    }
    if (p.matchRateNow < 0.55 && p.feedbackCount < 150) {
      out.push({
        id: `low-${p.id}`,
        profileId: p.id,
        kind: 'tune',
        title: t('ai.ins.tune.title', { profile: p.short }),
        body: t('ai.ins.tune.body', { rate: Math.round(p.matchRateNow*100) }),
        cta: t('ai.ins.tune.cta'),
        target: 'refine',
      });
    }
    const edge = (p.leads || []).find(l => l.score === 'unsicher' && l.isNew);
    if (edge) {
      out.push({
        id: `edge-${p.id}-${edge.id}`,
        profileId: p.id,
        kind: 'edge',
        title: t('ai.ins.edge.title', { company: edge.company }),
        body: edge.uncertainty || t('ai.ins.edge.fallback'),
        cta: t('ai.ins.edge.cta'),
        target: 'lead',
        leadId: edge.id,
      });
    }
  }
  return out.slice(0, 4);
}

// --- Context builder for Claude -----------------------------------------
function buildAIContext(profiles, activeProfileId) {
  const active = profiles.find(p => p.id === activeProfileId) || profiles[0];
  const lang = (window.LangStore && window.LangStore.get()) || 'de';
  const isEn = lang === 'en';
  const tag = (m) => {
    if (m.confirmed) return isEn ? 'confirmed' : 'bestätigt';
    if (m.uncertain) return isEn ? 'uncertain' : 'unsicher';
    return isEn ? 'unconfirmed' : 'unbestätigt';
  };
  const profilesSummary = profiles.map(p => {
    const patterns = (p.memory || []).map(m =>
      `  • [${m.strength}, ${tag(m)}] ${m.text}`
    ).join('\n');
    if (isEn) {
      return `Profile "${p.name}" (${p.query})
- ${p.feedbackCount} feedbacks, ${p.acceptedCount} accepted, ${p.rejectedCount} rejected
- Match rate: ${Math.round(p.matchRateStart*100)} % → ${Math.round(p.matchRateNow*100)} %
- Learned patterns:
${patterns || '  (none yet)'}`;
    }
    return `Profil "${p.name}" (${p.query})
- ${p.feedbackCount} Feedbacks, ${p.acceptedCount} Annahmen, ${p.rejectedCount} Ablehnungen
- Match-Rate: ${Math.round(p.matchRateStart*100)} % → ${Math.round(p.matchRateNow*100)} %
- Gelernte Muster:
${patterns || '  (noch keine)'}`;
  }).join('\n\n');

  if (isEn) {
    return `You are "Cortex Assistant", the 24/7 AI companion inside the Leadscraper system. Leadscraper is a B2B lead-generation tool that learns from user feedback which companies match the customer profile.

Your role:
- Help the user formulate more precise search runs (industry, location, size, contact persona, extras)
- Explain what the system has learned and why specific leads are shown
- Recommend which patterns should be confirmed next
- Be proactive but concise. Write like a competent sales-ops colleague — friendly, direct, precise. Never fluffy.
- ${t('ai.langHint')}
- When you suggest concrete queries, format them as a list with industry/location/size/extras.
- Do not invent company names or numbers that aren't in the context.

Current user context:

${profilesSummary}

Active profile: "${active.name}"`;
  }

  return `Du bist "Cortex Assistent", der 24/7-KI-Companion im Leadscraper-System. Leadscraper ist ein B2B-Lead-Generation-Tool, das aus Nutzer-Feedback lernt, welche Unternehmen zum Kundenprofil passen.

Deine Rolle:
- Hilf dem Nutzer, präzisere Suchläufe zu formulieren (Branche, Standort, Größe, Ansprechpartner, Extras)
- Erkläre, was das System gerade gelernt hat, und warum bestimmte Leads gezeigt werden
- Empfiehl, welche Muster bestätigt werden sollten
- Sei proaktiv, aber knapp. Schreib wie ein kompetenter Sales-Ops-Kollege — freundlich, direkt, präzise. Nie floskelhaft.
- ${t('ai.langHint')}
- Wenn du konkrete Query-Vorschläge machst, formatiere sie als Liste mit Branche/Standort/Größe/Extras.
- Erfinde keine Unternehmensnamen oder Zahlen, die nicht im Kontext stehen.

Aktueller Nutzerkontext:

${profilesSummary}

Aktives Profil: "${active.name}"`;
}

// --- Quick starter prompts ---------------------------------------------
const STARTER_PROMPT_KEYS = [
  { labelKey: 'ai.sp1.label', promptKey: 'ai.sp1.prompt' },
  { labelKey: 'ai.sp2.label', promptKey: 'ai.sp2.prompt' },
  { labelKey: 'ai.sp3.label', promptKey: 'ai.sp3.prompt' },
  { labelKey: 'ai.sp4.label', promptKey: 'ai.sp4.prompt' },
];

// --- Main component -----------------------------------------------------
function AIAssistant({ profiles, activeProfileId, feedbackByProfile, onGoTo }) {
  useLang();
  // State: 'closed' (just ball) · 'peek' (teaser card) · 'open' (full chat)
  const [state, setState] = useState('closed');
  const [messages, setMessages] = useState([]); // { role, content, id }
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [dismissedInsights, setDismissedInsights] = useState(new Set());
  const [unread, setUnread] = useState(0);
  const threadRef = useRef(null);

  const insights = useMemo(
    () => buildProactiveInsights(profiles, feedbackByProfile).filter(i => !dismissedInsights.has(i.id)),
    [profiles, feedbackByProfile, dismissedInsights]
  );

  // Unread counter: insights while not yet seen
  useEffect(() => {
    if (state === 'open') { setUnread(0); return; }
    if (state === 'peek') { setUnread(0); return; } // seen
    setUnread(insights.length);
  }, [insights.length, state]);

  // Scroll to bottom on new message
  useEffect(() => {
    if (threadRef.current) {
      threadRef.current.scrollTop = threadRef.current.scrollHeight;
    }
  }, [messages, sending]);

  const send = async (text) => {
    const q = (text || input).trim();
    if (!q || sending) return;
    setInput('');
    const userMsg = { id: `u-${Date.now()}`, role: 'user', content: q };
    const history = [...messages, userMsg];
    setMessages(history);
    setSending(true);
    try {
      const system = buildAIContext(profiles, activeProfileId);
      const claudeMessages = [
        ...history.map(m => ({ role: m.role, content: m.content }))
      ];
      const reply = await window.claude.complete({
        system,
        messages: claudeMessages,
      });
      setMessages(prev => [...prev, { id: `a-${Date.now()}`, role: 'assistant', content: reply }]);
    } catch (e) {
      setMessages(prev => [...prev, {
        id: `a-${Date.now()}`, role: 'assistant',
        content: t('ai.errorReply')
      }]);
    } finally {
      setSending(false);
    }
  };

  const handleInsightAction = (ins) => {
    if (!onGoTo) return;
    if (ins.target === 'memory') onGoTo({ tab: 'memory', profileId: ins.profileId });
    else if (ins.target === 'refine') {
      // Seed a conversation
      setState('open');
      setDismissedInsights(s => new Set([...s, ins.id]));
      send(t('ai.seedRefine', { profile: profiles.find(p=>p.id===ins.profileId)?.short }));
    } else if (ins.target === 'lead') {
      onGoTo({ tab: 'results', profileId: ins.profileId });
    }
  };

  // ----------------------------------------------------------------------
  // Closed / Peek state — floating bubble (+ optional teaser card)
  // ----------------------------------------------------------------------
  if (state !== 'open') {
    const showPeek = state === 'peek' && insights.length > 0 && messages.length === 0;
    return (
      <>
        {/* Teaser card — only when state === 'peek' */}
        {showPeek && (
          <div
            className="fixed z-[45] bottom-[94px] right-5 w-[300px] bg-white rounded-2xl fade-in cortex-peek overflow-hidden"
            style={{
              boxShadow: '0 12px 40px -8px rgba(15,23,42,0.22), 0 2px 8px -2px rgba(15,23,42,0.08)',
              border: '1px solid rgba(15,23,42,0.06)',
            }}>
            <button
              onClick={(e) => { e.stopPropagation(); setState('closed'); }}
              className="absolute top-2.5 right-2.5 w-6 h-6 rounded-md hover:bg-gray-100 text-ink-soft hover:text-ink-muted flex items-center justify-center z-10"
              title={t('ai.collapse')}>
              <Icon.X size={11}/>
            </button>
            <button
              onClick={() => setState('open')}
              className="w-full text-left p-3.5 hover:bg-gray-50/60 transition-colors">
              <div className="flex items-start gap-2.5 pr-5">
                <AvatarCortex size={28} pulse/>
                <div className="flex-1 min-w-0">
                  <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('ai.cortex')}</div>
                  <div className="text-[13px] text-ink font-medium mt-0.5 leading-snug">{insights[0].title}</div>
                  <div className="text-[12px] text-ink-muted mt-1 leading-snug line-clamp-2">{insights[0].body}</div>
                </div>
              </div>
              <div className="mt-2.5 pt-2.5 flex items-center justify-between text-[11.5px] text-[#3465E3] font-medium"
                   style={{borderTop:'1px solid rgba(15,23,42,0.05)'}}>
                <span className="inline-flex items-center gap-1">
                  {t('ai.openChat')} <Icon.ChevRight size={11}/>
                </span>
                {insights.length > 1 && (
                  <span className="text-[11px] text-ink-soft font-normal">{t('ai.moreN', { n: insights.length - 1 })}</span>
                )}
              </div>
            </button>
          </div>
        )}

        <button
          onClick={() => {
            // Ball click: if we have insights → show peek; else jump straight to chat
            if (insights.length > 0 && messages.length === 0 && state === 'closed') {
              setState('peek');
            } else {
              setState('open');
            }
          }}
          className="fixed z-[46] bottom-5 right-5 w-[56px] h-[56px] rounded-full flex items-center justify-center text-white cortex-fab"
          style={{
            background: 'linear-gradient(135deg, #3465E3 0%, #8B5CF6 55%, #EC4899 100%)',
            boxShadow: '0 10px 28px -6px rgba(52,101,227,0.5), 0 4px 12px -2px rgba(139,92,246,0.3), inset 0 1px 1px rgba(255,255,255,0.3)'
          }}
          title={t('ai.cortex')}>
          <Icon.Sparkle size={22}/>
          {unread > 0 && state === 'closed' && (
            <span className="absolute -top-1 -right-1 min-w-[20px] h-[20px] px-1.5 rounded-full bg-white text-[11px] font-semibold tabular-nums flex items-center justify-center ring-2"
                  style={{color:'#3465E3', ringColor:'rgba(52,101,227,0.25)'}}>
              {unread}
            </span>
          )}
        </button>
      </>
    );
  }

  // ----------------------------------------------------------------------
  // Open state — panel
  // ----------------------------------------------------------------------
  const activeProfile = profiles.find(p => p.id === activeProfileId) || profiles[0];

  return (
    <div
      className="cortex-panel fixed z-[46] bg-white overflow-hidden flex flex-col fade-in"
      style={{
        boxShadow: '0 24px 64px -16px rgba(15,23,42,0.28), 0 4px 12px -2px rgba(15,23,42,0.08)',
        border: '1px solid rgba(15,23,42,0.06)',
      }}>
      {/* Header */}
      <div
        className="relative px-4 pt-4 pb-3.5 text-white flex-shrink-0"
        style={{background: 'linear-gradient(135deg, #3465E3 0%, #6D4FE6 55%, #8B5CF6 100%)'}}>
        <div className="flex items-start justify-between gap-3">
          <div className="flex items-center gap-2.5 min-w-0">
            <AvatarCortex size={32} pulse/>
            <div className="min-w-0">
              <div className="text-[14px] font-semibold leading-tight">{t('ai.cortex')}</div>
              <div className="text-[11.5px] text-white/75 leading-tight mt-0.5 flex items-center gap-1.5">
                <span className="w-1.5 h-1.5 rounded-full bg-emerald-300"/>
                {t('ai.onlinePrefix', { n: profiles.length })}
              </div>
            </div>
          </div>
          <button
            onClick={() => setState(insights.length > 0 && messages.length === 0 ? 'peek' : 'closed')}
            className="w-7 h-7 rounded-md hover:bg-white/15 flex items-center justify-center text-white/85 hover:text-white transition-colors"
            title={t('ai.collapse')}>
            <Icon.Min size={14}/>
          </button>
        </div>
        <div className="text-[12px] text-white/80 mt-2.5 leading-snug">
          {t('ai.intro')}
        </div>
      </div>

      {/* Thread */}
      <div ref={threadRef} className="flex-1 overflow-y-auto bg-[#FAFBFC]">
        {/* Cold start — greeting + insights + starters */}
        {messages.length === 0 && (
          <div className="p-4 space-y-3.5">
            <div className="flex items-start gap-2">
              <AvatarCortex size={26}/>
              <div className="flex-1">
                <div className="text-[11px] text-ink-soft font-medium mb-1">{t('ai.cortex')} · {t('ai.now')}</div>
                <div className="bg-white rounded-xl rounded-tl-md px-3.5 py-2.5 text-[13.5px] text-ink leading-[1.55]"
                     style={{border:'1px solid rgba(15,23,42,0.06)', boxShadow:'0 1px 2px rgba(15,23,42,0.03)'}}>
                  {t('ai.greeting', { profile: activeProfile.short })}
                </div>
              </div>
            </div>

            {/* Proactive insights */}
            {insights.length > 0 && (
              <div className="pl-9 space-y-2">
                <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium">{t('ai.thinkingAbout')}</div>
                {insights.map(ins => (
                  <div key={ins.id}
                       className="bg-white rounded-xl p-3 relative"
                       style={{border:'1px solid rgba(15,23,42,0.06)', boxShadow:'0 1px 2px rgba(15,23,42,0.03)'}}>
                    <button
                      onClick={() => setDismissedInsights(s => new Set([...s, ins.id]))}
                      className="absolute top-2 right-2 w-5 h-5 rounded hover:bg-gray-100 text-ink-soft hover:text-ink-muted flex items-center justify-center"
                      title={t('ai.dismiss')}>
                      <Icon.X size={10}/>
                    </button>
                    <div className="flex items-center gap-1.5 mb-1 pr-6">
                      <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${ins.kind === 'pattern' ? 'bg-[#8B5CF6]' : ins.kind === 'edge' ? 'bg-amber-400' : 'bg-[#3465E3]'}`}/>
                      <span className="text-[11px] font-medium text-ink-muted truncate">{ins.title}</span>
                    </div>
                    <div className="text-[12.5px] text-ink-muted leading-snug">{ins.body}</div>
                    <button
                      onClick={() => handleInsightAction(ins)}
                      className="mt-2 text-[12px] font-medium text-[#3465E3] hover:underline inline-flex items-center gap-1">
                      {ins.cta} <Icon.ChevRight size={10}/>
                    </button>
                  </div>
                ))}
              </div>
            )}

            {/* Starter prompts */}
            <div className="pl-9 space-y-1.5">
              <div className="text-[11px] uppercase tracking-[0.08em] text-ink-soft font-medium pt-1">{t('ai.quickStart')}</div>
              {STARTER_PROMPT_KEYS.map((s, i) => (
                <button
                  key={i}
                  onClick={() => send(t(s.promptKey))}
                  className="w-full text-left text-[12.5px] text-ink-muted hover:text-ink bg-white hover:bg-gray-50 rounded-lg px-3 py-2 transition-colors"
                  style={{border:'1px solid rgba(15,23,42,0.06)'}}>
                  {t(s.labelKey)}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Active thread */}
        {messages.length > 0 && (
          <div className="p-4 space-y-3">
            {messages.map(m => (
              <div key={m.id} className={`flex items-start gap-2 ${m.role === 'user' ? 'flex-row-reverse' : ''}`}>
                {m.role === 'assistant' && <AvatarCortex size={26}/>}
                <div className={`max-w-[82%] ${m.role === 'user' ? 'bg-[#3465E3] text-white rounded-xl rounded-tr-md' : 'bg-white text-ink rounded-xl rounded-tl-md'} px-3.5 py-2.5 text-[13.5px] leading-[1.55] whitespace-pre-wrap`}
                     style={m.role === 'assistant' ? {border:'1px solid rgba(15,23,42,0.06)', boxShadow:'0 1px 2px rgba(15,23,42,0.03)'} : {}}>
                  {m.content}
                </div>
              </div>
            ))}
            {sending && (
              <div className="flex items-start gap-2">
                <AvatarCortex size={26}/>
                <div className="bg-white rounded-xl rounded-tl-md"
                     style={{border:'1px solid rgba(15,23,42,0.06)'}}>
                  <TypingDots/>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Input */}
      <div className="p-3 bg-white flex-shrink-0" style={{borderTop:'1px solid rgba(15,23,42,0.06)'}}>
        <div className="flex items-end gap-2 bg-[#F4F6F9] rounded-xl px-3 py-2"
             style={{border:'1px solid rgba(15,23,42,0.04)'}}>
          <textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
            }}
            placeholder={t('ai.inputP')}
            rows={1}
            className="flex-1 bg-transparent border-0 outline-none resize-none text-[13.5px] text-ink placeholder:text-ink-soft max-h-[120px] leading-[1.5] py-1"
          />
          <button
            onClick={() => send()}
            disabled={sending || !input.trim()}
            className="w-8 h-8 rounded-lg flex items-center justify-center text-white transition-all flex-shrink-0"
            style={{
              background: input.trim() && !sending
                ? 'linear-gradient(135deg, #3465E3 0%, #8B5CF6 100%)'
                : '#CBD3E0',
              opacity: input.trim() && !sending ? 1 : 0.7
            }}
            title={t('ai.send')}>
            <Icon.Send size={13}/>
          </button>
        </div>
        <div className="text-[10.5px] text-ink-soft text-center mt-2">
          {t('ai.footer')}
        </div>
      </div>
    </div>
  );
}

// Expose globally
window.AIAssistant = AIAssistant;
