const { useState, useEffect, useRef } = React;

// Translations
const translations = {
  uz: {
    nav: {
      about: 'Men haqimda',
      achievements: 'Yutuqlar',
      projects: 'Loyihalar',
      publications: 'Nashrlar',
      contact: 'Aloqa',
    },
    hero: {
      tagline: 'Sun\'iy intellekt mutaxassisi',
      subtitle: 'Tibbiyot, Biotexnologiya va boshqa sohalarda',
      greeting: 'Salom, men',
      description: 'Men biotexnologiya, molekulyar genetika, sog\'liqni saqlash va boshqa sohalarda sun\'iy intellektni qo\'llash bo\'yicha ishlayman. AI modellar, dasturlar va botlar yarataman.',
      viewProjects: 'Loyihalarni ko\'rish',
      contactMe: 'Bog\'lanish',
      specialization: 'Mutaxassislik',
      specializationText: 'AI Tibbiyot va boshqa sohalar uchun',
      location: 'Joylashuv',
      locationText: 'Pisa, Italiya · O\'zbekiston',
      email: 'Email',
    },
    about: {
      title: 'Men haqimda',
      intro: 'Maqsadim — Tibbiyot, Biotexnologiya va boshqa sohalardagi jarayonlarga zamonaviy AI modellari yordamida tahlil qilishni joriy qilish.',
      description: 'Men biotexnologiya, molekulyar genetika va sog\'liqni saqlashda sun\'iy intellektni qo\'llash bo\'yicha ishlayman. Menga jarayonlarni sun\'iy intellekt bilan integratsiyasini ta\'minlash, AI modellar, dasturlar va telegram botlar yaratish yuzasidan bog\'lanishingiz mumkin.',
      education: 'Ta\'lim',
      educationItems: [
        'Magistr — Biotexnologiya va AI Tibbiyotda, Pisa universiteti',
        'Magistr — Biotexnologiya, O\'zbekiston Milliy Universiteti',
      ],
      interests: 'Qiziqishlar',
      interestsItems: [
        'AI Tibbiyotda',
        'Genomika va Bioinformatika',
        'Tibbiy tasvirlarni tahlil qilish',
        'Federated Learning',
        'AI Integratsiya',
      ],
    },
    achievements: {
      title: 'Yutuqlar',
      items: [
        {
          title: 'Davlat Stipendiyalari',
          description: 'Mirzo Ulug\'bek va Prezident davlat stipendiyalari.',
        },
        {
          title: '"El-Yurt Umidi" Stipendiyasi',
          description: '"El-Yurt Umidi" jamg\'armasi granti asosida xorijda ta\'lim.',
        },
        {
          title: 'Innovatsion tanlovlar',
          description: 'Mirzo Ulug\'bek vorislari ilmiy-innovatsion loyihalar tanlovi g\'olibi.',
        },
      ],
    },
    projects: {
      title: 'Tanlangan Loyihalar',
      items: [
        {
          title: 'Rentgen tasvirlari asosida Pneumoniyani aniqlash',
          description: 'Katta hajmdagi rentgen tasvirlarida o\'qitilgan chuqur o\'rganish modeli. Normal sinf uchun 98% precision va Pneumonia sinfi uchun 99% recall ko\'rsatkichlariga erishilgan.',
          tech: 'Python, CNN, Medical Imaging',
          github: 'https://github.com/yourgithub/pneumonia-model',
          image: 'assets/xray1.jpg',
        },
        {
          title: 'EKG signallarini tahlil qiluvchi Model',
          description: '12,000 dan ortiq belgilangan EKG tasvirlari asosida o\'qitilgan model. Internetdan olingan random EKG rasmlarini yuqori aniqlik bilan tasnifladi.',
          tech: 'Python, Deep Learning, CNN',
          github: 'https://github.com/byShukrullo/ECG-classifier-',
          image: 'assets/ecg1.jpg',
        },
        {
          title: 'Surunkali Buyrak yetishmovchiligini aniqlash',
          description: 'Labarator tahlillar natijasi asosida aniqlovchi Model. Juda ham aniqlikda ishlaydi: 99.6-100%.',
          tech: 'Python, Random Forest',
          github: 'https://github.com/byShukrullo/ckd_classifier',
          image: 'assets/example_tets.png',
        },
      ],
    },
    publications: {
      title: 'Nashrlar va Ma\'ruzalar',
      items: [
        {
          title: 'Seminar: Tibbiyotda sun\'iy intellektdan foydalanish',
          description: 'Ilmiy seminar — Germaniya, 2025.',
        },
        {
          title: 'Seminar: Molecular Markers in Genomics',
          description: 'Genomika va Bioinformatika markazida molekulyar markerlar bo\'yicha ma\'ruza.',
        },
        {
          title: 'Juglans regia Genetic Studies',
          description: 'Oddiy yong\'oq navlari o\'rtasidagi genetik o\'xshashlikni mikrosatellit markerlar asosida tahlil qilish.',
        },
      ],
    },
    contact: {
      title: 'Aloqa',
      description: 'Hamkorlik, ilmiy loyihalar, AI platformalar yoki boshqa takliflar bo\'lsa, bemalol bog\'lanishingiz mumkin.',
      email: 'Email',
      linkedin: 'LinkedIn',
      github: 'GitHub',
      telegram: 'Telegram',
    },
    footer: {
      rights: 'Barcha huquqlar himoyalangan.',
    },
  },
  en: {
    nav: {
      about: 'About',
      achievements: 'Achievements',
      projects: 'Projects',
      publications: 'Publications',
      contact: 'Contact',
    },
    hero: {
      tagline: 'Artificial Intelligence Specialist',
      subtitle: 'in Healthcare, Biotechnology & Beyond',
      greeting: 'Hello, I\'m',
      description: 'I work on applying artificial intelligence in biotechnology, molecular genetics, healthcare, and other fields. I create AI models, applications, and telegram bots.',
      viewProjects: 'View Projects',
      contactMe: 'Contact Me',
      specialization: 'Specialization',
      specializationText: 'AI for Health and Other Fields',
      location: 'Location',
      locationText: 'Pisa, Italy · Uzbekistan',
      email: 'Email',
    },
    about: {
      title: 'About Me',
      intro: 'My goal is to integrate modern AI models into processes in Medicine, Biotechnology, and other fields for advanced analysis.',
      description: 'I work on applying artificial intelligence in biotechnology, molecular genetics, and healthcare. You can contact me about AI integration into processes, creating AI models, applications, and telegram bots.',
      education: 'Education',
      educationItems: [
        'Master — Biotechnologies and Applied AI for Health, University of Pisa',
        'Master — Biotechnology, National University of Uzbekistan',
      ],
      interests: 'Interests',
      interestsItems: [
        'AI in Healthcare',
        'Genomics & Bioinformatics',
        'Medical Image Analysis',
        'Federated Learning',
        'AI Integration',
      ],
    },
    achievements: {
      title: 'Achievements',
      items: [
        {
          title: 'State Scholarships',
          description: 'Mirzo Ulugbek and Presidential State Scholarships.',
        },
        {
          title: '"El-Yurt Umidi" Scholarship',
          description: 'Education abroad based on "El-Yurt Umidi" Foundation grant.',
        },
        {
          title: 'Student of the Year',
          description: 'Winner of Mirzo Ulugbek Heirs Scientific-Innovation Projects Competition.',
        },
      ],
    },
    projects: {
      title: 'Selected Projects',
      items: [
        {
          title: 'Pneumonia Detection from X-ray Images',
          description: 'Deep learning model trained on large-scale X-ray images. Achieved 98% precision for Normal class and 99% recall for Pneumonia class.',
          tech: 'Python, CNN, Medical Imaging',
          github: 'https://github.com/yourgithub/pneumonia-model',
          image: 'assets/xray1.jpg',
        },
        {
          title: 'ECG Signal Analysis Model',
          description: 'Model trained on over 12,000 labeled ECG images. Classifies random ECG images from the internet with high accuracy.',
          tech: 'Python, Deep Learning, CNN',
          github: 'https://github.com/byShukrullo/ECG-classifier-',
          image: 'assets/ecg1.jpg',
        },
        {
          title: 'Chronic Kidney Disease Classifier',
          description: 'Model that detects Chronic Kidney Disease based on laboratory test results. Works with very high accuracy: 99.6-100%.',
          tech: 'Python, Random Forest',
          github: 'https://github.com/byShukrullo/ckd_classifier',
          image: 'assets/example_tets.png',
        },
      ],
    },
    publications: {
      title: 'Publications & Talks',
      items: [
        {
          title: 'Seminar: Using AI in Medicine',
          description: 'Scientific seminar — Germany, 2025.',
        },
        {
          title: 'Seminar: Molecular Markers in Genomics',
          description: 'Lecture on molecular markers at the Genomics and Bioinformatics Center.',
        },
        {
          title: 'Juglans regia Genetic Studies',
          description: 'Analysis of genetic similarity between walnut varieties using microsatellite markers.',
        },
      ],
    },
    contact: {
      title: 'Contact',
      description: 'If you have collaboration opportunities, scientific projects, AI platforms, or other proposals, feel free to reach out.',
      email: 'Email',
      linkedin: 'LinkedIn',
      github: 'GitHub',
      telegram: 'Telegram',
    },
    footer: {
      rights: 'All rights reserved.',
    },
  },
  ru: {
    nav: {
      about: 'Обо мне',
      achievements: 'Достижения',
      projects: 'Проекты',
      publications: 'Публикации',
      contact: 'Контакты',
    },
    hero: {
      tagline: 'Специалист по искусственному интеллекту',
      subtitle: 'в медицине, биотехнологии и других областях',
      greeting: 'Здравствуйте, я',
      description: 'Я работаю над применением искусственного интеллекта в биотехнологии, молекулярной генетике, здравоохранении и других областях. Создаю AI модели, приложения и telegram боты.',
      viewProjects: 'Посмотреть проекты',
      contactMe: 'Связаться',
      specialization: 'Специализация',
      specializationText: 'ИИ для медицины и других областей',
      location: 'Местоположение',
      locationText: 'Пиза, Италия · Узбекистан',
      email: 'Email',
    },
    about: {
      title: 'Обо мне',
      intro: 'Моя цель — интегрировать современные модели ИИ в процессы медицины, биотехнологии и других областей для продвинутого анализа.',
      description: 'Я работаю над применением искусственного интеллекта в биотехнологии, молекулярной генетике и здравоохранении. Можете связаться со мной по вопросам интеграции ИИ в процессы, создания AI моделей, приложений и telegram ботов.',
      education: 'Образование',
      educationItems: [
        'Магистр — Биотехнологии и прикладной ИИ в медицине, Университет Пизы',
        'Магистр — Биотехнология, Национальный университет Узбекистана',
      ],
      interests: 'Интересы',
      interestsItems: [
        'ИИ в здравоохранении',
        'Геномика и биоинформатика',
        'Анализ медицинских изображений',
        'Федеративное обучение',
        'Интеграция ИИ',
      ],
    },
    achievements: {
      title: 'Достижения',
      items: [
        {
          title: 'Государственные стипендии',
          description: 'Государственные стипендии Мирзо Улугбека и Президента.',
        },
        {
          title: 'Стипендия "El-Yurt Umidi"',
          description: 'Обучение за рубежом на основе гранта фонда "El-Yurt Umidi".',
        },
        {
          title: 'Студент года',
          description: 'Победитель конкурса научно-инновационных проектов наследников Мирзо Улугбека.',
        },
      ],
    },
    projects: {
      title: 'Избранные проекты',
      items: [
        {
          title: 'Обнаружение пневмонии по рентгеновским снимкам',
          description: 'Модель глубокого обучения, обученная на большом объеме рентгеновских изображений. Достигнута точность 98% для нормального класса и 99% recall для класса пневмонии.',
          tech: 'Python, CNN, Medical Imaging',
          github: 'https://github.com/yourgithub/pneumonia-model',
          image: 'assets/xray1.jpg',
        },
        {
          title: 'Модель анализа ЭКГ сигналов',
          description: 'Модель обучена на более чем 12,000 размеченных изображениях ЭКГ. Классифицирует случайные изображения ЭКГ из интернета с высокой точностью.',
          tech: 'Python, Deep Learning, CNN',
          github: 'https://github.com/byShukrullo/ECG-classifier-',
          image: 'assets/ecg1.jpg',
        },
        {
          title: 'Классификатор хронической болезни почек',
          description: 'Модель обнаруживает хроническую болезнь почек на основе результатов лабораторных анализов. Работает с очень высокой точностью: 99.6-100%.',
          tech: 'Python, Random Forest',
          github: 'https://github.com/byShukrullo/ckd_classifier',
          image: 'assets/example_tets.png',
        },
      ],
    },
    publications: {
      title: 'Публикации и выступления',
      items: [
        {
          title: 'Семинар: Использование ИИ в медицине',
          description: 'Научный семинар — Германия, 2025.',
        },
        {
          title: 'Семинар: Молекулярные маркеры в геномике',
          description: 'Лекция о молекулярных маркерах в Центре геномики и биоинформатики.',
        },
        {
          title: 'Генетические исследования Juglans regia',
          description: 'Анализ генетического сходства между сортами грецкого ореха с использованием микросателлитных маркеров.',
        },
      ],
    },
    contact: {
      title: 'Контакты',
      description: 'Если у вас есть возможности для сотрудничества, научные проекты, AI платформы или другие предложения, свяжитесь со мной.',
      email: 'Email',
      linkedin: 'LinkedIn',
      github: 'GitHub',
      telegram: 'Telegram',
    },
    footer: {
      rights: 'Все права защищены.',
    },
  },
};

