'use client'

import React, { createContext, useContext, useState, useEffect } from 'react'

type Language = 'en' | 'ar'

type LanguageContextType = {
  language: Language
  setLanguage: (lang: Language) => void
  t: (key: string) => string
  dir: 'ltr' | 'rtl'
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined)

export const useLanguage = () => {
  const context = useContext(LanguageContext)
  if (context === undefined) {
    throw new Error('useLanguage must be used within a LanguageProvider')
  }
  return context
}

type TranslationKeys = keyof typeof translations.en;

// Comprehensive translations for UTAS portal
const translations = {
  en: {
    // Navigation
    'welcome': 'Welcome to University Portal',
    'login': 'Login',
    'logout': 'Logout',
    'dashboard': 'Dashboard',
    'chat': 'Chat',
    'wellbeing': 'Wellbeing',
    'accessibility': 'Accessibility',
    'admin': 'Admin',
    'courses': 'Courses',
    'research': 'Research',
    'admissions': 'Admissions',
    'scholarships': 'Scholarships',
    'privacy': 'Privacy',
    
    // Common actions
    'search': 'Search',
    'filter': 'Filter',
    'apply_now': 'Apply Now',
    'learn_more': 'Learn More',
    'read_more': 'Read More',
    'contact_us': 'Contact Us',
    'get_started': 'Get Started',
    'download': 'Download',
    'register': 'Register',
    'book_now': 'Book Now',
    'submit': 'Submit',
    'cancel': 'Cancel',
    'save': 'Save',
    'edit': 'Edit',
    'delete': 'Delete',
    'view_all': 'View All',
    'back': 'Back',
    'next': 'Next',
    'previous': 'Previous',
    
    // Chat interface
    'ask_question': 'Ask a question...',
    'send': 'Send',
    'type_message': 'Type your message...',
    'chat_with_ai': 'Chat with AI Assistant',
    'how_can_help': 'How can I help you today?',
    
    // Forms and inputs
    'first_name': 'First Name',
    'last_name': 'Last Name',
    'email': 'Email',
    'phone': 'Phone',
    'message': 'Message',
    'subject': 'Subject',
    'required_field': 'Required field',
    'optional': 'Optional',
    
    // Academic content
    'undergraduate': 'Undergraduate',
    'postgraduate': 'Postgraduate',
    'research_degrees': 'Research Degrees',
    'study_areas': 'Study Areas',
    'entry_requirements': 'Entry Requirements',
    'course_duration': 'Course Duration',
    'annual_fees': 'Annual Fees',
    'campus_locations': 'Campus Locations',
    'career_outcomes': 'Career Outcomes',
    'key_features': 'Key Features',
    
    // Specific content
    'mental_health_support': 'Mental Health Support',
    'book_counselor': 'Book with Counselor',
    'upload_image': 'Upload Image',
    'alt_text_suggestion': 'Alt Text Suggestion',
    'wcag_score': 'WCAG Score',
    'survey_rating': 'How would you rate your experience?',
    'submit_feedback': 'Submit Feedback',
    'registration_opens': 'Registration opens August 15th',
    'tuition_balance': 'Tuition Balance',
    'advisor_contact': 'Advisor Contact',
    'my_courses': 'My Courses',
    'scholarship_deadlines': 'Scholarship Deadlines',
    'transfer_engineering': 'Transfer to Engineering',
    'library_location': 'Library Location',
    'contact_advisor': 'Contact Advisor',
    'class_registration': 'Class Registration',
    
    // Status and notifications
    'loading': 'Loading...',
    'error': 'Error',
    'success': 'Success',
    'warning': 'Warning',
    'info': 'Information',
    'no_results': 'No results found',
    'try_again': 'Try again',
    
    // Homepage content
    'hero_title': 'Shape Your Future at UTAS',
    'hero_subtitle': 'Join the world\'s #1 university for climate action and discover limitless possibilities in Tasmania\'s unique island campus.',
    'climate_action_leader': 'Climate Action Leader',
    'global_ranking': 'Global Ranking #1',
    'students_worldwide': 'Students Worldwide',
    'research_excellence': 'Research Excellence',
    
    // Features
    'ai_assistant': 'AI Assistant',
    'ai_assistant_desc': 'Get instant help with courses, applications, and campus life',
    'accessibility_tools': 'Accessibility Tools',
    'accessibility_desc': 'AI-powered tools for inclusive education and digital accessibility',
    'mental_health': 'Mental Health Support',
    'mental_health_desc': 'Comprehensive wellbeing services and counseling support',
    'smart_analytics': 'Smart Analytics',
    'analytics_desc': 'Data-driven insights for better student outcomes',
    
    // About UTAS
    'about_utas': 'About UTAS',
    'utas_description': 'The University of Tasmania is a world-class institution dedicated to creating brighter futures through transformative education and research that benefits our island, our nation, and our world.',
    'why_choose_utas': 'Why Choose UTAS?',
    'island_advantage': 'Island Advantage',
    'island_desc': 'Our unique island location provides an unparalleled living laboratory',
    'research_impact': 'Research Impact',
    'research_desc': 'Contributing to global solutions through world-leading research',
    'student_experience': 'Student Experience',
    'experience_desc': 'Personalized education with strong industry connections',
    
    // Footer
    'quick_links': 'Quick Links',
    'contact_info': 'Contact Information',
    'follow_us': 'Follow Us',
    'copyright': '© 2024 University of Tasmania. All rights reserved.',
    
    // Accessibility
    'accessibility_statement': 'Accessibility Statement',
    'keyboard_navigation': 'Keyboard Navigation',
    'screen_reader': 'Screen Reader Compatible',
    'high_contrast': 'High Contrast Mode',
    'text_size': 'Text Size',
    'increase_text': 'Increase Text Size',
    'decrease_text': 'Decrease Text Size',
    
    // Error messages
    'page_not_found': 'Page Not Found',
    'something_went_wrong': 'Something went wrong',
    'network_error': 'Network error. Please check your connection.',
    'invalid_input': 'Please check your input and try again',
    
    // Success messages
    'form_submitted': 'Form submitted successfully',
    'application_received': 'Application received',
    'email_sent': 'Email sent successfully',
    'profile_updated': 'Profile updated',
    
    // Date and time
    'today': 'Today',
    'yesterday': 'Yesterday',
    'tomorrow': 'Tomorrow',
    'this_week': 'This Week',
    'next_week': 'Next Week',
    'this_month': 'This Month',
    'next_month': 'Next Month',
    
    // Campus names
    'hobart_campus': 'Hobart Campus',
    'launceston_campus': 'Launceston Campus',
    'burnie_campus': 'Burnie Campus',
    'sydney_campus': 'Sydney Campus',
    
    // Study modes
    'full_time': 'Full-time',
    'part_time': 'Part-time',
    'online': 'Online',
    'blended': 'Blended',
    'evening': 'Evening',
    'weekend': 'Weekend',
    
    // Application process
    'how_to_apply': 'How to Apply',
    'application_deadlines': 'Application Deadlines',
    'domestic_students': 'Domestic Students',
    'international_students': 'International Students',
    'application_fee': 'Application Fee',
    'required_documents': 'Required Documents',
    'english_requirements': 'English Requirements',
    'academic_requirements': 'Academic Requirements',
  },
  ar: {
    // Navigation
    'welcome': 'مرحباً بكم في بوابة الجامعة',
    'login': 'تسجيل الدخول',
    'logout': 'تسجيل الخروج',
    'dashboard': 'لوحة التحكم',
    'chat': 'المحادثة',
    'wellbeing': 'الرفاهية',
    'accessibility': 'إمكانية الوصول',
    'admin': 'المسؤول',
    'courses': 'المقررات',
    'research': 'البحث',
    'admissions': 'القبول',
    'scholarships': 'المنح الدراسية',
    'privacy': 'الخصوصية',
    
    // Common actions
    'search': 'بحث',
    'filter': 'تصفية',
    'apply_now': 'قدم الآن',
    'learn_more': 'اعرف المزيد',
    'read_more': 'اقرأ المزيد',
    'contact_us': 'اتصل بنا',
    'get_started': 'ابدأ الآن',
    'download': 'تحميل',
    
    // Chat related
    'chat_placeholder': 'اكتب رسالتك هنا...',
    'chat_start': 'ابدأ المحادثة',
    'chat_end': 'إنهاء المحادثة',
    'chat_loading': 'جارٍ التحميل...',
    'chat_error': 'عذراً، حدث خطأ. يرجى المحاولة مرة أخرى.',
    'chat_welcome': 'مرحباً! كيف يمكنني مساعدتك اليوم؟',
    
    // Wellbeing
    'mental_health_support': 'دعم الصحة النفسية',
    'book_counselor': 'احجز موعداً مع مستشار',
    'emergency_contacts': 'جهات اتصال للطوارئ',
    'wellness_resources': 'موارد العافية',
    
    // Course related
    'course_search': 'البحث عن المقررات',
    'course_apply': 'التقدم للمقرر',
    'course_details': 'تفاصيل المقرر',
    'prerequisites': 'المتطلبات السابقة',
    'course_duration': 'مدة المقرر',
    'start_dates': 'تواريخ البدء',
    
    // Research
    'research_areas': 'مجالات البحث',
    'publications': 'المنشورات',
    'funding': 'التمويل',
    'partnerships': 'الشراكات',
    
    // Student services
    'student_support': 'دعم الطلاب',
    'library_services': 'خدمات المكتبة',
    'it_support': 'الدعم التقني',
    'housing': 'السكن',
    
    // Accessibility
    'accessibility_options': 'خيارات إمكانية الوصول',
    'screen_reader': 'قارئ الشاشة',
    'high_contrast': 'تباين عالي',
    'text_size': 'حجم النص',
    
    // Error messages
    'error_404': 'الصفحة غير موجودة',
    'error_500': 'خطأ في الخادم',
    'try_again': 'حاول مرة أخرى',
    'go_back': 'العودة'
  }
}

export const LanguageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [language, setLanguage] = useState<Language>('en')
  const [dir, setDir] = useState<'ltr' | 'rtl'>('ltr')

  useEffect(() => {
    setDir(language === 'ar' ? 'rtl' : 'ltr')
    document.documentElement.dir = language === 'ar' ? 'rtl' : 'ltr'
    document.documentElement.lang = language
  }, [language])

  const t = (key: string) => {
    return translations[language][key as TranslationKeys] || key
  }

  const value = {
    language,
    setLanguage,
    t,
    dir,
  }

  return (
    <LanguageContext.Provider value={value}>
      {children}
    </LanguageContext.Provider>
  )
}
