/**
 * War Room — Zentrale Übersicht & Steuerung der Content-Operationen
 * 
 * Referenz: docs/design-references/screen-war-room.png
 * 
 * Layout:
 * - Page Header (Titel + Datum-Filter)
 * - 5 KPI-Karten (Heute geplant, Entwürfe offen, Freigaben nötig, Kanäle verbunden, Affiliate-Potenzial)
 * - Signal Cards (4 Karten aus ATLAS-Systemen)
 * - Content Pipeline (Funnel: Idee→Draft→Review→Geplant→Veröffentlicht)
 * - Kanal-Status (TikTok, Instagram, LinkedIn, X, YouTube)
 */

import { useState } from 'react';
import { useLocation } from 'wouter';
import { 
  Calendar, FileText, CheckSquare, Share2, Diamond,
  TrendingUp, TrendingDown, RefreshCw, ArrowRight,
  Star
} from 'lucide-react';
import { usePostizPosts, usePostizIntegrations } from '@/hooks/usePostiz';

// Sparkline mini-chart component
function Sparkline({ color, trend }: { color: string; trend: 'up' | 'down' | 'flat' }) {
  const points = trend === 'up' 
    ? '0,20 10,18 20,15 30,12 40,10 50,8 60,5 70,3'
    : trend === 'down'
    ? '0,3 10,5 20,8 30,10 40,12 50,15 60,18 70,20'
    : '0,10 10,12 20,9 30,11 40,10 50,12 60,9 70,11';
  
  return (
    <svg width="70" height="24" viewBox="0 0 70 24" fill="none">
      <polyline
        points={points}
        stroke={color}
        strokeWidth="1.5"
        fill="none"
        strokeLinecap="round"
        strokeLinejoin="round"
        opacity="0.8"
      />
    </svg>
  );
}

interface KpiCardProps {
  icon: React.ReactNode;
  iconBg: string;
  title: string;
  value: string;
  trend: string;
  trendUp: boolean | null;
  trendLabel: string;
  sparkColor: string;
  sparkTrend: 'up' | 'down' | 'flat';
  subtext?: string;
  subtextColor?: string;
}

function KpiCard({ icon, iconBg, title, value, trend, trendUp, trendLabel, sparkColor, sparkTrend, subtext, subtextColor }: KpiCardProps) {
  return (
    <div className="atlas-kpi-card flex-1 min-w-0">
      <div className="flex items-start justify-between mb-2">
        <div>
          <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-body)' }}>
            {title}
          </div>
          <div className="text-2xl font-bold" style={{ fontFamily: 'var(--font-mono)', color: 'var(--foreground)' }}>
            {value}
          </div>
        </div>
        <div 
          className="flex items-center justify-center rounded-lg flex-shrink-0"
          style={{ width: '36px', height: '36px', background: iconBg }}
        >
          {icon}
        </div>
      </div>
      
      {subtext ? (
        <div className="text-xs mb-2" style={{ color: subtextColor || 'var(--atlas-green)', fontFamily: 'var(--font-body)' }}>
          {subtext}
        </div>
      ) : (
        <div className="flex items-center gap-1 mb-2">
          {trendUp === true ? (
            <TrendingUp size={11} style={{ color: 'var(--atlas-green)' }} />
          ) : trendUp === false ? (
            <TrendingDown size={11} style={{ color: 'var(--atlas-red)' }} />
          ) : null}
          <span 
            className="text-xs"
            style={{ 
              color: trendUp === true ? 'var(--atlas-green)' : trendUp === false ? 'var(--atlas-red)' : 'var(--muted-foreground)',
              fontFamily: 'var(--font-body)'
            }}
          >
            {trend} {trendLabel}
          </span>
        </div>
      )}
      
      <Sparkline color={sparkColor} trend={sparkTrend} />
    </div>
  );
}

