/**
 * CoPilotPanel — AI Co-Pilot Rechts-Panel
 * 
 * Kommando-Eingabe, Vorschläge, LLM-Integration
 * Width: 320px, fixed right
 */

import { useState, useRef, useEffect } from 'react';
import { X, Send, Sparkles, Zap, FileEdit, Calendar, Package } from 'lucide-react';

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: Date;
}

const SUGGESTED_COMMANDS = [
  { icon: FileEdit, label: 'Draft für pit_001 erstellen', cmd: 'Erstelle einen LinkedIn-Draft für Shelly Plus Plug S mit Affiliate-UTM-Link' },
  { icon: Zap, label: 'Signal analysieren', cmd: 'Analysiere die aktuellen Signale und schlage 3 Post-Ideen vor' },
  { icon: Calendar, label: 'Wochenplan erstellen', cmd: 'Erstelle einen optimalen Posting-Plan für diese Woche' },
  { icon: Package, label: 'Produkt-Post', cmd: 'Schreibe einen Instagram-Post für das beste Produkt im Katalog' },
];

interface CoPilotPanelProps {
  onClose: () => void;
}

export function CoPilotPanel({ onClose }: CoPilotPanelProps) {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '0',
      role: 'assistant',
      content: 'ATLAS Co-Pilot bereit. Ich helfe dir mit Drafts, Kampagnen, Signalanalyse und Content-Planung. Was soll ich tun?',
      timestamp: new Date(),
    }
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const sendMessage = async (text: string) => {
    if (!text.trim() || loading) return;
    
    const userMsg: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: text.trim(),
      timestamp: new Date(),
    };
    
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setLoading(true);
    
    try {
      // Call built-in LLM via Manus proxy
      const res = await fetch(import.meta.env.VITE_FRONTEND_FORGE_API_URL || 'https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${import.meta.env.VITE_FRONTEND_FORGE_API_KEY || ''}`,
        },
        body: JSON.stringify({
          model: 'gpt-4o-mini',
          messages: [
            {
              role: 'system',
              content: `Du bist ATLAS Co-Pilot, ein AI-Assistent für Social Media Content-Erstellung und -Management.
              
Du hilfst Torsten Hiss (hiss@clara360.de) beim:
- Erstellen von Social Media Drafts (LinkedIn, Instagram, TikTok)
- Analysieren von Signalen und Trends
- Planen von Content-Kalendern
- Optimieren von Affiliate-Links (UTM-Tracking)
- Verwalten des Produktkatalogs (catalog.json)

Kontext:
- Postiz ist die Publishing-Engine (postiz.atlas-os.ai)
- Produkte kommen aus catalog.json (search.atlas-os.ai/catalog.json)
- Aktuelles Hauptprodukt: Shelly Plus Plug S (pit_001)
- Affiliate-Regel: display_status=active nur wenn program_status=approved

Antworte präzise, direkt und auf Deutsch. Keine Floskeln.`,
            },
            ...messages.slice(-10).map(m => ({ role: m.role, content: m.content })),
            { role: 'user', content: text.trim() },
          ],
          max_tokens: 500,
          temperature: 0.7,
        }),
      });
      
      if (res.ok) {
        const data = await res.json();
        const reply = data.choices?.[0]?.message?.content || 'Keine Antwort erhalten.';
        
        setMessages(prev => [...prev, {
          id: Date.now().toString(),
          role: 'assistant',
          content: reply,
          timestamp: new Date(),
        }]);
      } else {
        throw new Error(`HTTP ${res.status}`);
      }
    } catch {
      // Fallback response
      setMessages(prev => [...prev, {
        id: Date.now().toString(),
        role: 'assistant',
        content: getFallbackResponse(text),
        timestamp: new Date(),
      }]);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage(input);
    }
  };

  return (
    <aside
      className="flex flex-col flex-shrink-0 animate-slide-in-right"
      style={{
        width: '320px',
        background: 'var(--atlas-surface)',
        borderLeft: '1px solid var(--atlas-border)',
      }}
    >
      {/* Header */}
      <div 
        className="flex items-center justify-between px-4 py-3 flex-shrink-0"
        style={{ borderBottom: '1px solid var(--atlas-border)' }}
      >
        <div className="flex items-center gap-2">
          <div 
            className="flex items-center justify-center rounded"
            style={{
              width: '24px',
              height: '24px',
              background: 'oklch(0.82 0.18 210 / 0.12)',
              border: '1px solid oklch(0.82 0.18 210 / 0.25)',
            }}
          >
            <Sparkles size={12} style={{ color: 'var(--atlas-cyan)' }} />
          </div>
          <span 
            className="text-sm font-semibold"
            style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}
          >
            Co-Pilot
          </span>
          <span className="atlas-badge-cyan">AI</span>
        </div>
        <button
          onClick={onClose}
          className="p-1 rounded transition-colors"
          style={{ color: 'var(--muted-foreground)' }}
          onMouseEnter={e => (e.currentTarget.style.color = 'var(--foreground)')}
          onMouseLeave={e => (e.currentTarget.style.color = 'var(--muted-foreground)')}
        >
          <X size={14} />
        </button>
      </div>
      
      {/* Suggested Commands */}
      <div 
        className="px-3 py-2 flex-shrink-0"
        style={{ borderBottom: '1px solid var(--atlas-border)' }}
      >
        <div 
          className="text-xs mb-2"
          style={{ 
            fontFamily: 'var(--font-mono)',
            color: 'var(--muted-foreground)',
            fontSize: '0.625rem',
            letterSpacing: '0.08em',
            textTransform: 'uppercase'
          }}
        >
          Schnellbefehle
        </div>
        <div className="grid grid-cols-2 gap-1">
          {SUGGESTED_COMMANDS.map((cmd, i) => {
            const Icon = cmd.icon;
            return (
              <button
                key={i}
                onClick={() => sendMessage(cmd.cmd)}
                className="flex items-center gap-1.5 px-2 py-1.5 rounded text-left transition-all"
                style={{
                  background: 'var(--atlas-navy)',
                  border: '1px solid var(--atlas-border)',
                  color: 'var(--muted-foreground)',
                  fontSize: '0.6875rem',
                  fontFamily: 'var(--font-body)',
                }}
                onMouseEnter={e => {
                  e.currentTarget.style.borderColor = 'oklch(0.82 0.18 210 / 0.3)';
                  e.currentTarget.style.color = 'var(--foreground)';
                }}
                onMouseLeave={e => {
                  e.currentTarget.style.borderColor = 'var(--atlas-border)';
                  e.currentTarget.style.color = 'var(--muted-foreground)';
                }}
              >
                <Icon size={10} style={{ flexShrink: 0 }} />
                <span className="truncate">{cmd.label}</span>
              </button>
            );
          })}
        </div>
      </div>
      
      {/* Messages */}
      <div className="flex-1 overflow-y-auto atlas-scrollbar px-3 py-3 space-y-3">
        {messages.map(msg => (
          <div
            key={msg.id}
            className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className="max-w-[85%] rounded px-3 py-2"
              style={msg.role === 'user' ? {
                background: 'oklch(0.82 0.18 210 / 0.12)',
                border: '1px solid oklch(0.82 0.18 210 / 0.2)',
                color: 'var(--foreground)',
              } : {
                background: 'var(--atlas-navy)',
                border: '1px solid var(--atlas-border)',
                color: 'var(--foreground)',
              }}
            >
              {msg.role === 'assistant' && (
                <div 
                  className="flex items-center gap-1 mb-1"
                >
                  <Sparkles size={9} style={{ color: 'var(--atlas-cyan)' }} />
                  <span style={{ 
                    fontSize: '0.625rem', 
                    color: 'var(--atlas-cyan)',
                    fontFamily: 'var(--font-mono)',
                    letterSpacing: '0.05em'
                  }}>
                    CO-PILOT
                  </span>
                </div>
              )}
              <p style={{ fontSize: '0.8125rem', lineHeight: '1.5', whiteSpace: 'pre-wrap' }}>
                {msg.content}
              </p>
              <div 
                className="mt-1 text-right"
                style={{ fontSize: '0.625rem', color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)' }}
              >
                {msg.timestamp.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
              </div>
            </div>
          </div>
        ))}
        
        {loading && (
          <div className="flex justify-start">
            <div
              className="rounded px-3 py-2"
              style={{
                background: 'var(--atlas-navy)',
                border: '1px solid var(--atlas-border)',
              }}
            >
              <div className="flex items-center gap-1">
                <Sparkles size={9} style={{ color: 'var(--atlas-cyan)' }} />
                <span style={{ fontSize: '0.625rem', color: 'var(--atlas-cyan)', fontFamily: 'var(--font-mono)' }}>
                  CO-PILOT
                </span>
              </div>
              <div className="flex gap-1 mt-1">
                {[0, 1, 2].map(i => (
                  <div
                    key={i}
                    className="rounded-full"
                    style={{
                      width: '6px',
                      height: '6px',
                      background: 'var(--atlas-cyan)',
                      animation: `pulse-green 1.2s ease-in-out ${i * 0.2}s infinite`,
                    }}
                  />
                ))}
              </div>
            </div>
          </div>
        )}
        
        <div ref={messagesEndRef} />
      </div>
      
      {/* Input */}
      <div 
        className="px-3 py-3 flex-shrink-0"
        style={{ borderTop: '1px solid var(--atlas-border)' }}
      >
        <div 
          className="flex gap-2 items-end rounded"
          style={{
            background: 'var(--atlas-navy)',
            border: '1px solid var(--atlas-border)',
            padding: '0.5rem',
          }}
        >
          <textarea
            ref={inputRef}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Befehl eingeben... (Enter = Senden)"
            rows={2}
            className="flex-1 bg-transparent resize-none outline-none atlas-scrollbar"
            style={{
              color: 'var(--foreground)',
              fontSize: '0.8125rem',
              fontFamily: 'var(--font-body)',
              lineHeight: '1.5',
            }}
          />
          <button
            onClick={() => sendMessage(input)}
            disabled={!input.trim() || loading}
            className="flex-shrink-0 p-1.5 rounded transition-all"
            style={{
              background: input.trim() && !loading ? 'var(--atlas-cyan)' : 'var(--atlas-border)',
              color: input.trim() && !loading ? 'var(--atlas-navy)' : 'var(--muted-foreground)',
            }}
          >
            <Send size={14} />
          </button>
        </div>
        <div 
          className="mt-1 text-center"
          style={{ fontSize: '0.625rem', color: 'var(--muted-foreground)', fontFamily: 'var(--font-body)' }}
        >
          ATLAS kann Fehler machen. Prüfe wichtige Infos.
        </div>
      </div>
    </aside>
  );
}

