"use client";

import { useState, useEffect, useRef } from 'react';
import { 
  GraduationCap, 
  Target, 
  BookOpen, 
  Globe, 
  Building, 
  FileText,
  Download,
  Sparkles,
  User,
  Mail,
  Phone,
  ChevronDown,
  Calendar,
  Award,
  Clock,
  Check,
  Loader2,
  FileText as FileDoc,
  File,
  Flag,
  MessageSquare,
  Languages
} from 'lucide-react';
import { Document, Page, Text, View, StyleSheet, Font, pdf } from '@react-pdf/renderer';
import { saveAs } from 'file-saver';
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
import { Document as DocxDocument, Packer, Paragraph, TextRun, HeadingLevel } from 'docx';

// Register fonts for PDF
Font.register({
  family: 'Inter',
  fonts: [
    { src: 'https://fonts.gstatic.com/s/inter/v12/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuLyfAZ9hjQ.ttf', fontWeight: 400 },
    { src: 'https://fonts.gstatic.com/s/inter/v12/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuFuYAZ9hjQ.ttf', fontWeight: 600 },
    { src: 'https://fonts.gstatic.com/s/inter/v12/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuBWYAZ9hjQ.ttf', fontWeight: 700 },
  ]
});

interface UserInfo {
  fullName: string;
  email: string;
  phone: string;
}

interface StudyPlanData {
  fullName: string;
  email: string;
  phone: string;
  nationality: string;
  lastEducation: string;
  educationLevel: string;
  cgpa: string;
  studyGap: string;
  gapJustification: string;
  country: string;
  university: string;
  course: string;
  wordCount: string;
  responseStyle: string;
  englishTest: string;
  englishScore: string;
}