// Navbar Component
const Navbar = ({ language, setLanguage, t }) => {
  const [isScrolled, setIsScrolled] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 50);
    };
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const languages = [
    { code: 'uz', label: 'UZ' },
    { code: 'en', label: 'EN' },
    { code: 'ru', label: 'RU' },
  ];

  return (
    <nav className={`navbar ${isScrolled ? 'scrolled' : ''}`}>
      <div className="container">
        <div className="nav-content">
          <a href="#" className="logo">
            by<span>Shukrullo</span>
          </a>

          <div className={`nav-links ${isMobileMenuOpen ? 'active' : ''}`}>
            <a href="#about" onClick={() => setIsMobileMenuOpen(false)}>{t.nav.about}</a>
            <a href="#achievements" onClick={() => setIsMobileMenuOpen(false)}>{t.nav.achievements}</a>
            <a href="#projects" onClick={() => setIsMobileMenuOpen(false)}>{t.nav.projects}</a>
            <a href="#publications" onClick={() => setIsMobileMenuOpen(false)}>{t.nav.publications}</a>
            <a href="#contact" onClick={() => setIsMobileMenuOpen(false)}>{t.nav.contact}</a>
          </div>

          <div className="nav-actions">
            <div className="language-selector">
              {languages.map((lang) => (
                <button
                  key={lang.code}
                  className={`lang-btn ${language === lang.code ? 'active' : ''}`}
                  onClick={() => setLanguage(lang.code)}
                >
                  {lang.label}
                </button>
              ))}
            </div>
            <button
              className="mobile-menu-btn"
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            >
              <i data-lucide={isMobileMenuOpen ? 'x' : 'menu'}></i>
            </button>
          </div>
        </div>
      </div>
    </nav>
  );
};

