import { useState, useEffect } from 'react';
import { 
  loadMarketingKit, 
  generateMarketingKit, 
  generateSocialMediaContent, 
  generateEmailTemplate,
  generateFlyerData,
  copyToClipboard,
  downloadAsset
} from '../../lib/marketing-kit';
import { 
  generateSocialMediaContentWithAI, 
  generateEmailTemplatesWithAI, 
  generateFlyerDataWithAI,
  regenerateSocialMediaPost,
  regenerateEmailTemplate,
  saveContentVote,
  type EmailTemplate as AIEmailTemplate,
  type FlyerData
} from '../../lib/marketing-kit-enhanced';
import { loadEventData } from '../../lib/event-management';
import type { MarketingKitData, SocialMediaContent, EmailTemplate } from '../../lib/marketing-kit';

interface MarketingTabProps {
  eventId: string;
  organizationId: string;
}

export default function MarketingTab({ eventId, organizationId }: MarketingTabProps) {
  const [marketingKit, setMarketingKit] = useState<MarketingKitData | null>(null);
  const [socialContent, setSocialContent] = useState<SocialMediaContent[]>([]);
  const [emailTemplate, setEmailTemplate] = useState<EmailTemplate | null>(null);
  const [aiEmailTemplates, setAiEmailTemplates] = useState<AIEmailTemplate[]>([]);
  const [flyerData, setFlyerData] = useState<FlyerData[]>([]);
  const [activeTab, setActiveTab] = useState<'overview' | 'social' | 'email' | 'assets'>('overview');
  const [generating, setGenerating] = useState(false);
  const [loading, setLoading] = useState(true);
  const [generatingAI, setGeneratingAI] = useState(false);
  const [generatingEmails, setGeneratingEmails] = useState(false);
  const [generatingFlyers, setGeneratingFlyers] = useState(false);
  const [regeneratingPosts, setRegeneratingPosts] = useState<Record<string, boolean>>({});
  const [regeneratingEmails, setRegeneratingEmails] = useState<Record<string, boolean>>({});

  useEffect(() => {
    loadData();
  }, [eventId]);

  const loadData = async () => {
    setLoading(true);
    try {
      const kitData = await loadMarketingKit(eventId);
      
      if (kitData) {
        setMarketingKit(kitData);
        
        // Load saved AI content from localStorage
        const savedSocialContent = localStorage.getItem(`social_content_${eventId}`);
        if (savedSocialContent) {
          setSocialContent(JSON.parse(savedSocialContent));
        }
        
        const savedEmailTemplates = localStorage.getItem(`email_templates_${eventId}`);
        if (savedEmailTemplates) {
          setAiEmailTemplates(JSON.parse(savedEmailTemplates));
        }
        
        const savedFlyerData = localStorage.getItem(`flyer_data_${eventId}`);
        if (savedFlyerData) {
          setFlyerData(JSON.parse(savedFlyerData));
        }
        
        // Generate basic email template (fallback)
        const emailData = generateEmailTemplate(kitData.event);
        setEmailTemplate(emailData);
      }
    } catch (error) {

    } finally {
      setLoading(false);
    }
  };

  const handleGenerateKit = async () => {
    setGenerating(true);
    try {
      const newKit = await generateMarketingKit(eventId);
      if (newKit) {
        setMarketingKit(newKit);
        
        // Don't auto-generate, wait for user to click generate button
        
        const emailData = generateEmailTemplate(newKit.event);
        setEmailTemplate(emailData);
      }
    } catch (error) {

    } finally {
      setGenerating(false);
    }
  };

  const handleCopyContent = async (content: string) => {
    try {
      await copyToClipboard(content);
      alert('Content copied to clipboard!');
    } catch (error) {

    }
  };

  const handleDownloadAsset = async (assetUrl: string, filename: string) => {
    try {
      await downloadAsset(assetUrl, filename);
    } catch (error) {

    }
  };

  const handleGenerateAISocialContent = async () => {
    if (!marketingKit) return;
    
    setGeneratingAI(true);
    try {
      const aiContent = await generateSocialMediaContentWithAI(marketingKit.event);
      setSocialContent(aiContent);
      
      // Save to localStorage for persistence
      localStorage.setItem(`social_content_${eventId}`, JSON.stringify(aiContent));
    } catch (error) {

      alert('Failed to generate AI content. Please try again.');
    } finally {
      setGeneratingAI(false);
    }
  };

  const handleGenerateAIEmailTemplates = async () => {
    if (!marketingKit) return;
    
    setGeneratingEmails(true);
    try {
      const aiTemplates = await generateEmailTemplatesWithAI(marketingKit.event);
      setAiEmailTemplates(aiTemplates);
      
      // Save to localStorage for persistence
      localStorage.setItem(`email_templates_${eventId}`, JSON.stringify(aiTemplates));
    } catch (error) {

      alert('Failed to generate AI email templates. Please try again.');
    } finally {
      setGeneratingEmails(false);
    }
  };

  const handleGenerateAIFlyers = async () => {
    if (!marketingKit) return;
    
    setGeneratingFlyers(true);
    try {
      const aiFlyers = await generateFlyerDataWithAI(marketingKit.event);
      setFlyerData(aiFlyers);
      
      // Save to localStorage for persistence
      localStorage.setItem(`flyer_data_${eventId}`, JSON.stringify(aiFlyers));
    } catch (error) {

      alert('Failed to generate AI flyers. Please try again.');
    } finally {
      setGeneratingFlyers(false);
    }
  };

  const handleVoteContent = async (contentId: string, vote: 'up' | 'down') => {
    await saveContentVote(contentId, vote);
    
    // Update local state to reflect the vote
    setSocialContent(prev => prev.map(content => 
      content.id === contentId 
        ? { ...content, votes: (content.votes || 0) + (vote === 'up' ? 1 : -1) }
        : content
    ));
  };

  const handleRegenerateSocialPost = async (contentId: string, platform: string, tone?: string) => {
    if (!marketingKit) return;
    
    setRegeneratingPosts(prev => ({ ...prev, [contentId]: true }));
    
    try {
      const newPost = await regenerateSocialMediaPost(marketingKit.event, platform, tone);
      if (newPost) {
        // Replace the old post with the new one
        setSocialContent(prev => prev.map(content => 
          content.id === contentId ? newPost : content
        ));
        
        // Update localStorage
        const updatedContent = socialContent.map(content => 
          content.id === contentId ? newPost : content
        );
        localStorage.setItem(`social_content_${eventId}`, JSON.stringify(updatedContent));
      }
    } catch (error) {

      alert('Failed to regenerate post. Please try again.');
    } finally {
      setRegeneratingPosts(prev => ({ ...prev, [contentId]: false }));
    }
  };

  const handleRegenerateEmailTemplate = async (templateId: string, tone: string) => {
    if (!marketingKit) return;
    
    setRegeneratingEmails(prev => ({ ...prev, [templateId]: true }));
    
    try {
      const newTemplate = await regenerateEmailTemplate(marketingKit.event, tone);
      if (newTemplate) {
        // Replace the old template with the new one
        setAiEmailTemplates(prev => prev.map(template => 
          template.id === templateId ? newTemplate : template
        ));
        
        // Update localStorage
        const updatedTemplates = aiEmailTemplates.map(template => 
          template.id === templateId ? newTemplate : template
        );
        localStorage.setItem(`email_templates_${eventId}`, JSON.stringify(updatedTemplates));
      }
    } catch (error) {

      alert('Failed to regenerate email template. Please try again.');
    } finally {
      setRegeneratingEmails(prev => ({ ...prev, [templateId]: false }));
    }
  };

  const handleVoteEmailTemplate = async (templateId: string, vote: 'up' | 'down') => {
    await saveContentVote(templateId, vote);
    
    // If thumbs down, automatically regenerate
    if (vote === 'down') {
      const template = aiEmailTemplates.find(t => t.id === templateId);
      if (template) {
        await handleRegenerateEmailTemplate(templateId, template.tone || 'professional');
      }
    } else {
      // Update local state to reflect the vote
      setAiEmailTemplates(prev => prev.map(template => 
        template.id === templateId 
          ? { ...template, votes: (template.votes || 0) + (vote === 'up' ? 1 : -1) }
          : template
      ));
    }
  };

  const handleVoteSocialContent = async (contentId: string, vote: 'up' | 'down') => {
    await saveContentVote(contentId, vote);
    
    // If thumbs down, automatically regenerate
    if (vote === 'down') {
      const content = socialContent.find(c => c.id === contentId);
      if (content) {
        await handleRegenerateSocialPost(contentId, content.platform, content.tone);
      }
    } else {
      // Update local state to reflect the vote
      setSocialContent(prev => prev.map(content => 
        content.id === contentId 
          ? { ...content, votes: (content.votes || 0) + (vote === 'up' ? 1 : -1) }
          : content
      ));
    }
  };

  const getPlatformIcon = (platform: string) => {
    switch (platform) {
      case 'facebook':
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
            <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
          </svg>
        );
      case 'twitter':
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
            <path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/>
          </svg>
        );
      case 'instagram':
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
            <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/>
          </svg>
        );
      case 'linkedin':
        return (
          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
            <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/>
          </svg>
        );
      default:
        return null;
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-light text-white">Marketing Kit</h2>
        <button
          onClick={handleGenerateKit}
          disabled={generating}
          className="flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all duration-200 disabled:opacity-50"
          style={{
            background: 'var(--glass-text-accent)',
            color: 'white'
          }}
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          {generating ? 'Generating...' : 'Generate Marketing Kit'}
        </button>
      </div>

      {!marketingKit ? (
        <div className="text-center py-12">
          <svg className="w-12 h-12 text-white/40 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
          </svg>
          <p className="text-white/60 mb-4">No marketing kit generated yet</p>
          <button
            onClick={handleGenerateKit}
            disabled={generating}
            className="px-6 py-3 rounded-lg font-medium transition-all duration-200 disabled:opacity-50"
            style={{
              background: 'var(--glass-text-accent)',
              color: 'white'
            }}
          >
            {generating ? 'Generating...' : 'Generate Marketing Kit'}
          </button>
        </div>
      ) : (
        <>
          {/* Tab Navigation */}
          <div className="border-b border-white/20">
            <nav className="flex space-x-8">
              {[
                { id: 'overview', label: 'Overview', icon: '📊' },
                { id: 'social', label: 'Social Media', icon: '📱' },
                { id: 'email', label: 'Email', icon: '✉️' },
                { id: 'assets', label: 'Assets', icon: '🎨' }
              ].map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as any)}
                  className={`flex items-center gap-2 py-3 px-1 border-b-2 font-medium text-sm transition-colors ${
                    activeTab === tab.id
                      ? 'border-blue-500 text-blue-400'
                      : 'border-transparent text-white/60 hover:text-white/80 hover:border-white/20'
                  }`}
                >
                  <span>{tab.icon}</span>
                  {tab.label}
                </button>
              ))}
            </nav>
          </div>

          {/* Tab Content */}
          <div className="min-h-[500px]">
            {activeTab === 'overview' && (
              <div className="space-y-6">
                <div className="bg-white/5 border border-white/20 rounded-xl p-6">
                  <h3 className="text-lg font-semibold text-white mb-4">Marketing Kit Overview</h3>
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                    <div className="text-center">
                      <div className="text-3xl font-bold text-blue-400 mb-2">{socialContent.length}</div>
                      <div className="text-white/60">Social Posts</div>
                    </div>
                    <div className="text-center">
                      <div className="text-3xl font-bold text-green-400 mb-2">{aiEmailTemplates.length}</div>
                      <div className="text-white/60">Email Templates</div>
                    </div>
                    <div className="text-center">
                      <div className="text-3xl font-bold text-purple-400 mb-2">{flyerData.length}</div>
                      <div className="text-white/60">Flyer Concepts</div>
                    </div>
                    <div className="text-center">
                      <div className="text-3xl font-bold text-orange-400 mb-2">{marketingKit.assets.length}</div>
                      <div className="text-white/60">Legacy Assets</div>
                    </div>
                  </div>
                </div>

                <div className="bg-white/5 border border-white/20 rounded-xl p-6">
                  <h3 className="text-lg font-semibold text-white mb-4">Event Information</h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                      <h4 className="font-medium text-white mb-2">Event Details</h4>
                      <div className="space-y-2 text-sm">
                        <div><span className="text-white/60">Title:</span> <span className="text-white">{marketingKit.event.title}</span></div>
                        <div><span className="text-white/60">Date:</span> <span className="text-white">{new Date(marketingKit.event.date).toLocaleDateString()}</span></div>
                        <div><span className="text-white/60">Venue:</span> <span className="text-white">{marketingKit.event.venue}</span></div>
                      </div>
                    </div>
                    <div>
                      <h4 className="font-medium text-white mb-2">Social Links</h4>
                      <div className="space-y-2 text-sm">
                        {Object.entries(marketingKit.social_links).map(([platform, url]) => (
                          <div key={platform}>
                            <span className="text-white/60 capitalize">{platform}:</span> 
                            <span className="text-white ml-2">{url || 'Not configured'}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {activeTab === 'social' && (
              <div className="space-y-6">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="text-xl font-semibold text-white">Social Media Content</h3>
                  <button
                    onClick={handleGenerateAISocialContent}
                    disabled={generatingAI || !marketingKit}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all duration-200 ${
                      generatingAI || !marketingKit
                        ? 'bg-gray-600 text-gray-400 cursor-not-allowed'
                        : ''
                    }`}
                    style={generatingAI || !marketingKit ? {} : {
                      background: 'var(--glass-text-accent)',
                      color: 'white'
                    }}
                  >
                    {generatingAI ? (
                      <>
                        <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Generating with AI...
                      </>
                    ) : (
                      <>
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                        </svg>
                        Generate AI Content
                      </>
                    )}
                  </button>
                </div>
                
                {socialContent.length === 0 ? (
                  <div className="text-center py-12">
                    <svg className="w-12 h-12 text-white/40 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
                    </svg>
                    <p className="text-white/60 mb-4">No social media content generated yet</p>
                    <p className="text-white/40 text-sm">Click "Generate AI Content" to create 5 unique posts</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    {socialContent.map((content) => (
                      <div key={content.platform} className="bg-white/5 border border-white/20 rounded-xl p-6">
                        <div className="flex items-center gap-3 mb-4">
                          <div className="text-blue-400">
                            {getPlatformIcon(content.platform)}
                          </div>
                          <h3 className="text-lg font-semibold text-white capitalize">{content.platform}</h3>
                        </div>
                        
                        <div className="space-y-4">
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Content</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white text-sm whitespace-pre-wrap">
                              {content.content}
                            </div>
                          </div>
                          
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Hashtags</label>
                            <div className="flex flex-wrap gap-2">
                              {content.hashtags.map((hashtag, index) => (
                                <span key={index} className="px-2 py-1 bg-blue-500/20 text-blue-300 rounded-lg text-xs">
                                  {hashtag}
                                </span>
                              ))}
                            </div>
                          </div>
                          
                          <div className="flex justify-between items-center">
                            <div className="flex gap-2">
                              <button
                                onClick={() => handleVoteSocialContent(content.id || '', 'up')}
                                disabled={regeneratingPosts[content.id || '']}
                                className={`p-2 rounded-lg transition-colors ${
                                  (content.votes || 0) > 0 
                                    ? 'bg-green-500/20 text-green-400' 
                                    : 'bg-white/10 text-white/60 hover:text-green-400'
                                } ${regeneratingPosts[content.id || ''] ? 'opacity-50 cursor-not-allowed' : ''}`}
                                title="Like this content"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" />
                                </svg>
                              </button>
                              <button
                                onClick={() => handleVoteSocialContent(content.id || '', 'down')}
                                disabled={regeneratingPosts[content.id || '']}
                                className={`p-2 rounded-lg transition-colors ${
                                  regeneratingPosts[content.id || ''] 
                                    ? 'bg-blue-500/20 text-blue-400' 
                                    : (content.votes || 0) < 0 
                                    ? 'bg-red-500/20 text-red-400' 
                                    : 'bg-white/10 text-white/60 hover:text-red-400'
                                }`}
                                title={regeneratingPosts[content.id || ''] ? "Regenerating..." : "Dislike & regenerate"}
                              >
                                {regeneratingPosts[content.id || ''] ? (
                                  <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                  </svg>
                                ) : (
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5" />
                                  </svg>
                                )}
                              </button>
                              {content.tone && (
                                <span className="px-2 py-1 bg-white/10 text-white/60 rounded-lg text-xs capitalize">
                                  {content.tone}
                                </span>
                              )}
                            </div>
                            <button
                              onClick={() => handleCopyContent(`${content.content}\n\n${content.hashtags.join(' ')}`)}
                              className="px-4 py-2 rounded-lg text-sm transition-colors"
                              style={{
                                background: 'var(--glass-text-accent)',
                                color: 'white'
                              }}
                            >
                              Copy Content
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {activeTab === 'email' && (
              <div className="space-y-6">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="text-xl font-semibold text-white">Email Templates</h3>
                  <button
                    onClick={handleGenerateAIEmailTemplates}
                    disabled={generatingEmails || !marketingKit}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all duration-200 ${
                      generatingEmails || !marketingKit
                        ? 'bg-gray-600 text-gray-400 cursor-not-allowed'
                        : ''
                    }`}
                    style={generatingEmails || !marketingKit ? {} : {
                      background: 'var(--glass-text-accent)',
                      color: 'white'
                    }}
                  >
                    {generatingEmails ? (
                      <>
                        <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Generating with AI...
                      </>
                    ) : (
                      <>
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                        </svg>
                        Generate AI Email Templates
                      </>
                    )}
                  </button>
                </div>

                {aiEmailTemplates.length === 0 ? (
                  <div className="text-center py-12">
                    <svg className="w-12 h-12 text-white/40 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                    <p className="text-white/60 mb-4">No AI email templates generated yet</p>
                    <p className="text-white/40 text-sm">Click "Generate AI Email Templates" to create 3 unique templates</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 gap-6">
                    {aiEmailTemplates.map((template, index) => (
                      <div key={template.id} className="bg-white/5 border border-white/20 rounded-xl p-6">
                        <div className="flex justify-between items-start mb-4">
                          <h4 className="text-lg font-semibold text-white capitalize">{template.tone} Tone</h4>
                          <div className="flex gap-2">
                            <button
                              onClick={() => handleVoteEmailTemplate(template.id || '', 'up')}
                              disabled={regeneratingEmails[template.id || '']}
                              className={`p-2 rounded-lg transition-colors ${
                                (template.votes || 0) > 0 
                                  ? 'bg-green-500/20 text-green-400' 
                                  : 'bg-white/10 text-white/60 hover:text-green-400'
                              } ${regeneratingEmails[template.id || ''] ? 'opacity-50 cursor-not-allowed' : ''}`}
                              title="Like this template"
                            >
                              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" />
                              </svg>
                            </button>
                            <button
                              onClick={() => handleVoteEmailTemplate(template.id || '', 'down')}
                              disabled={regeneratingEmails[template.id || '']}
                              className={`p-2 rounded-lg transition-colors ${
                                regeneratingEmails[template.id || ''] 
                                  ? 'bg-blue-500/20 text-blue-400' 
                                  : (template.votes || 0) < 0 
                                  ? 'bg-red-500/20 text-red-400' 
                                  : 'bg-white/10 text-white/60 hover:text-red-400'
                              }`}
                              title={regeneratingEmails[template.id || ''] ? "Regenerating..." : "Dislike & regenerate"}
                            >
                              {regeneratingEmails[template.id || ''] ? (
                                <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                              ) : (
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5" />
                                </svg>
                              )}
                            </button>
                          </div>
                        </div>
                        
                        <div className="space-y-4">
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Subject Line</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white">
                              {template.subject}
                            </div>
                            <div className="flex justify-end mt-2">
                              <button
                                onClick={() => handleCopyContent(template.subject)}
                                className="px-3 py-1 rounded-lg text-sm transition-colors"
                                style={{
                                  background: 'var(--glass-text-accent)',
                                  color: 'white'
                                }}
                              >
                                Copy Subject
                              </button>
                            </div>
                          </div>
                          
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Preview Text</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white">
                              {template.preview_text}
                            </div>
                          </div>
                          
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">HTML Content</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white text-sm max-h-64 overflow-y-auto">
                              <pre className="whitespace-pre-wrap">{template.html_content}</pre>
                            </div>
                            <div className="flex justify-end mt-2">
                              <button
                                onClick={() => handleCopyContent(template.html_content)}
                                className="px-3 py-1 rounded-lg text-sm transition-colors"
                                style={{
                                  background: 'var(--glass-text-accent)',
                                  color: 'white'
                                }}
                              >
                                Copy HTML
                              </button>
                            </div>
                          </div>
                          
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Text Content</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white text-sm max-h-64 overflow-y-auto">
                              <pre className="whitespace-pre-wrap">{template.text_content}</pre>
                            </div>
                            <div className="flex justify-end mt-2">
                              <button
                                onClick={() => handleCopyContent(template.text_content)}
                                className="px-3 py-1 rounded-lg text-sm transition-colors"
                                style={{
                                  background: 'var(--glass-text-accent)',
                                  color: 'white'
                                }}
                              >
                                Copy Text
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {activeTab === 'assets' && (
              <div className="space-y-6">
                <div className="flex justify-between items-center mb-6">
                  <h3 className="text-xl font-semibold text-white">Marketing Assets</h3>
                  <button
                    onClick={handleGenerateAIFlyers}
                    disabled={generatingFlyers || !marketingKit}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all duration-200 ${
                      generatingFlyers || !marketingKit
                        ? 'bg-gray-600 text-gray-400 cursor-not-allowed'
                        : ''
                    }`}
                    style={generatingFlyers || !marketingKit ? {} : {
                      background: 'var(--glass-text-accent)',
                      color: 'white'
                    }}
                  >
                    {generatingFlyers ? (
                      <>
                        <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Generating with AI...
                      </>
                    ) : (
                      <>
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                        </svg>
                        Generate AI Flyers
                      </>
                    )}
                  </button>
                </div>

                {flyerData.length === 0 ? (
                  <div className="text-center py-12">
                    <svg className="w-12 h-12 text-white/40 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg>
                    <p className="text-white/60 mb-4">No AI flyers generated yet</p>
                    <p className="text-white/40 text-sm">Click "Generate AI Flyers" to create 3 unique flyer concepts</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {flyerData.map((flyer) => (
                      <div key={flyer.id} className="bg-white/5 border border-white/20 rounded-xl p-6">
                        <div className="flex items-center justify-between mb-4">
                          <h3 className="text-lg font-semibold text-white capitalize">{flyer.style} Style</h3>
                          <div className="flex gap-2">
                            <button
                              onClick={() => handleVoteContent(flyer.id || '', 'up')}
                              className={`p-2 rounded-lg transition-colors ${
                                (flyer.votes || 0) > 0 
                                  ? 'bg-green-500/20 text-green-400' 
                                  : 'bg-white/10 text-white/60 hover:text-green-400'
                              }`}
                              title="Like this flyer"
                            >
                              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" />
                              </svg>
                            </button>
                            <button
                              onClick={() => handleVoteContent(flyer.id || '', 'down')}
                              className={`p-2 rounded-lg transition-colors ${
                                (flyer.votes || 0) < 0 
                                  ? 'bg-red-500/20 text-red-400' 
                                  : 'bg-white/10 text-white/60 hover:text-red-400'
                              }`}
                              title="Dislike this flyer"
                            >
                              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.736 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.096c.5 0 .905-.405.905-.904 0-.715.211-1.413.608-2.008L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5" />
                              </svg>
                            </button>
                          </div>
                        </div>
                        
                        <div className="space-y-4">
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Title</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white font-semibold">
                              {flyer.title}
                            </div>
                          </div>
                          
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Content</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white text-sm">
                              {flyer.content}
                            </div>
                          </div>
                          
                          <div>
                            <label className="block text-sm font-medium text-white/80 mb-2">Design Theme</label>
                            <div className="bg-white/10 rounded-lg p-3 text-white/80 text-sm">
                              {flyer.theme}
                            </div>
                          </div>
                          
                          <div className="flex justify-end">
                            <button
                              onClick={() => handleCopyContent(`${flyer.title}\n\n${flyer.content}\n\nDesign Theme: ${flyer.theme}`)}
                              className="px-4 py-2 rounded-lg text-sm transition-colors"
                              style={{
                                background: 'var(--glass-text-accent)',
                                color: 'white'
                              }}
                            >
                              Copy Flyer Content
                            </button>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}