export default function AIStudyPlanForm() {
  const [showUserInfoModal, setShowUserInfoModal] = useState(false);
  const [userInfo, setUserInfo] = useState<UserInfo>({
    fullName: '',
    email: '',
    phone: ''
  });
  
  const [formData, setFormData] = useState<StudyPlanData>({
    fullName: '',
    email: '',
    phone: '',
    nationality: '',
    lastEducation: '',
    educationLevel: '',
    cgpa: '',
    studyGap: '',
    gapJustification: '',
    country: '',
    university: '',
    course: '',
    wordCount: '500-600',
    responseStyle: 'professional',
    englishTest: 'none',
    englishScore: ''
  });

  const [loading, setLoading] = useState(false);
  const [studyPlan, setStudyPlan] = useState<string>('');
  const [isStreaming, setIsStreaming] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const resultsRef = useRef<HTMLDivElement>(null);

  const educationLevels = [
    { value: 'high_school', label: 'High School', icon: '🏫' },
    { value: 'bachelors', label: 'Bachelor\'s Degree', icon: '🎓' },
    { value: 'masters', label: 'Master\'s Degree', icon: '📚' },
    { value: 'phd', label: 'PhD', icon: '🔬' },
    { value: 'diploma', label: 'Diploma', icon: '📜' }
  ];

  const wordCountOptions = [
    '100-200', '200-300', '300-400', '400-500', '500-600',
    '600-700', '700-800', '800-900', '900-1000'
  ];

  const responseStyles = [
    { value: 'professional', label: 'Professional', desc: 'Formal and structured' },
    { value: 'concise', label: 'Concise', desc: 'Direct and to the point' },
    { value: 'detailed', label: 'Detailed', desc: 'Comprehensive and thorough' },
    { value: 'academic', label: 'Academic', desc: 'Research-oriented' },
    { value: 'motivational', label: 'Motivational', desc: 'Encouraging and inspiring' }
  ];

  const englishTests = [
    { value: 'ielts', label: 'IELTS', maxScore: 9, step: 0.5, placeholder: 'e.g., 6.5' },
    { value: 'pte', label: 'PTE', maxScore: 90, step: 1, placeholder: 'e.g., 58' },
    { value: 'toefl', label: 'TOEFL', maxScore: 120, step: 1, placeholder: 'e.g., 80' },
    { value: 'duolingo', label: 'Duolingo', maxScore: 160, step: 5, placeholder: 'e.g., 105' },
    { value: 'none', label: 'No English Test', maxScore: 0, step: 0, placeholder: '' }
  ];

  // Get current English test configuration
  const getCurrentEnglishTest = () => {
    return englishTests.find(test => test.value === formData.englishTest) || englishTests[4];
  };

  // Clean and wrap HTML content
  const cleanAndWrapHTML = (html: string) => {
    if (!html) return '';
    
    let cleaned = html
      .replace(/<div[^>]*>/g, '')
      .replace(/<\/div>/g, '')
      .replace(/style="[^"]*"/g, '')
      .replace(/class="[^"]*"/g, '');
    
    return `<div class="ai-study-plan-content">${cleaned}</div>`;
  };

  // Improved HTML to plain text conversion that preserves structure
  const htmlToPlainText = (html: string) => {
    if (!html) return '';
    
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = html;
    
    const processNode = (node: Node): string => {
      if (node.nodeType === Node.TEXT_NODE) {
        return node.textContent || '';
      }
      
      if (node.nodeType === Node.ELEMENT_NODE) {
        const element = node as HTMLElement;
        const tagName = element.tagName.toLowerCase();
        const children = Array.from(element.childNodes);
        const childText = children.map(processNode).join('');
        
        switch (tagName) {
          case 'h1':
            return '\n\n' + childText.toUpperCase() + '\n\n';
          case 'h2':
            return '\n\n' + childText + '\n\n';
          case 'h3':
            return '\n' + childText + '\n\n';
          case 'p':
            return childText + '\n\n';
          case 'li':
            return '• ' + childText + '\n';
          case 'ul':
          case 'ol':
            return childText;
          case 'br':
            return '\n';
          case 'strong':
          case 'b':
            return childText;
          case 'em':
          case 'i':
            return childText;
          default:
            return childText;
        }
      }
      
      return '';
    };
    
    return processNode(tempDiv).trim();
  };

  // PDF Document Component with proper bullet point handling
  const StudyPlanPDF = () => {
    const plainText = htmlToPlainText(studyPlan);
    
    // Split into sections and clean up
    const sections = plainText.split(/\n\s*\n/).filter(section => section.trim());

    // PDF Styles
    const styles = StyleSheet.create({
      page: {
        flexDirection: 'column',
        backgroundColor: '#FFFFFF',
        padding: 40,
        fontFamily: 'Inter',
        fontSize: 11,
        lineHeight: 1.5,
      },
      header: {
        marginBottom: 25,
        paddingBottom: 15,
        borderBottomWidth: 2,
        borderBottomColor: '#0B6D76',
        borderBottomStyle: 'solid',
      },
      title: {
        fontSize: 22,
        fontWeight: 700,
        color: '#0B6D76',
        marginBottom: 5,
        textTransform: 'uppercase',
      },
      subtitle: {
        fontSize: 12,
        color: '#666666',
        marginBottom: 15,
      },
      infoGrid: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginBottom: 15,
        gap: 8,
      },
      infoItem: {
        width: '48%',
        marginBottom: 4,
      },
      infoLabel: {
        fontSize: 8,
        color: '#666666',
        fontWeight: 600,
        textTransform: 'uppercase',
        letterSpacing: 0.5,
        marginBottom: 1,
      },
      infoValue: {
        fontSize: 9,
        color: '#333333',
      },
      section: {
        marginBottom: 15,
      },
      sectionTitle: {
        fontSize: 14,
        fontWeight: 700,
        color: '#0B6D76',
        marginBottom: 8,
        backgroundColor: '#F0F9FA',
        padding: 6,
        borderRadius: 4,
      },
      subsectionTitle: {
        fontSize: 11,
        fontWeight: 600,
        color: '#333333',
        marginBottom: 6,
        marginTop: 6,
      },
      paragraph: {
        marginBottom: 6,
        textAlign: 'justify',
      },
      listContainer: {
        marginBottom: 10,
        marginLeft: 15,
      },
      listItem: {
        flexDirection: 'row',
        marginBottom: 5,
        alignItems: 'flex-start',
      },
      bullet: {
        fontSize: 8,
        marginRight: 6,
        marginTop: 2,
      },
      listText: {
        flex: 1,
        fontSize: 10,
      },
      nestedList: {
        marginLeft: 15,
        marginTop: 3,
      },
      footer: {
        position: 'absolute',
        bottom: 20,
        left: 40,
        right: 40,
        fontSize: 8,
        color: '#999999',
        textAlign: 'center',
        borderTopWidth: 1,
        borderTopColor: '#EEEEEE',
        borderTopStyle: 'solid',
        paddingTop: 8,
      },
      generatedDate: {
        fontSize: 8,
        color: '#666666',
        marginBottom: 3,
      },
      pageNumber: {
        position: 'absolute',
        fontSize: 8,
        bottom: 15,
        left: 0,
        right: 0,
        textAlign: 'center',
        color: '#999999',
      }
    });

    // Function to parse and render content with proper bullet points
    const renderSectionContent = (sectionText: string) => {
      const lines = sectionText.split('\n').filter(line => line.trim());
      const elements = [];
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        
        // Skip empty lines
        if (!line) continue;
        
        // Check if it's a bullet point (starts with • or - or number.)
        if (line.startsWith('•') || line.startsWith('-') || /^\d+\./.test(line)) {
          // Check for consecutive bullet points
          const bulletItems = [];
          while (i < lines.length && (lines[i].trim().startsWith('•') || lines[i].trim().startsWith('-') || /^\d+\./.test(lines[i].trim()))) {
            bulletItems.push(lines[i].trim());
            i++;
          }
          i--; // Adjust index
          
          // Render bullet list
          elements.push(
            <View key={`bullet-${i}`} style={styles.listContainer}>
              {bulletItems.map((item, idx) => (
                <View key={idx} style={styles.listItem}>
                  <Text style={styles.bullet}>•</Text>
                  <Text style={styles.listText}>
                    {item.replace(/^[•\-]\s*/, '').replace(/^\d+\.\s*/, '')}
                  </Text>
                </View>
              ))}
            </View>
          );
        } 
        // Check if it's a subsection title (all caps or ends with colon and not too long)
        else if ((line === line.toUpperCase() && line.length < 100) || line.endsWith(':')) {
          elements.push(
            <Text key={i} style={styles.subsectionTitle}>
              {line}
            </Text>
          );
        } 
        // Regular paragraph
        else {
          elements.push(
            <Text key={i} style={styles.paragraph}>
              {line}
            </Text>
          );
        }
      }
      
      return elements;
    };

    // Group sections by their titles
    const groupedSections: { title: string; content: string[] }[] = [];
    let currentTitle = 'EXECUTIVE SUMMARY';
    let currentContent: string[] = [];

    sections.forEach((section, index) => {
      const lines = section.split('\n').filter(line => line.trim());
      const firstLine = lines[0] || '';
      
      // Check if this section should be a new title
      if (
        firstLine === firstLine.toUpperCase() && 
        firstLine.length < 100 &&
        !firstLine.startsWith('•') &&
        !firstLine.startsWith('-') &&
        !/^\d+\./.test(firstLine)
      ) {
        // Save previous section
        if (currentContent.length > 0) {
          groupedSections.push({
            title: currentTitle,
            content: currentContent
          });
        }
        
        // Start new section
        currentTitle = firstLine;
        currentContent = lines.slice(1);
      } else {
        // Add to current section
        currentContent = [...currentContent, ...lines];
      }
      
      // Add the last section
      if (index === sections.length - 1 && currentContent.length > 0) {
        groupedSections.push({
          title: currentTitle,
          content: currentContent
        });
      }
    });

    // Get English test label
    const getEnglishTestLabel = () => {
      const test = englishTests.find(t => t.value === formData.englishTest);
      if (!test || formData.englishTest === 'none') return 'No English Test';
      return `${test.label}${formData.englishScore ? `: ${formData.englishScore}` : ''}`;
    };

    return (
      <Document>
        <Page size="A4" style={styles.page}>

          {/* Render grouped sections */}
          {groupedSections.map((section, index) => (
            <View key={index} style={styles.section}>
              <Text style={styles.sectionTitle}>{section.title}</Text>
              {renderSectionContent(section.content.join('\n'))}
            </View>
          ))}

          {/* Footer */}
          <View style={styles.footer}>
            <Text style={styles.generatedDate}>
              Generated on: {new Date().toLocaleDateString('en-US', { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric' 
              })}
            </Text>
            <Text>Generated by UnversitiesPage AI Study Plan Generator</Text>
          </View>
          
          {/* Page Number */}
          <Text style={styles.pageNumber} render={({ pageNumber, totalPages }) => (
            `Page ${pageNumber} of ${totalPages}`
          )} fixed />
        </Page>
      </Document>
    );
  };

  // Generate PDF
  const generatePDF = async () => {
    if (!studyPlan) return;
    
    setIsDownloading(true);
    try {
      const blob = await pdf(<StudyPlanPDF />).toBlob();
      saveAs(blob, `Study-Plan-${formData.fullName.replace(/\s+/g, '-')}.pdf`);
    } catch (error) {
      console.error('Error generating PDF:', error);
      // Fallback to alternative method
      await generatePDFAlternative();
    } finally {
      setIsDownloading(false);
    }
  };

  // Generate Word Document with proper bullet points
  const generateWordDocument = async () => {
    if (!studyPlan) return;
    
    setIsDownloading(true);
    try {
      const plainText = htmlToPlainText(studyPlan);
      const sections = plainText.split(/\n\s*\n/).filter(section => section.trim());
      
      const docChildren = [];
      
      // Title
      docChildren.push(
        new Paragraph({
          text: "AI-GENERATED STUDY PLAN",
          heading: HeadingLevel.HEADING_1,
          spacing: { after: 200 },
        })
      );
      
      // Student Information
      docChildren.push(
        new Paragraph({
          text: `Prepared for: ${formData.fullName}`,
          spacing: { after: 100 },
        })
      );
      
      // Add information table
      const infoItems = [
        { label: "Nationality", value: formData.nationality || "Not specified" },
        { label: "English Proficiency", value: getCurrentEnglishTest().label + (formData.englishScore ? `: ${formData.englishScore}` : '') },
        { label: "Last Education", value: formData.lastEducation },
        { label: "CGPA/Marks", value: formData.cgpa || "Not specified" },
        { label: "Study Gap", value: formData.studyGap || "None" },
        { label: "Target University", value: formData.university },
        { label: "Target Course", value: formData.course },
        { label: "Target Country", value: formData.country },
      ];
      
      infoItems.forEach(item => {
        if (item.value) {
          docChildren.push(
            new Paragraph({
              children: [
                new TextRun({
                  text: `${item.label}: `,
                  bold: true,
                }),
                new TextRun({
                  text: item.value,
                }),
              ],
              spacing: { after: 50 },
            })
          );
        }
      });
      
      // Gap Justification if exists
      if (formData.gapJustification) {
        docChildren.push(
          new Paragraph({
            text: "Gap Justification:",
            spacing: { before: 100, after: 50 },
          })
        );
        
        docChildren.push(
          new Paragraph({
            text: formData.gapJustification,
            spacing: { after: 150 },
          })
        );
      }
      
      docChildren.push(
        new Paragraph({
          text: "",
          spacing: { after: 300 },
        })
      );
      
      // Process content sections
      let currentSectionTitle = "EXECUTIVE SUMMARY";
      let currentSectionItems: string[] = [];
      
      const processSection = () => {
        if (currentSectionItems.length > 0) {
          
          // Process section items
          currentSectionItems.forEach(item => {
            const trimmedItem = item.trim();
            
            // Check if it's a bullet point
            if (trimmedItem.startsWith('•') || trimmedItem.startsWith('-') || /^\d+\./.test(trimmedItem)) {
              docChildren.push(
                new Paragraph({
                  text: trimmedItem.replace(/^[•\-]\s*/, '').replace(/^\d+\.\s*/, ''),
                  bullet: {
                    level: 0
                  },
                  spacing: { after: 100 },
                })
              );
            } 
            // Check if it's a subsection
            else if ((trimmedItem === trimmedItem.toUpperCase() && trimmedItem.length < 100) || trimmedItem.endsWith(':')) {
              docChildren.push(
                new Paragraph({
                  text: trimmedItem,
                  heading: HeadingLevel.HEADING_4,
                  spacing: { before: 150, after: 100 },
                })
              );
            }
            // Regular paragraph
            else {
              docChildren.push(
                new Paragraph({
                  text: trimmedItem,
                  spacing: { after: 150 },
                })
              );
            }
          });
          
          docChildren.push(
            new Paragraph({
              text: "",
              spacing: { after: 300 },
            })
          );
        }
      };
      
      sections.forEach(section => {
        const lines = section.split('\n').filter(line => line.trim());
        
        if (lines.length === 0) return;
        
        const firstLine = lines[0];
        
        // Check if this is a new section title
        if (
          firstLine === firstLine.toUpperCase() && 
          firstLine.length < 100 &&
          !firstLine.startsWith('•') &&
          !firstLine.startsWith('-') &&
          !/^\d+\./.test(firstLine)
        ) {
          // Process previous section
          processSection();
          
          // Start new section
          currentSectionTitle = firstLine;
          currentSectionItems = lines.slice(1);
        } else {
          // Add to current section
          currentSectionItems = [...currentSectionItems, ...lines];
        }
      });
      
      // Process the last section
      processSection();
      
      // Footer
      docChildren.push(
        new Paragraph({
          text: `Generated on: ${new Date().toLocaleDateString('en-US', { 
            weekday: 'long', 
            year: 'numeric', 
            month: 'long', 
            day: 'numeric' 
          })}`,
          spacing: { before: 400, after: 100 },
        })
      );
      
      docChildren.push(
        new Paragraph({
          text: `Generated by UnversitiesPage AI Study Plan Generator`,
          spacing: { after: 100 },
        })
      );
      
      const doc = new DocxDocument({
        sections: [{
          properties: {},
          children: docChildren,
        }],
      });

      const blob = await Packer.toBlob(doc);
      saveAs(blob, `Study-Plan-${formData.fullName.replace(/\s+/g, '-')}.docx`);
      
    } catch (error) {
      console.error('Error generating Word document:', error);
      alert('Error generating Word document. Please try again.');
    } finally {
      setIsDownloading(false);
    }
  };

  // Alternative PDF generation using html2canvas (backup method)
  const generatePDFAlternative = async () => {
    if (!studyPlan || !resultsRef.current) return;
    
    try {
      const element = resultsRef.current;
      const canvas = await html2canvas(element, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff',
        logging: false,
      });
      
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'mm', 'a4');
      const imgWidth = 190;
      const pageHeight = 295;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;
      let position = 10;
      
      pdf.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;
      
      while (heightLeft > 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }
      
      pdf.save(`Study-Plan-${formData.fullName.replace(/\s+/g, '-')}.pdf`);
    } catch (error) {
      console.error('Error generating alternative PDF:', error);
      alert('Error generating PDF. Please try again.');
    }
  };

  useEffect(() => {
    const savedUserInfo = localStorage.getItem('studyPlanUserInfo');
    if (savedUserInfo) {
      try {
        const parsedInfo = JSON.parse(savedUserInfo);
        const savedDate = localStorage.getItem('studyPlanUserInfoDate');
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
        
        if (savedDate && new Date(savedDate) > sevenDaysAgo) {
          setUserInfo(parsedInfo);
          setFormData(prev => ({
            ...prev,
            fullName: parsedInfo.fullName,
            email: parsedInfo.email,
            phone: parsedInfo.phone || ''
          }));
        } else {
          localStorage.removeItem('studyPlanUserInfo');
          localStorage.removeItem('studyPlanUserInfoDate');
        }
      } catch (error) {
        console.error('Error parsing saved user info:', error);
      }
    }
  }, []);

  const handleUserInfoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setUserInfo(prev => ({ ...prev, [name]: value }));
  };

  const handleUserInfoSubmit = () => {
    if (!userInfo.fullName || !userInfo.email) {
      alert('Please fill in at least Full Name and Email');
      return;
    }

    localStorage.setItem('studyPlanUserInfo', JSON.stringify(userInfo));
    localStorage.setItem('studyPlanUserInfoDate', new Date().toISOString());

    setFormData(prev => ({
      ...prev,
      fullName: userInfo.fullName,
      email: userInfo.email,
      phone: userInfo.phone
    }));

    setShowUserInfoModal(false);
    handleSubmit();
  };

  const handleFormChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear English score if test is changed to "none"
    if (name === 'englishTest' && value === 'none') {
      setFormData(prev => ({ ...prev, englishScore: '' }));
    }
  };

  const handleGenerateClick = () => {
    const savedUserInfo = localStorage.getItem('studyPlanUserInfo');
    if (savedUserInfo) {
      try {
        const parsedInfo = JSON.parse(savedUserInfo);
        const savedDate = localStorage.getItem('studyPlanUserInfoDate');
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
        
        if (savedDate && new Date(savedDate) > sevenDaysAgo) {
          handleSubmit();
          return;
        }
      } catch (error) {
        console.error('Error parsing saved info:', error);
      }
    }
    
    setShowUserInfoModal(true);
  };

  const handleSubmit = async () => {
    if (!formData.fullName || !formData.lastEducation || !formData.country || !formData.university || !formData.course) {
      alert('Please fill in all required fields');
      return;
    }

    // Validate English score if test is selected
    if (formData.englishTest !== 'none' && formData.englishScore) {
      const test = getCurrentEnglishTest();
      const score = parseFloat(formData.englishScore);
      
      if (isNaN(score) || score < 0 || score > test.maxScore) {
        alert(`Please enter a valid ${test.label} score between 0 and ${test.maxScore}`);
        return;
      }
    }

    setLoading(true);
    setIsStreaming(true);
    setStudyPlan('');
    setIsSubmitted(false);
    
    let planId: number | null = null;

    try {
      const response = await fetch('/api/frontend/study-plan', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        throw new Error('Failed to generate study plan');
      }

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();

      if (reader) {
        let fullResponse = '';
        let planIdExtracted = false;
        
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          const chunk = decoder.decode(value);
          
          // Extract planId from the first chunk
          if (!planIdExtracted && chunk.includes('<plan-id')) {
            const match = chunk.match(/data-id="(\d+)"/);
            if (match && match[1]) {
              planId = parseInt(match[1]);
              planIdExtracted = true;
              
              // Remove the plan-id tag from the response
              const cleanedChunk = chunk.replace(/<plan-id[^>]*><\/plan-id>/, '');
              fullResponse += cleanedChunk;
              setStudyPlan(cleanAndWrapHTML(fullResponse));
            } else {
              fullResponse += chunk;
              setStudyPlan(cleanAndWrapHTML(fullResponse));
            }
          } else {
            fullResponse += chunk;
            setStudyPlan(cleanAndWrapHTML(fullResponse));
          }
          
          if (resultsRef.current) {
            resultsRef.current.scrollTop = resultsRef.current.scrollHeight;
          }
        }
        
        // After stream completes, call CRM API
        if (planId) {
          try {
            const crmResponse = await fetch('/api/frontend/study-plan/crm', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({ planId }),
            });

            if (crmResponse.ok) {
              console.log('CRM data sent successfully');
            } else {
              console.warn('CRM API responded with non-OK status');
            }
          } catch (crmError) {
            console.warn('CRM API Error (non-blocking):', crmError);
            // Continue even if CRM fails
          }
        }
        
        setIsSubmitted(true);
      }
    } catch (error) {
      console.error('Error:', error);
      setStudyPlan('<div class="error-message"><p>❌ Error generating study plan. Please try again.</p></div>');
    } finally {
      setLoading(false);
      setIsStreaming(false);
    }
  };

  const ResultsDisplay = () => {
    if (isStreaming) {
      return (
        <div className="space-y-4">
          <div className="flex items-center gap-3 p-4 bg-gradient-to-r from-blue-50 to-emerald-50 rounded-xl border border-blue-100">
            <div className="p-2 rounded-lg bg-blue-100">
              <Sparkles className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <div className="font-medium">AI is crafting your study plan...</div>
              <div className="text-sm text-gray-500">This usually takes 15-30 seconds</div>
            </div>
          </div>
          
          {studyPlan ? (
            <div 
              className="ai-study-plan-output"
              dangerouslySetInnerHTML={{ 
                __html: studyPlan 
              }}
            />
          ) : (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="w-8 h-8 animate-spin" style={{ color: '#0B6D76' }} />
            </div>
          )}
        </div>
      );
    }
    
    if (studyPlan) {
      return (
        <div className="space-y-6">
          <div className="p-6 bg-gradient-to-r from-[#0B6D76]/5 to-emerald-50 rounded-xl border border-[#0B6D76]/10">
            <h3 className="text-xl font-bold mb-3" style={{ color: '#0B6D76' }}>
              📋 Study Plan for {formData.fullName}
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
              <div className="flex items-center gap-2">
                <Flag className="w-4 h-4 text-gray-500" />
                <span>{formData.nationality || 'Nationality not specified'}</span>
              </div>
              <div className="flex items-center gap-2">
                <Languages className="w-4 h-4 text-gray-500" />
                <span>
                  {formData.englishTest === 'none' ? 'No English Test' : 
                   `${getCurrentEnglishTest().label}${formData.englishScore ? `: ${formData.englishScore}` : ''}`}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <Building className="w-4 h-4 text-gray-500" />
                <span>{formData.university}</span>
              </div>
              <div className="flex items-center gap-2">
                <BookOpen className="w-4 h-4 text-gray-500" />
                <span>{formData.course}</span>
              </div>
              <div className="flex items-center gap-2">
                <Globe className="w-4 h-4 text-gray-500" />
                <span>{formData.country}</span>
              </div>
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4 text-gray-500" />
                <span>{new Date().toLocaleDateString()}</span>
              </div>
            </div>
          </div>
          
          <div 
            className="ai-study-plan-output"
            dangerouslySetInnerHTML={{ 
              __html: studyPlan 
            }}
          />
          
          {isSubmitted && (
            <div className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 rounded-xl border border-green-200">
              <div className="flex items-center gap-3">
                <div className="p-2 rounded-lg bg-green-100">
                  <Check className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <div className="font-medium text-green-800">Study plan generated successfully!</div>
                  <div className="text-sm text-green-600">Your plan has been saved to our database</div>
                </div>
              </div>
            </div>
          )}
        </div>
      );
    }
    
    return (
      <div className="h-full flex flex-col items-center justify-center text-center p-8">
        <div className="w-20 h-20 rounded-full flex items-center justify-center mb-6" 
          style={{ backgroundColor: 'rgba(11, 109, 118, 0.1)' }}>
          <BookOpen className="w-10 h-10" style={{ color: '#0B6D76' }} />
        </div>
        <h3 className="text-xl font-medium mb-3">Ready for Your Study Plan</h3>
        <p className="text-gray-600 max-w-md">
          Fill in your academic details and generate a personalized AI study plan.
          Get actionable steps for your educational goals.
        </p>
        <div className="mt-8 grid grid-cols-2 gap-4">
          {[
            '📅 Weekly Schedule',
            '🎯 Goal Setting',
            '📚 Resources',
            '📈 Progress Track'
          ].map((feature, index) => (
            <div key={index} className="px-4 py-3 bg-white rounded-xl border border-gray-200 text-sm">
              {feature}
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-gray-50 to-white">
      <style jsx global>{`
        .ai-study-plan-output {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          line-height: 1.6;
          color: #374151;
          width: 100%;
          overflow-x: hidden;
        }
        
        .ai-study-plan-content {
          width: 100%;
          max-width: 100%;
          overflow-x: hidden;
        }
        
        .ai-study-plan-output h1 {
          font-size: 1.75rem;
          font-weight: 700;
          color: #0B6D76;
          margin-bottom: 1.5rem;
          padding-bottom: 0.5rem;
          border-bottom: 2px solid #e5e7eb;
          width: 100%;
          max-width: 100%;
          word-wrap: break-word;
        }
        
        .ai-study-plan-output h2 {
          font-size: 1.5rem;
          font-weight: 600;
          color: #0B6D76;
          margin-top: 2rem;
          margin-bottom: 1rem;
          width: 100%;
          max-width: 100%;
          word-wrap: break-word;
        }
        
        .ai-study-plan-output h3 {
          font-size: 1.25rem;
          font-weight: 600;
          color: #4b5563;
          margin-top: 1.5rem;
          margin-bottom: 0.75rem;
          width: 100%;
          max-width: 100%;
          word-wrap: break-word;
        }
        
        .ai-study-plan-output p {
          font-size: 1rem;
          margin-bottom: 1rem;
          color: #4b5563;
          width: 100%;
          max-width: 100%;
          word-wrap: break-word;
        }
        
        .ai-study-plan-output ul {
          margin-bottom: 1.5rem;
          padding-left: 1.5rem;
          width: 100%;
          max-width: 100%;
          list-style-type: disc !important;
        }
        
        .ai-study-plan-output ol {
          margin-bottom: 1.5rem;
          padding-left: 1.5rem;
          width: 100%;
          max-width: 100%;
          list-style-type: decimal !important;
        }
        
        .ai-study-plan-output li {
          margin-bottom: 0.5rem;
          color: #4b5563;
          width: 100%;
          max-width: 100%;
          word-wrap: break-word;
          display: list-item !important;
        }
        
        .ai-study-plan-output ul li::before {
          content: "•";
          color: #0B6D76;
          font-weight: bold;
          display: inline-block;
          width: 1em;
          margin-left: -1em;
        }
        
        .ai-study-plan-output ol li {
          list-style-type: decimal !important;
          display: list-item !important;
        }
        
        .ai-study-plan-output strong {
          font-weight: 600;
          color: #0B6D76;
        }
        
        .ai-study-plan-output em {
          font-style: italic;
          color: #6b7280;
        }
        
        .ai-study-plan-output * {
          box-sizing: border-box;
          max-width: 100%;
        }
      `}</style>

      <div className="relative overflow-hidden bg-gradient-to-br from-white via-blue-50/50 to-emerald-50/50">
        <div className="absolute inset-0 bg-gradient-to-br from-[#0B6D76]/5 to-transparent"></div>
        <div className="absolute top-0 right-0 w-96 h-96 bg-gradient-to-br from-[#0B6D76]/10 to-teal-300/10 rounded-full blur-3xl transform translate-x-64 -translate-y-64"></div>
        <div className="absolute bottom-0 left-0 w-96 h-96 bg-gradient-to-tr from-emerald-200/20 to-blue-100/20 rounded-full blur-3xl transform -translate-x-64 translate-y-64"></div>
        
        <div className="relative max-w-7xl mx-auto px-4 py-16 lg:py-24">
          <div className="text-center max-w-4x mx-auto">
            <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/80 backdrop-blur-sm border border-[#0B6D76]/10 mb-6">
              <Sparkles className="w-4 h-4" style={{ color: '#0B6D76' }} />
              <span className="text-sm font-medium" style={{ color: '#0B6D76' }}>
                Powered by UnversitiesPage AI
              </span>
            </div>
            
            <h1 className="text-5xl lg:text-6xl font-bold mb-6 leading-tight">
              AI-Powered
              <span className="block" style={{ color: '#0B6D76' }}>Study Plan Generator</span>
            </h1>
            
            <p className="text-xl text-gray-600 mb-10">
              Get a personalized academic roadmap tailored to your goals, background, and target university.
              Our AI creates actionable study plans to guide your educational journey.
            </p>
            
            <div className="flex flex-wrap justify-center gap-6 mb-12">
              {[
                { icon: <Target className="w-6 h-6" />, text: 'Goal-Oriented' },
                { icon: <Clock className="w-6 h-6" />, text: 'Time-Efficient' },
                { icon: <Award className="w-6 h-6" />, text: 'Personalized' },
                { icon: <Check className="w-6 h-6" />, text: 'Actionable' }
              ].map((item, index) => (
                <div key={index} className="flex items-center gap-2 px-4 py-2 bg-white/60 rounded-full backdrop-blur-sm">
                  <div className="p-1.5 rounded-lg" style={{ backgroundColor: 'rgba(11, 109, 118, 0.1)' }}>
                    {item.icon}
                  </div>
                  <span className="text-sm font-medium">{item.text}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 py-8 lg:py-12">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-12">
          <div className="space-y-8">
            <div className="bg-white rounded-2xl shadow-lg p-6 lg:p-8">
              <div className="flex items-center gap-3 mb-8">
                <div className="p-3 rounded-xl" style={{ backgroundColor: 'rgba(11, 109, 118, 0.1)' }}>
                  <BookOpen className="w-6 h-6" style={{ color: '#0B6D76' }} />
                </div>
                <div>
                  <h2 className="text-2xl font-bold">Create Your Study Plan</h2>
                  <p className="text-gray-600">Fill in your academic details below</p>
                </div>
              </div>

              <div className="space-y-6">
                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <User className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      Full Name *
                    </label>
                  </div>
                  <input
                    type="text"
                    name="fullName"
                    value={formData.fullName}
                    onChange={handleFormChange}
                    required
                    className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="Enter your full name"
                  />
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <Flag className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      Nationality
                    </label>
                  </div>
                  <input
                    type="text"
                    name="nationality"
                    value={formData.nationality}
                    onChange={handleFormChange}
                    className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="e.g., Pakistani, Indian, etc."
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <GraduationCap className="w-4 h-4 text-gray-500" />
                      <label className="block text-sm font-medium text-gray-700">
                        Last Education *
                      </label>
                    </div>
                    <input
                      type="text"
                      name="lastEducation"
                      value={formData.lastEducation}
                      onChange={handleFormChange}
                      required
                      className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                      placeholder="e.g., BSc Computer Science"
                    />
                  </div>
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-gray-500">🏫</span>
                      <label className="block text-sm font-medium text-gray-700">
                        Education Level *
                      </label>
                    </div>
                    <div className="relative">
                      <select
                        name="educationLevel"
                        value={formData.educationLevel}
                        onChange={handleFormChange}
                        required
                        className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 appearance-none transition-all duration-300"
                      >
                        <option value="">Select Level</option>
                        {educationLevels.map(level => (
                          <option key={level.value} value={level.value}>
                            {level.icon} {level.label}
                          </option>
                        ))}
                      </select>
                      <ChevronDown className="absolute right-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
                    </div>
                  </div>
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <Award className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      CGPA/Marks *
                    </label>
                  </div>
                  <div className="flex gap-3">
                    <div className="relative flex-1 min-w-0">
                      <select className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 appearance-none transition-all duration-300">
                        <option value="cgpa">CGPA</option>
                        <option value="percentage">Percentage</option>
                      </select>
                      <ChevronDown className="absolute right-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
                    </div>
                    <input
                      type="text"
                      name="cgpa"
                      value={formData.cgpa}
                      onChange={handleFormChange}
                      required
                      className="flex-1 px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                      placeholder="e.g., 3.5 or 85%"
                    />
                  </div>
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <Calendar className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      Study Gap (if any)
                    </label>
                  </div>
                  <input
                    type="text"
                    name="studyGap"
                    value={formData.studyGap}
                    onChange={handleFormChange}
                    className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="e.g., 2 years after graduation"
                  />
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <MessageSquare className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      Gap Justification / Experience
                    </label>
                  </div>
                  <textarea
                    name="gapJustification"
                    value={formData.gapJustification}
                    onChange={handleFormChange}
                    rows={3}
                    className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300 resize-none"
                    placeholder="Explain what you did during the gap period, work experience, internships, etc."
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <Languages className="w-4 h-4 text-gray-500" />
                      <label className="block text-sm font-medium text-gray-700">
                        English Proficiency Test
                      </label>
                    </div>
                    <div className="relative">
                      <select
                        name="englishTest"
                        value={formData.englishTest}
                        onChange={handleFormChange}
                        className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 appearance-none transition-all duration-300"
                      >
                        {englishTests.map(test => (
                          <option key={test.value} value={test.value}>
                            {test.label}
                          </option>
                        ))}
                      </select>
                      <ChevronDown className="absolute right-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-gray-500">📊</span>
                      <label className="block text-sm font-medium text-gray-700">
                        Test Score {formData.englishTest !== 'none' && `(Max: ${getCurrentEnglishTest().maxScore})`}
                      </label>
                    </div>
                    <input
                      type="number"
                      name="englishScore"
                      value={formData.englishScore}
                      onChange={handleFormChange}
                      disabled={formData.englishTest === 'none'}
                      step={getCurrentEnglishTest().step}
                      min="0"
                      max={getCurrentEnglishTest().maxScore}
                      className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                      placeholder={getCurrentEnglishTest().placeholder}
                    />
                  </div>
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <Globe className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      Target Country *
                    </label>
                  </div>
                  <input
                    type="text"
                    name="country"
                    value={formData.country}
                    onChange={handleFormChange}
                    required
                    className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="e.g., United States"
                  />
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <Building className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      Target University *
                    </label>
                  </div>
                  <input
                    type="text"
                    name="university"
                    value={formData.university}
                    onChange={handleFormChange}
                    required
                    className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="e.g., Stanford University"
                  />
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-2">
                    <BookOpen className="w-4 h-4 text-gray-500" />
                    <label className="block text-sm font-medium text-gray-700">
                      Target Course/Program *
                    </label>
                  </div>
                  <input
                    type="text"
                    name="course"
                    value={formData.course}
                    onChange={handleFormChange}
                    required
                    className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="e.g., Master of Computer Science"
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <FileText className="w-4 h-4 text-gray-500" />
                      <label className="block text-sm font-medium text-gray-700">
                        Response Length
                      </label>
                    </div>
                    <div className="relative">
                      <select
                        name="wordCount"
                        value={formData.wordCount}
                        onChange={handleFormChange}
                        className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 appearance-none transition-all duration-300"
                      >
                        {wordCountOptions.map(option => (
                          <option key={option} value={option}>
                            {option} words
                          </option>
                        ))}
                      </select>
                      <ChevronDown className="absolute right-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
                    </div>
                  </div>
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <Sparkles className="w-4 h-4 text-gray-500" />
                      <label className="block text-sm font-medium text-gray-700">
                        Response Style
                      </label>
                    </div>
                    <div className="relative">
                      <select
                        name="responseStyle"
                        value={formData.responseStyle}
                        onChange={handleFormChange}
                        className="w-full px-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 appearance-none transition-all duration-300"
                      >
                        {responseStyles.map(style => (
                          <option key={style.value} value={style.value}>
                            {style.label}
                          </option>
                        ))}
                      </select>
                      <ChevronDown className="absolute right-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 pointer-events-none" />
                    </div>
                  </div>
                </div>

                <button
                  onClick={handleGenerateClick}
                  disabled={loading}
                  className="w-full mt-2 py-4 px-6 rounded-xl font-semibold text-white transition-all duration-300 hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed transform hover:-translate-y-0.5 active:translate-y-0"
                  style={{ 
                    backgroundColor: '#0B6D76',
                    backgroundImage: 'linear-gradient(to right, #0B6D76, #0A5A62)'
                  }}
                >
                  {loading ? (
                    <div className="flex items-center justify-center gap-3">
                      <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                      Generating AI Study Plan...
                    </div>
                  ) : (
                    'Generate AI Study Plan'
                  )}
                </button>
              </div>
            </div>
          </div>

          <div className="space-y-8">
            <div className="bg-white rounded-2xl shadow-lg p-6 lg:p-8 flex flex-col h-full">
              <div className="flex items-center gap-3 mb-8">
                <div className="p-3 rounded-xl" style={{ backgroundColor: 'rgba(11, 109, 118, 0.1)' }}>
                  <Sparkles className="w-6 h-6" style={{ color: '#0B6D76' }} />
                </div>
                <div>
                  <h2 className="text-2xl font-bold">Your AI Study Plan</h2>
                  <p className="text-gray-600">Powered by UnversitiesPage AI • Real-time generation</p>
                </div>
              </div>

              <div 
                ref={resultsRef}
                className="flex-1 border-2 border-dashed border-gray-200 rounded-2xl p-6 min-h-[500px] max-h-[500px] overflow-y-auto bg-gray-50/30"
              >
                <ResultsDisplay />
              </div>

              {studyPlan && (
                <div className="mt-8 pt-6 border-t border-gray-200">
                  <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                      <h4 className="font-medium">Download Options</h4>
                      <p className="text-sm text-gray-500">Save your study plan offline</p>
                    </div>
                    <div className="flex gap-3">
                      <button
                        onClick={generatePDF}
                        disabled={isDownloading || !studyPlan}
                        className="px-6 py-3 rounded-lg border-2 border-gray-200 hover:border-[#0B6D76] hover:bg-[#0B6D76] hover:text-white transition-all duration-300 flex items-center gap-2 group transform hover:-translate-y-0.5 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {isDownloading ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <File className="w-4 h-4" />
                        )}
                        PDF
                      </button>
                      <button
                        onClick={generateWordDocument}
                        disabled={isDownloading || !studyPlan}
                        className="px-6 py-3 rounded-lg border-2 border-gray-200 hover:border-[#0B6D76] hover:bg-[#0B6D76] hover:text-white transition-all duration-300 flex items-center gap-2 group transform hover:-translate-y-0.5 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {isDownloading ? (
                          <Loader2 className="w-4 h-4 animate-spin" />
                        ) : (
                          <FileDoc className="w-4 h-4" />
                        )}
                        Word
                      </button>
                    </div>
                  </div>
                  <div className="mt-4 p-4 bg-blue-50 rounded-xl">
                    <div className="flex items-start gap-3">
                      <Sparkles className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
                      <p className="text-sm text-blue-800">
                        <strong>Note:</strong> This AI-generated plan serves as a guideline. 
                        Always verify information with official university resources.
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {showUserInfoModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6 animate-in fade-in zoom-in-95 duration-300">
            <div className="flex items-center gap-3 mb-6">
              <div className="p-3 rounded-xl" style={{ backgroundColor: 'rgba(11, 109, 118, 0.1)' }}>
                <User className="w-6 h-6" style={{ color: '#0B6D76' }} />
              </div>
              <div>
                <h3 className="text-xl font-bold">Complete Your Profile</h3>
                <p className="text-gray-600">We`ll remember you for 7 days</p>
              </div>
            </div>

            <div className="space-y-5">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Full Name *
                </label>
                <div className="relative">
                  <User className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    type="text"
                    name="fullName"
                    value={userInfo.fullName}
                    onChange={handleUserInfoChange}
                    required
                    className="w-full pl-12 pr-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="Enter your full name"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Email Address *
                </label>
                <div className="relative">
                  <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    type="email"
                    name="email"
                    value={userInfo.email}
                    onChange={handleUserInfoChange}
                    required
                    className="w-full pl-12 pr-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="your@email.com"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Phone Number (Optional)
                </label>
                <div className="relative">
                  <Phone className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    type="tel"
                    name="phone"
                    value={userInfo.phone}
                    onChange={handleUserInfoChange}
                    className="w-full pl-12 pr-4 py-3.5 rounded-xl border border-gray-200 bg-gray-50/50 focus:bg-white focus:border-[#0B6D76] focus:ring-2 focus:ring-[#0B6D76]/20 transition-all duration-300"
                    placeholder="+1 (555) 123-4567"
                  />
                </div>
              </div>
            </div>

            <div className="mt-8 flex gap-3">
              <button
                onClick={() => setShowUserInfoModal(false)}
                className="flex-1 px-6 py-3.5 rounded-xl border-2 border-gray-300 hover:bg-gray-50 transition-all duration-300 font-medium"
              >
                Cancel
              </button>
              <button
                onClick={handleUserInfoSubmit}
                className="flex-1 px-6 py-3.5 rounded-xl font-semibold text-white transition-all hover:shadow-lg transform hover:-translate-y-0.5"
                style={{ 
                  backgroundColor: '#0B6D76',
                  backgroundImage: 'linear-gradient(to right, #0B6D76, #0A5A62)'
                }}
              >
                Save & Generate
              </button>
            </div>

            <p className="text-xs text-gray-500 text-center mt-6">
              Your information will be stored locally for 7 days. No spam, ever.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}