// Hero Component
const Hero = ({ t }) => {
  return (
    <section className="hero">
      <div className="hero-bg">
        <div className="gradient-orb orb-1"></div>
        <div className="gradient-orb orb-2"></div>
        <div className="gradient-orb orb-3"></div>
      </div>
      
      <div className="container">
        <div className="hero-content">
          <div className="hero-text" data-animate="fade-up">
            <p className="tagline">
              <span className="tagline-dot"></span>
              {t.hero.tagline}
            </p>
            <p className="subtitle">{t.hero.subtitle}</p>
            <h1>
              {t.hero.greeting} <span className="gradient-text">Shukrullo Foziljonov</span>
            </h1>
            <p className="description">{t.hero.description}</p>
            <div className="hero-actions">
              <a href="#projects" className="btn btn-primary">
                {t.hero.viewProjects}
                <i data-lucide="arrow-right"></i>
              </a>
              <a href="#contact" className="btn btn-secondary">
                {t.hero.contactMe}
                <i data-lucide="mail"></i>
              </a>
            </div>
          </div>

          <div className="hero-card" data-animate="fade-up" style={{animationDelay: '0.2s'}}>
            <div className="card-glow"></div>
            <div className="hero-photo-wrapper">
              <img src="assets/myphoto.PNG" alt="Shukrullo Foziljonov" className="hero-photo" />
              <div className="photo-ring"></div>
            </div>
            <div className="hero-meta">
              <div className="meta-item">
                <i data-lucide="briefcase"></i>
                <div>
                  <span className="meta-label">{t.hero.specialization}</span>
                  <span className="meta-value">{t.hero.specializationText}</span>
                </div>
              </div>
              <div className="meta-item">
                <i data-lucide="map-pin"></i>
                <div>
                  <span className="meta-label">{t.hero.location}</span>
                  <span className="meta-value">{t.hero.locationText}</span>
                </div>
              </div>
              <div className="meta-item">
                <i data-lucide="mail"></i>
                <div>
                  <span className="meta-label">{t.hero.email}</span>
                  <span className="meta-value">contact@byshukrullo.uz</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// About Component
const About = ({ t }) => {
  return (
    <section id="about" className="section">
      <div className="container">
        <div className="section-content">
          <div className="about-text" data-animate="fade-up">
            <h2 className="section-title">{t.about.title}</h2>
            <p className="intro-text">{t.about.intro}</p>
            <p className="description-text">{t.about.description}</p>
          </div>

          <div className="info-cards">
            <div className="info-card" data-animate="fade-up" style={{animationDelay: '0.1s'}}>
              <div className="card-icon">
                <i data-lucide="graduation-cap"></i>
              </div>
              <h3>{t.about.education}</h3>
              <ul>
                {t.about.educationItems.map((item, index) => (
                  <li key={index}>{item}</li>
                ))}
              </ul>
            </div>

            <div className="info-card" data-animate="fade-up" style={{animationDelay: '0.2s'}}>
              <div className="card-icon">
                <i data-lucide="sparkles"></i>
              </div>
              <h3>{t.about.interests}</h3>
              <ul>
                {t.about.interestsItems.map((item, index) => (
                  <li key={index}>{item}</li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// Achievements Component
const Achievements = ({ t }) => {
  return (
    <section id="achievements" className="section section-alt">
      <div className="container">
        <h2 className="section-title" data-animate="fade-up">{t.achievements.title}</h2>
        <div className="cards-grid">
          {t.achievements.items.map((achievement, index) => (
            <div
              key={index}
              className="achievement-card"
              data-animate="fade-up"
              style={{animationDelay: `${index * 0.1}s`}}
            >
              <div className="achievement-number">{String(index + 1).padStart(2, '0')}</div>
              <h3>{achievement.title}</h3>
              <p>{achievement.description}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// Projects Component
const Projects = ({ t }) => {
  return (
    <section id="projects" className="section">
      <div className="container">
        <h2 className="section-title" data-animate="fade-up">{t.projects.title}</h2>
        <div className="projects-grid">
          {t.projects.items.map((project, index) => (
            <div
              key={index}
              className="project-card"
              data-animate="fade-up"
              style={{animationDelay: `${index * 0.1}s`}}
            >
              <div className="project-image-wrapper">
                <img src={project.image} alt={project.title} />
                <div className="project-overlay">
                  <a href={project.github} target="_blank" rel="noopener noreferrer" className="project-link">
                    <i data-lucide="github"></i>
                  </a>
                </div>
              </div>
              <div className="project-content">
                <h3>{project.title}</h3>
                <p>{project.description}</p>
                <div className="project-tech">
                  <i data-lucide="code"></i>
                  <span>{project.tech}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// Publications Component
const Publications = ({ t }) => {
  return (
    <section id="publications" className="section section-alt">
      <div className="container">
        <h2 className="section-title" data-animate="fade-up">{t.publications.title}</h2>
        <div className="timeline">
          {t.publications.items.map((pub, index) => (
            <div
              key={index}
              className="timeline-item"
              data-animate="fade-up"
              style={{animationDelay: `${index * 0.1}s`}}
            >
              <div className="timeline-marker"></div>
              <div className="timeline-content">
                <h3>{pub.title}</h3>
                <p>{pub.description}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// Contact Component
const Contact = ({ t }) => {
  const socialLinks = [
    { icon: 'mail', label: t.contact.email, href: 'mailto:contact@byshukrullo.uz' },
    { icon: 'linkedin', label: t.contact.linkedin, href: 'https://linkedin.com/in/shukrullo-foziljonov/' },
    { icon: 'github', label: t.contact.github, href: 'https://github.com/byshukrullo' },
    { icon: 'send', label: t.contact.telegram, href: 'https://t.me/byshukrullo' },
  ];

  return (
    <section id="contact" className="section">
      <div className="container">
        <div className="contact-content">
          <div className="contact-text" data-animate="fade-up">
            <h2 className="section-title">{t.contact.title}</h2>
            <p className="description-text">{t.contact.description}</p>
          </div>

          <div className="contact-links" data-animate="fade-up" style={{animationDelay: '0.2s'}}>
            {socialLinks.map((link, index) => (
              <a
                key={index}
                href={link.href}
                target="_blank"
                rel="noopener noreferrer"
                className="contact-link"
              >
                <div className="contact-icon">
                  <i data-lucide={link.icon}></i>
                </div>
                <span>{link.label}</span>
                <i data-lucide="arrow-right" className="arrow"></i>
              </a>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

// Footer Component
const Footer = ({ t }) => {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-content">
          <p>© {new Date().getFullYear()} byShukrullo. {t.footer.rights}</p>
        </div>
      </div>
    </footer>
  );
};

// Main App Component
const App = () => {
  const [language, setLanguage] = useState('uz');
  const t = translations[language];

  useEffect(() => {
    // Initialize Lucide icons
    if (window.lucide) {
      window.lucide.createIcons();
    }

    // Animate elements on scroll
    const observerOptions = {
      threshold: 0.1,
      rootMargin: '0px 0px -50px 0px',
    };

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('animated');
        }
      });
    }, observerOptions);

    const animatedElements = document.querySelectorAll('[data-animate]');
    animatedElements.forEach((el) => observer.observe(el));

    return () => observer.disconnect();
  }, [language]);

  return (
    <div className="app">
      <Navbar language={language} setLanguage={setLanguage} t={t} />
      <Hero t={t} />
      <About t={t} />
      <Achievements t={t} />
      <Projects t={t} />
      <Publications t={t} />
      <Contact t={t} />
      <Footer t={t} />
    </div>
  );
};

// Render App
ReactDOM.render(<App />, document.getElementById('root'));