function getFallbackResponse(input: string): string {
  const lower = input.toLowerCase();
  
  if (lower.includes('draft') || lower.includes('post') || lower.includes('shelly')) {
    return `Draft-Vorschlag für Shelly Plus Plug S:

🔌 **Smart Home Upgrade für 14,99€**

Der Shelly Plus Plug S macht jede Steckdose smart. Energiemessung in Echtzeit, WLAN-Steuerung, Home Assistant kompatibel.

Mein Tipp: Erst messen, dann optimieren. Mit dem Shelly siehst du genau, was Strom frisst.

→ Link in Bio (Affiliate-UTM wird automatisch injiziert)

#SmartHome #Energie #Shelly #HomeAssistant`;
  }
  
  if (lower.includes('signal') || lower.includes('trend')) {
    return `Aktuelle Signal-Analyse:

📊 **Top-Trends heute:**
1. Smart Home Energiesparen (+34% Suchvolumen)
2. Home Assistant 2025 Update
3. Strompreise Winter 2025

**Empfehlung:** Shelly Plus Plug S jetzt pushen — passt perfekt zu Trend #1 und #3.

Soll ich einen Draft dafür erstellen?`;
  }
  
  if (lower.includes('kalender') || lower.includes('plan') || lower.includes('woche')) {
    return `Wochenplan-Vorschlag:

**Mo:** LinkedIn — Shelly Plug S Produktvorstellung
**Di:** Instagram Story — Smart Home Setup Tour  
**Mi:** TikTok — "Wie viel Strom verbraucht dein Fernseher wirklich?"
**Do:** LinkedIn — Affiliate-Einnahmen Update
**Fr:** Instagram Reel — Top 5 Smart Home Geräte unter 20€
**Sa:** Pause
**So:** Newsletter-Teaser für nächste Woche

Soll ich die Drafts dafür anlegen?`;
  }
  
  return `Verstanden. Ich arbeite daran.

Für vollständige AI-Antworten muss der ATLAS Co-Pilot mit dem LLM-Backend verbunden sein. Die Verbindung wird beim nächsten Deployment konfiguriert.

Was kann ich sonst für dich tun?`;
}
