import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useSource, useAppState, useAction } from './sdk';
import { Badge, Metric, Glass, Icon } from './components';
import { BarChart, Bar, LineChart, Line, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { 
  Calendar, Plus, Settings, Twitter, Linkedin, Instagram, Facebook, 
  TrendingUp, Clock, CheckCircle, FileText, Sparkles, Trash2, Edit2,
  ChevronLeft, ChevronRight, GripVertical, Save, X, Search, Filter
} from 'lucide-react';

// Platform colors from Design Spec
const PLATFORM_COLORS: Record<string, string> = {
  twitter: '#1da1f2',
  linkedin: '#0a66c2',
  instagram: '#e4405f',
  facebook: '#1877f2',
  tiktok: '#000000',
  youtube: '#ff0000',
  threads: '#000000'
};

const PLATFORM_ICONS: Record<string, any> = {
  twitter: Twitter,
  linkedin: Linkedin,
  instagram: Instagram,
  facebook: Facebook
};

// MOCK DATA - since no providers connected yet
const MOCK_KPIs = {
  total_posts: 127,
  scheduled_count: 23,
  published_count: 89,
  engagement_rate: 4.7,
  total_reach: 125000
};

const MOCK_POSTS = [
  { id: '1', content: 'Excited to announce our new AI-powered feature! 🚀 #tech #startup #innovation', platform: 'twitter', scheduled_date: '2026-04-11', scheduled_time: '09:00', status: 'scheduled', engagement: 245, reach: 12500 },
  { id: '2', content: 'Behind the scenes at our startup: How we built our MVP in 30 days. Link in bio.', platform: 'linkedin', scheduled_date: '2026-04-11', scheduled_time: '14:00', status: 'scheduled', engagement: 189, reach: 8900 },
  { id: '3', content: 'Product update: We just shipped dark mode! 🌙 What feature should we build next?', platform: 'twitter', scheduled_date: '2026-04-10', scheduled_time: '11:30', status: 'published', engagement: 567, reach: 28000 },
  { id: '4', content: 'Team spotlight: Meet Sarah, our lead engineer who makes magic happen every day ✨', platform: 'instagram', scheduled_date: '2026-04-10', scheduled_time: '16:00', status: 'published', engagement: 892, reach: 45000 },
  { id: '5', content: '5 lessons we learned scaling from 0 to 10k users. Thread 🧵', platform: 'twitter', scheduled_date: '2026-04-09', scheduled_time: '10:00', status: 'published', engagement: 1234, reach: 67000 },
  { id: '6', content: 'We are hiring! Join our growing team as a Senior Frontend Developer. Remote-friendly.', platform: 'linkedin', scheduled_date: '2026-04-12', scheduled_time: '09:00', status: 'draft', engagement: 0, reach: 0 },
  { id: '7', content: 'Customer success story: How @TechCorp increased productivity by 40% using our platform', platform: 'twitter', scheduled_date: '2026-04-12', scheduled_time: '15:00', status: 'draft', engagement: 0, reach: 0 },
  { id: '8', content: 'Weekend vibes: Our team offsite in the mountains 🏔️ #teamculture', platform: 'instagram', scheduled_date: '2026-04-13', scheduled_time: '12:00', status: 'scheduled', engagement: 0, reach: 0 },
  { id: '9', content: 'New blog post: The future of AI in startup operations. Read more on our website.', platform: 'facebook', scheduled_date: '2026-04-14', scheduled_time: '10:00', status: 'scheduled', engagement: 0, reach: 0 },
  { id: '10', content: 'Quick tip: Use keyboard shortcuts to navigate faster. Press ? to see all shortcuts.', platform: 'twitter', scheduled_date: '2026-04-08', scheduled_time: '14:30', status: 'published', engagement: 345, reach: 15600 },
];

const MOCK_DRAFTS = [
  { id: 'd1', content: 'Announcing our Series A funding round! Thank you to all our supporters 🎉', target_platform: 'twitter', created_at: '2026-04-10' },
  { id: 'd2', content: 'Product roadmap update: Q2 2026 priorities and what to expect', target_platform: 'linkedin', created_at: '2026-04-09' },
  { id: 'd3', content: 'Tutorial: Getting started with our API in 5 minutes', target_platform: 'twitter', created_at: '2026-04-08' },
  { id: 'd4', content: 'Feature comparison: Us vs competitors (humble brag edition)', target_platform: 'linkedin', created_at: '2026-04-07' },
];

const ENGAGEMENT_DATA = [
  { day: 'Mon', engagement: 1200, reach: 45000 },
  { day: 'Tue', engagement: 1800, reach: 62000 },
  { day: 'Wed', engagement: 2100, reach: 78000 },
  { day: 'Thu', engagement: 1650, reach: 55000 },
  { day: 'Fri', engagement: 2400, reach: 89000 },
  { day: 'Sat', engagement: 980, reach: 34000 },
  { day: 'Sun', engagement: 750, reach: 28000 },
];

const PLATFORM_DISTRIBUTION = [
  { name: 'Twitter', value: 45, color: '#1da1f2' },
  { name: 'LinkedIn', value: 28, color: '#0a66c2' },
  { name: 'Instagram', value: 18, color: '#e4405f' },
  { name: 'Facebook', value: 9, color: '#1877f2' },
];

export default function App() {
  const [activeTab, setActiveTab] = useState('calendar');
  const [selectedPlatform, setSelectedPlatform] = useState('all');
  const [selectedPost, setSelectedPost] = useState<any | null>(null);
  const [calendarMonth, setCalendarMonth] = useState(new Date(2026, 3, 1)); // April 2026
  const [generatorTopic, setGeneratorTopic] = useState('');
  const [generatorTone, setGeneratorTone] = useState('professional');
  const [generatorPlatform, setGeneratorPlatform] = useState('twitter');
  const [generatedContent, setGeneratedContent] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [draggedDraft, setDraggedDraft] = useState<string | null>(null);
  const [showGenerator, setShowGenerator] = useState(false);
  
  const dispatch = useAction();
  const { data, loading, error } = useSource('/api/framework/connections/app/social-media-content/data', 30000);

  // Use live data if available, otherwise mock data
  const kpis = useMemo(() => MOCK_KPIs, []);
  const posts = useMemo(() => {
    const allPosts = MOCK_POSTS;
    if (selectedPlatform === 'all') return allPosts;
    return allPosts.filter(p => p.platform === selectedPlatform);
  }, [selectedPlatform]);
  const drafts = MOCK_DRAFTS;

  // Calendar helpers
  const getDaysInMonth = (date: Date) => {
    const year = date.getFullYear();
    const month = date.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDay = firstDay.getDay();
    return { daysInMonth, startingDay, year, month };
  };

  const { daysInMonth, startingDay, year, month } = getDaysInMonth(calendarMonth);
  const monthName = calendarMonth.toLocaleString('default', { month: 'long' });

  const getPostsForDay = useCallback((day: number) => {
    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    return posts.filter(p => p.scheduled_date === dateStr);
  }, [posts, year, month]);

  const getStatusBadge = (status: string) => {
    const variants: Record<string, any> = {
      published: { variant: 'positive' as const, label: 'Published', icon: CheckCircle },
      scheduled: { variant: 'neutral' as const, label: 'Scheduled', icon: Clock },
      draft: { variant: 'negative' as const, label: 'Draft', icon: FileText }
    };
    const config = variants[status] || variants.draft;
    const IconComp = config.icon;
    return (
      <Badge label={config.label} variant={config.variant} />
    );
  };

  const getPlatformIcon = (platform: string) => {
    const IconComp = PLATFORM_ICONS[platform] || FileText;
    return <IconComp size={14} style={{ color: PLATFORM_COLORS[platform] || '#94a3b8' }} />;
  };

  const handleGenerateContent = async () => {
    if (!generatorTopic.trim()) return;
    setIsGenerating(true);
    // Simulate AI generation
    await new Promise(resolve => setTimeout(resolve, 1500));
    const templates: Record<string, string> = {
      professional: `🚀 ${generatorTopic}\n\nIn today's fast-paced business environment, staying ahead requires innovative solutions. Our team has been working diligently to bring you cutting-edge features that drive results.\n\n#Innovation #Business #Technology #Startup`,
      casual: `Hey everyone! 👋 Just wanted to share something cool about ${generatorTopic}...\n\nWe've been experimenting with this and the results are pretty awesome! What do you think? Drop a comment below! 👇\n\n#Startup #Tech #Innovation`,
      witty: `${generatorTopic} walks into a bar... 🍺\n\nJust kidding! But seriously, we've been diving deep into this and found some fascinating insights. Thread incoming! 🧵\n\n#TechTwitter #Startup #Humor`,
      inspirational: `✨ ${generatorTopic}\n\n"The only way to do great work is to love what you do." - Steve Jobs\n\nThis quote perfectly captures our journey. Every challenge is an opportunity in disguise.\n\n#Motivation #Startup #Growth #Inspiration`
    };
    setGeneratedContent(templates[generatorTone] || templates.professional);
    setIsGenerating(false);
  };

  const handleSaveGenerated = () => {
    if (!generatedContent.trim()) return;
    dispatch('toast', { message: 'Draft saved successfully!', type: 'success' });
    setGeneratedContent('');
    setGeneratorTopic('');
    setShowGenerator(false);
  };

  const handleDeletePost = (postId: string) => {
    dispatch('toast', { message: 'Post deleted', type: 'success' });
    setSelectedPost(null);
  };

  const handleDragStart = (draftId: string) => {
    setDraggedDraft(draftId);
  };

  const handleDrop = (day: number) => {
    if (!draggedDraft) return;
    dispatch('toast', { message: `Draft scheduled for ${monthName} ${day}`, type: 'success' });
    setDraggedDraft(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  // Render calendar days
  const renderCalendarDays = () => {
    const days = [];
    const totalCells = 35; // 5 rows × 7 cols
    
    // Empty cells for days before month starts
    for (let i = 0; i < startingDay; i++) {
      days.push(<div key={`empty-${i}`} className="h-24 bg-slate-900/30 border border-white/[0.04]" />);
    }
    
    // Actual days
    for (let day = 1; day <= daysInMonth; day++) {
      const dayPosts = getPostsForDay(day);
      days.push(
        <div
          key={day}
          className={`h-24 p-2 border border-white/[0.04] hover:bg-white/[0.02] transition-colors cursor-pointer ${draggedDraft ? 'bg-blue-500/10' : ''}`}
          onClick={() => {}}
          onDrop={() => handleDrop(day)}
          onDragOver={handleDragOver}
        >
          <div className="text-xs font-medium text-slate-400 mb-1">{day}</div>
          <div className="space-y-1 overflow-y-auto max-h-16">
            {dayPosts.slice(0, 3).map(post => (
              <div
                key={post.id}
                className="text-[10px] px-1.5 py-0.5 rounded truncate cursor-pointer hover:opacity-80"
                style={{ backgroundColor: `${PLATFORM_COLORS[post.platform]}30`, color: PLATFORM_COLORS[post.platform] }}
                onClick={(e) => { e.stopPropagation(); setSelectedPost(post); }}
              >
                {post.scheduled_time} · {post.content.slice(0, 20)}...
              </div>
            ))}
            {dayPosts.length > 3 && (
              <div className="text-[9px] text-slate-500">+{dayPosts.length - 3} more</div>
            )}
          </div>
        </div>
      );
    }
    
    // Empty cells to fill grid
    for (let i = days.length; i < totalCells; i++) {
      days.push(<div key={`empty-end-${i}`} className="h-24 bg-slate-900/30 border border-white/[0.04]" />);
    }
    
    return days;
  };

  return (
    <div className="min-h-screen bg-[#0f172a] text-white">
      {/* Header */}
      <header className="border-b border-white/[0.08] px-6 py-4 flex items-center justify-between sticky top-0 bg-[#0f172a]/95 backdrop-blur z-40">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
            <Calendar size={18} className="text-white" />
          </div>
          <div>
            <h1 className="text-lg font-bold">ContentFlow</h1>
            <p className="text-xs text-slate-400">Social Media Dashboard</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button 
            onClick={() => setShowGenerator(!showGenerator)}
            className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity"
          >
            <Sparkles size={16} />
            New Post
          </button>
          <button className="p-2 hover:bg-white/[0.08] rounded-lg transition-colors">
            <Settings size={18} className="text-slate-400" />
          </button>
        </div>
      </header>

      <div className="p-6 space-y-6">
        {/* KPI Row */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
          <Metric 
            label="Total Posts" 
            value={kpis.total_posts.toLocaleString()} 
            trend="up" 
            trendLabel="+12%"
          />
          <Metric 
            label="Scheduled" 
            value={kpis.scheduled_count.toString()} 
            trend="up" 
            trendLabel="+5"
          />
          <Metric 
            label="Published" 
            value={kpis.published_count.toLocaleString()} 
            trend="up" 
            trendLabel="+89"
          />
          <Metric 
            label="Engagement Rate" 
            value={`${kpis.engagement_rate}%`} 
            trend="up" 
            trendLabel="+0.3%"
          />
          <Metric 
            label="Total Reach" 
            value={`${(kpis.total_reach / 1000).toFixed(0)}K`} 
            trend="up" 
            trendLabel="+23%"
          />
        </div>

        {/* Platform Filter */}
        <Glass className="p-4">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-sm text-slate-400 mr-2">Platform:</span>
            <button
              onClick={() => setSelectedPlatform('all')}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                selectedPlatform === 'all' 
                  ? 'bg-blue-500/20 text-blue-400 border border-blue-500/30' 
                  : 'bg-white/[0.05] text-slate-400 hover:text-white border border-white/[0.08]'
              }`}
            >
              All
            </button>
            {Object.entries(PLATFORM_ICONS).map(([platform, IconComp]) => (
              <button
                key={platform}
                onClick={() => setSelectedPlatform(platform)}
                className={`flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                  selectedPlatform === platform 
                    ? 'bg-blue-500/20 text-blue-400 border border-blue-500/30' 
                    : 'bg-white/[0.05] text-slate-400 hover:text-white border border-white/[0.08]'
                }`}
              >
                <IconComp size={14} style={{ color: selectedPlatform === platform ? PLATFORM_COLORS[platform] : '#94a3b8' }} />
                {platform.charAt(0).toUpperCase() + platform.slice(1)}
              </button>
            ))}
          </div>
        </Glass>

        {/* Main Grid: Calendar + Upcoming Posts */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Calendar View */}
          <div className="lg:col-span-2">
            <Glass className="p-5">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <Calendar size={20} className="text-blue-400" />
                  <h2 className="text-lg font-semibold">{monthName} {year}</h2>
                </div>
                <div className="flex items-center gap-2">
                  <button 
                    onClick={() => setCalendarMonth(new Date(year, month - 1, 1))}
                    className="p-2 hover:bg-white/[0.08] rounded-lg transition-colors"
                  >
                    <ChevronLeft size={18} className="text-slate-400" />
                  </button>
                  <button 
                    onClick={() => setCalendarMonth(new Date(year, month + 1, 1))}
                    className="p-2 hover:bg-white/[0.08] rounded-lg transition-colors"
                  >
                    <ChevronRight size={18} className="text-slate-400" />
                  </button>
                </div>
              </div>
              
              {/* Weekday labels */}
              <div className="grid grid-cols-7 gap-px mb-2">
                {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(day => (
                  <div key={day} className="text-center text-xs font-medium text-slate-400 py-2">
                    {day}
                  </div>
                ))}
              </div>
              
              {/* Calendar grid */}
              <div className="grid grid-cols-7 gap-px bg-white/[0.04] border border-white/[0.04] rounded-lg overflow-hidden">
                {renderCalendarDays()}
              </div>
            </Glass>
          </div>

          {/* Upcoming Posts List */}
          <div>
            <Glass className="p-5 h-full">
              <div className="flex items-center gap-3 mb-4">
                <Clock size={20} className="text-blue-400" />
                <h2 className="text-lg font-semibold">Upcoming Posts</h2>
              </div>
              <div className="space-y-3 max-h-[480px] overflow-y-auto">
                {posts.filter(p => p.status !== 'published').slice(0, 8).map(post => (
                  <div
                    key={post.id}
                    className="p-3 bg-white/[0.03] rounded-lg border border-white/[0.06] hover:bg-white/[0.06] transition-colors cursor-pointer"
                    onClick={() => setSelectedPost(post)}
                  >
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex items-center gap-2">
                        {getPlatformIcon(post.platform)}
                        <span className="text-xs text-slate-400">{post.scheduled_date} · {post.scheduled_time}</span>
                      </div>
                      {getStatusBadge(post.status)}
                    </div>
                    <p className="text-sm text-slate-300 line-clamp-2">{post.content}</p>
                  </div>
                ))}
              </div>
            </Glass>
          </div>
        </div>

        {/* Content Queue & Analytics Row */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Content Queue (Drafts) */}
          <Glass className="p-5">
            <div className="flex items-center gap-3 mb-4">
              <GripVertical size={20} className="text-blue-400" />
              <h2 className="text-lg font-semibold">Content Queue</h2>
              <Badge label={`${drafts.length} drafts`} variant="neutral" />
            </div>
            <div className="flex gap-3 overflow-x-auto pb-2">
              {drafts.map(draft => (
                <div
                  key={draft.id}
                  draggable
                  onDragStart={() => handleDragStart(draft.id)}
                  className="flex-shrink-0 w-48 p-3 bg-white/[0.03] rounded-lg border border-white/[0.06] hover:bg-white/[0.06] transition-colors cursor-grab active:cursor-grabbing"
                >
                  <div className="flex items-center gap-2 mb-2">
                    {getPlatformIcon(draft.target_platform)}
                    <span className="text-xs text-slate-400">
                      {new Date(draft.created_at).toLocaleDateString()}
                    </span>
                  </div>
                  <p className="text-sm text-slate-300 line-clamp-3">{draft.content}</p>
                </div>
              ))}
            </div>
            <p className="text-xs text-slate-500 mt-3">Drag drafts to calendar to schedule</p>
          </Glass>

          {/* Analytics Chart */}
          <Glass className="p-5">
            <div className="flex items-center gap-3 mb-4">
              <TrendingUp size={20} className="text-blue-400" />
              <h2 className="text-lg font-semibold">Engagement Trends</h2>
            </div>
            <div className="h-48">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={ENGAGEMENT_DATA}>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(148,163,184,0.1)" />
                  <XAxis dataKey="day" stroke="#94a3b8" fontSize={12} />
                  <YAxis stroke="#94a3b8" fontSize={12} />
                  <Tooltip 
                    contentStyle={{ 
                      backgroundColor: 'rgba(15,23,42,0.95)', 
                      border: '1px solid rgba(148,163,184,0.2)',
                      borderRadius: '8px'
                    }}
                    labelStyle={{ color: '#f1f5f9' }}
                  />
                  <Legend />
                  <Line type="monotone" dataKey="engagement" stroke="#3b82f6" strokeWidth={2} dot={{ fill: '#3b82f6' }} />
                  <Line type="monotone" dataKey="reach" stroke="#10b981" strokeWidth={2} dot={{ fill: '#10b981' }} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </Glass>
        </div>

        {/* Platform Distribution */}
        <Glass className="p-5">
          <div className="flex items-center gap-3 mb-4">
            <Filter size={20} className="text-blue-400" />
            <h2 className="text-lg font-semibold">Platform Distribution</h2>
          </div>
          <div className="h-48 flex items-center">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={PLATFORM_DISTRIBUTION}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  paddingAngle={2}
                  dataKey="value"
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  labelLine={false}
                >
                  {PLATFORM_DISTRIBUTION.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: 'rgba(15,23,42,0.95)', 
                    border: '1px solid rgba(148,163,184,0.2)',
                    borderRadius: '8px'
                  }}
                />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </Glass>

        {/* AI Post Generator Panel (collapsible) */}
        {showGenerator && (
          <Glass className="p-5">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <Sparkles size={20} className="text-purple-400" />
                <h2 className="text-lg font-semibold">AI Post Generator</h2>
              </div>
              <button 
                onClick={() => setShowGenerator(false)}
                className="p-2 hover:bg-white/[0.08] rounded-lg transition-colors"
              >
                <X size={18} className="text-slate-400" />
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
              <div>
                <label className="text-xs text-slate-400 mb-1 block">Topic / Input</label>
                <input
                  type="text"
                  value={generatorTopic}
                  onChange={(e) => setGeneratorTopic(e.target.value)}
                  placeholder="e.g., New feature launch"
                  className="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-sm focus:outline-none focus:border-blue-500/50"
                />
              </div>
              <div>
                <label className="text-xs text-slate-400 mb-1 block">Tone</label>
                <select
                  value={generatorTone}
                  onChange={(e) => setGeneratorTone(e.target.value)}
                  className="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-sm focus:outline-none focus:border-blue-500/50"
                >
                  <option value="professional">Professional</option>
                  <option value="casual">Casual</option>
                  <option value="witty">Witty</option>
                  <option value="inspirational">Inspirational</option>
                </select>
              </div>
              <div>
                <label className="text-xs text-slate-400 mb-1 block">Platform</label>
                <select
                  value={generatorPlatform}
                  onChange={(e) => setGeneratorPlatform(e.target.value)}
                  className="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-sm focus:outline-none focus:border-blue-500/50"
                >
                  <option value="twitter">Twitter</option>
                  <option value="linkedin">LinkedIn</option>
                  <option value="instagram">Instagram</option>
                  <option value="facebook">Facebook</option>
                </select>
              </div>
            </div>
            <div className="flex items-center gap-3 mb-4">
              <button
                onClick={handleGenerateContent}
                disabled={!generatorTopic.trim() || isGenerating}
                className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-purple-500 to-pink-500 rounded-lg text-sm font-medium hover:opacity-90 transition-opacity disabled:opacity-50"
              >
                <Sparkles size={16} />
                {isGenerating ? 'Generating...' : 'Generate'}
              </button>
            </div>
            {generatedContent && (
              <div>
                <label className="text-xs text-slate-400 mb-1 block">Generated Content</label>
                <textarea
                  value={generatedContent}
                  onChange={(e) => setGeneratedContent(e.target.value)}
                  rows={5}
                  className="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-sm focus:outline-none focus:border-blue-500/50 resize-none"
                />
                <div className="flex items-center gap-3 mt-3">
                  <button
                    onClick={handleSaveGenerated}
                    className="flex items-center gap-2 px-4 py-2 bg-blue-500/20 text-blue-400 rounded-lg text-sm font-medium hover:bg-blue-500/30 transition-colors"
                  >
                    <Save size={16} />
                    Save as Draft
                  </button>
                  <button
                    onClick={() => setGeneratedContent('')}
                    className="flex items-center gap-2 px-4 py-2 bg-white/[0.05] text-slate-400 rounded-lg text-sm font-medium hover:bg-white/[0.08] transition-colors"
                  >
                    <Trash2 size={16} />
                    Discard
                  </button>
                </div>
              </div>
            )}
          </Glass>
        )}
      </div>

      {/* Post Detail Modal */}
      {selectedPost && (
        <div 
          className="fixed inset-0 bg-black/70 z-50 flex items-center justify-center p-4"
          onClick={() => setSelectedPost(null)}
        >
          <Glass 
            className="p-6 max-w-lg w-full max-h-[80vh] overflow-y-auto"
            onClick={e => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                {getPlatformIcon(selectedPost.platform)}
                <h2 className="text-lg font-bold">Post Details</h2>
              </div>
              <button 
                onClick={() => setSelectedPost(null)}
                className="p-2 hover:bg-white/[0.08] rounded-lg transition-colors"
              >
                <X size={18} className="text-slate-400" />
              </button>
            </div>
            
            <div className="space-y-4">
              <div>
                <label className="text-xs text-slate-400 mb-1 block">Content</label>
                <p className="text-sm text-slate-200 bg-white/[0.03] p-3 rounded-lg">{selectedPost.content}</p>
              </div>
              
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-slate-400 mb-1 block">Platform</label>
                  <div className="flex items-center gap-2 text-sm">
                    {getPlatformIcon(selectedPost.platform)}
                    <span className="capitalize">{selectedPost.platform}</span>
                  </div>
                </div>
                <div>
                  <label className="text-xs text-slate-400 mb-1 block">Status</label>
                  {getStatusBadge(selectedPost.status)}
                </div>
                <div>
                  <label className="text-xs text-slate-400 mb-1 block">Scheduled</label>
                  <p className="text-sm">{selectedPost.scheduled_date} at {selectedPost.scheduled_time}</p>
                </div>
                <div>
                  <label className="text-xs text-slate-400 mb-1 block">Engagement</label>
                  <p className="text-sm">{selectedPost.engagement.toLocaleString()} interactions</p>
                </div>
              </div>

              {selectedPost.reach > 0 && (
                <div>
                  <label className="text-xs text-slate-400 mb-1 block">Reach</label>
                  <p className="text-sm">{selectedPost.reach.toLocaleString()} people</p>
                </div>
              )}
              
              <div className="flex items-center gap-3 pt-4 border-t border-white/[0.08]">
                <button className="flex items-center gap-2 px-4 py-2 bg-blue-500/20 text-blue-400 rounded-lg text-sm font-medium hover:bg-blue-500/30 transition-colors">
                  <Edit2 size={16} />
                  Edit
                </button>
                <button 
                  onClick={() => handleDeletePost(selectedPost.id)}
                  className="flex items-center gap-2 px-4 py-2 bg-red-500/20 text-red-400 rounded-lg text-sm font-medium hover:bg-red-500/30 transition-colors"
                >
                  <Trash2 size={16} />
                  Delete
                </button>
              </div>
            </div>
          </Glass>
        </div>
      )}

      {/* Connection prompt if no data */}
      {!loading && (!data || data.connected_count === 0) && (
        <div className="fixed bottom-6 right-6 max-w-sm">
          <Glass className="p-4 border border-blue-500/30 bg-blue-500/10">
            <div className="flex items-start gap-3">
              <div className="w-8 h-8 rounded-lg bg-blue-500/20 flex items-center justify-center flex-shrink-0">
                <Settings size={16} className="text-blue-400" />
              </div>
              <div>
                <h3 className="text-sm font-semibold text-blue-400 mb-1">Connect Social Accounts</h3>
                <p className="text-xs text-slate-400 mb-3">Connect your social media accounts to see live data and schedule posts directly.</p>
                <button 
                  onClick={() => dispatch('toast', { message: 'Connection flow would start here', type: 'info' })}
                  className="text-xs px-3 py-1.5 bg-blue-500/20 text-blue-400 rounded-lg hover:bg-blue-500/30 transition-colors"
                >
                  Connect Now
                </button>
              </div>
            </div>
          </Glass>
        </div>
      )}
    </div>
  );
}