const SIGNAL_CARDS = [
  {
    category: 'SMART HOME',
    categoryColor: '#00d4ff',
    title: 'Shelly Plus Plug S',
    description: 'Neue Funktionen + Energie-Monitoring in Fokus. Hohe Nachfrage signalisiert.',
    type: 'Produkt',
    priority: 'Hoch',
    priorityColor: '#10b981',
    image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=80&h=80&fit=crop',
  },
  {
    category: 'KITCHEN',
    categoryColor: '#a78bfa',
    title: 'Küchen-Trends 2025',
    description: 'Meal Prep + Airfryer Content performt stark auf TikTok & Instagram.',
    type: 'Trend',
    priority: 'Mittel',
    priorityColor: '#f59e0b',
    image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=80&h=80&fit=crop',
  },
  {
    category: 'NEWS',
    categoryColor: '#60a5fa',
    title: 'KI-News Update',
    description: 'OpenAI & Google I/O Highlights erzeugen hohe Engagement-Spitzen.',
    type: 'News',
    priority: 'Hoch',
    priorityColor: '#10b981',
    image: 'https://images.unsplash.com/photo-1677442135703-1787eea5ce01?w=80&h=80&fit=crop',
  },
  {
    category: 'RADAR',
    categoryColor: '#34d399',
    title: 'Sommer-Season Ahead',
    description: 'Outdoor & Energy-Saving Content hat Potenzial für Q2 Kampagnen.',
    type: 'Opportunity',
    priority: 'Mittel',
    priorityColor: '#f59e0b',
    image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=80&h=80&fit=crop',
  },
];

const PIPELINE_STAGES = [
  { label: 'Idee', count: 56, icon: '◇', color: '#60a5fa' },
  { label: 'Draft', count: 24, icon: '✎', color: '#a78bfa' },
  { label: 'Review', count: 7, icon: '✓', color: '#f59e0b' },
  { label: 'Geplant', count: 18, icon: '⊞', color: '#00d4ff' },
  { label: 'Veröffentlicht', count: 132, icon: '✓', color: '#10b981' },
];

const CHANNELS = [
  { name: 'TikTok', icon: '🎵', planned: 18, connected: true },
  { name: 'Instagram', icon: '📸', planned: 16, connected: true },
  { name: 'LinkedIn', icon: '💼', planned: 12, connected: true },
  { name: 'X (Twitter)', icon: '✗', planned: 14, connected: true },
  { name: 'YouTube Shorts', icon: '▶', planned: 10, connected: true },
];

export default function WarRoom() {
  const [, navigate] = useLocation();
  const { posts } = usePostizPosts();
  const { integrations } = usePostizIntegrations();
  
  const drafts = posts.filter(p => p.status === 'DRAFT').length;
  const scheduled = posts.filter(p => p.status === 'QUEUE').length;
  const connectedChannels = integrations.filter(i => !i.disabled).length;

  return (
    <div className="p-5 space-y-5 animate-fade-in-up">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>
            War Room
          </h1>
          <p className="text-sm mt-0.5" style={{ color: 'var(--muted-foreground)' }}>
            Zentrale Übersicht & Steuerung deiner Content-Operationen
          </p>
        </div>
        <div className="flex items-center gap-2">
          <div 
            className="flex items-center gap-1.5 px-3 py-1.5 rounded"
            style={{ background: 'var(--atlas-surface)', border: '1px solid var(--atlas-border)' }}
          >
            <Calendar size={13} style={{ color: 'var(--muted-foreground)' }} />
            <span className="text-xs" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-body)' }}>
              {new Date().toLocaleDateString('de-DE', { day: 'numeric', month: 'long', year: 'numeric' })}
            </span>
          </div>
          <select 
            className="text-xs px-2 py-1.5 rounded"
            style={{ 
              background: 'var(--atlas-surface)', 
              border: '1px solid var(--atlas-border)',
              color: 'var(--foreground)',
              fontFamily: 'var(--font-body)'
            }}
          >
            <option value="7">7 Tage</option>
            <option value="30">30 Tage</option>
            <option value="90">90 Tage</option>
          </select>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="flex gap-3">
        <KpiCard
          icon={<Calendar size={16} style={{ color: '#60a5fa' }} />}
          iconBg="oklch(0.6 0.15 250 / 0.15)"
          title="Heute geplant"
          value={String(scheduled || 18)}
          trend="↑ 12%"
          trendUp={true}
          trendLabel="vs. gestern"
          sparkColor="#60a5fa"
          sparkTrend="up"
        />
        <KpiCard
          icon={<FileText size={16} style={{ color: '#a78bfa' }} />}
          iconBg="oklch(0.6 0.15 300 / 0.15)"
          title="Entwürfe offen"
          value={String(drafts || 24)}
          trend="↑ 8%"
          trendUp={true}
          trendLabel="vs. gestern"
          sparkColor="#a78bfa"
          sparkTrend="up"
        />
        <KpiCard
          icon={<CheckSquare size={16} style={{ color: '#ef4444' }} />}
          iconBg="oklch(0.62 0.22 25 / 0.15)"
          title="Freigaben nötig"
          value="7"
          trend="↓ 13%"
          trendUp={false}
          trendLabel="vs. gestern"
          sparkColor="#ef4444"
          sparkTrend="down"
        />
        <KpiCard
          icon={<Share2 size={16} style={{ color: '#10b981' }} />}
          iconBg="oklch(0.65 0.15 165 / 0.15)"
          title="Kanäle verbunden"
          value={`${connectedChannels || 5} / 5`}
          trend=""
          trendUp={null}
          trendLabel=""
          subtext="Alle Systeme online"
          subtextColor="var(--atlas-green)"
          sparkColor="#10b981"
          sparkTrend="flat"
        />
        <KpiCard
          icon={<Diamond size={16} style={{ color: '#00d4ff' }} />}
          iconBg="oklch(0.82 0.18 210 / 0.12)"
          title="Affiliate-Potenzial"
          value="€12.430"
          trend="↑ 24%"
          trendUp={true}
          trendLabel="vs. 7 Tage"
          sparkColor="#00d4ff"
          sparkTrend="up"
        />
      </div>

      {/* Signal Cards */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <h2 className="text-sm font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>
              Signal Cards
            </h2>
            <span className="atlas-badge-cyan" style={{ fontSize: '0.6rem' }}>Von ATLAS-Systemen</span>
          </div>
          <button 
            onClick={() => navigate('/signals')}
            className="flex items-center gap-1 text-xs transition-colors"
            style={{ color: 'var(--atlas-cyan)', fontFamily: 'var(--font-body)' }}
          >
            Alle Signale anzeigen <ArrowRight size={12} />
          </button>
        </div>
        
        <div className="grid grid-cols-4 gap-3">
          {SIGNAL_CARDS.map((card, i) => (
            <div 
              key={i}
              className="atlas-card atlas-card-hover p-3 cursor-pointer"
              style={{ animationDelay: `${i * 60}ms` }}
            >
              <div className="flex items-start justify-between mb-2">
                <span 
                  className="text-xs font-semibold"
                  style={{ color: card.categoryColor, fontFamily: 'var(--font-mono)', fontSize: '0.625rem', letterSpacing: '0.06em' }}
                >
                  {card.category}
                </span>
                <Star size={12} style={{ color: 'var(--muted-foreground)' }} />
              </div>
              
              <div className="flex gap-2 mb-2">
                <img 
                  src={card.image} 
                  alt={card.title}
                  className="rounded flex-shrink-0"
                  style={{ width: '40px', height: '40px', objectFit: 'cover' }}
                  onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
                />
                <div className="min-w-0">
                  <div className="text-xs font-semibold truncate" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-display)' }}>
                    {card.title}
                  </div>
                  <div className="text-xs mt-0.5 line-clamp-2" style={{ color: 'var(--muted-foreground)', fontSize: '0.6875rem', lineHeight: '1.4' }}>
                    {card.description}
                  </div>
                </div>
              </div>
              
              <div className="flex items-center gap-1.5">
                <span 
                  className="text-xs px-1.5 py-0.5 rounded"
                  style={{ 
                    background: 'var(--atlas-navy)', 
                    color: 'var(--muted-foreground)',
                    border: '1px solid var(--atlas-border)',
                    fontSize: '0.6rem'
                  }}
                >
                  {card.type}
                </span>
                <span 
                  className="text-xs px-1.5 py-0.5 rounded"
                  style={{ 
                    background: `${card.priorityColor}20`,
                    color: card.priorityColor,
                    border: `1px solid ${card.priorityColor}40`,
                    fontSize: '0.6rem'
                  }}
                >
                  {card.priority}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Bottom Row: Pipeline + Kanal-Status */}
      <div className="grid grid-cols-2 gap-4">
        {/* Content Pipeline */}
        <div className="atlas-card p-4">
          <h2 className="text-sm font-semibold mb-3" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>
            Content Pipeline
          </h2>
          
          <div className="flex items-center gap-1 mb-4">
            {PIPELINE_STAGES.map((stage, i) => (
              <div key={i} className="flex items-center gap-1 flex-1">
                <div 
                  className="flex-1 rounded flex flex-col items-center justify-center py-3 px-2"
                  style={{ background: `${stage.color}15`, border: `1px solid ${stage.color}30` }}
                >
                  <div className="text-lg font-bold" style={{ fontFamily: 'var(--font-mono)', color: stage.color }}>
                    {stage.count}
                  </div>
                  <div className="text-xs mt-0.5" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem', textAlign: 'center' }}>
                    {stage.label}
                  </div>
                </div>
                {i < PIPELINE_STAGES.length - 1 && (
                  <div style={{ color: 'var(--atlas-border)', fontSize: '0.75rem' }}>›</div>
                )}
              </div>
            ))}
          </div>
          
          <div className="flex gap-4">
            <div>
              <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)' }}>Conversion Rate</div>
              <div className="flex items-center gap-2">
                <div className="flex-1 h-1.5 rounded-full" style={{ background: 'var(--atlas-border)' }}>
                  <div className="h-full rounded-full" style={{ width: '32%', background: 'var(--atlas-cyan)' }} />
                </div>
                <span className="text-xs font-bold" style={{ fontFamily: 'var(--font-mono)', color: 'var(--atlas-cyan)' }}>32%</span>
              </div>
            </div>
            <div>
              <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)' }}>Ø Time to Publish</div>
              <div className="flex items-center gap-2">
                <div className="flex-1 h-1.5 rounded-full" style={{ background: 'var(--atlas-border)' }}>
                  <div className="h-full rounded-full" style={{ width: '48%', background: '#00d4ff' }} />
                </div>
                <span className="text-xs font-bold" style={{ fontFamily: 'var(--font-mono)', color: '#00d4ff' }}>2.4 Tage</span>
              </div>
            </div>
          </div>
        </div>

        {/* Kanal-Status */}
        <div className="atlas-card p-4">
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-sm font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>
              Kanal-Status
            </h2>
            <select 
              className="text-xs px-2 py-1 rounded"
              style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}
            >
              <option>Alle Kanäle</option>
            </select>
          </div>
          
          <div className="space-y-2">
            {CHANNELS.map((ch, i) => (
              <div key={i} className="flex items-center justify-between py-1.5">
                <div className="flex items-center gap-2">
                  <span style={{ fontSize: '14px' }}>{ch.icon}</span>
                  <span className="text-sm" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-body)' }}>
                    {ch.name}
                  </span>
                </div>
                <div className="flex items-center gap-3">
                  <div className="flex items-center gap-1">
                    <div className="atlas-status-dot online" />
                    <span className="text-xs" style={{ color: 'var(--atlas-green)' }}>Verbunden</span>
                  </div>
                  <span className="text-xs" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)' }}>
                    {ch.planned} geplant
                  </span>
                  <Sparkline color="#00d4ff" trend="up" />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
