import { useEffect, useMemo, useState, type CSSProperties } from 'react'
import {
  ArrowUpRight,
  Bot,
  BriefcaseBusiness,
  Code2,
  Mail,
  MapPin,
  Phone,
  Send,
  Sparkles,
} from 'lucide-react'
import './App.css'

const profile = {
  name: 'Tran Quang Hung',
  role: 'Mobile App Developer Intern',
  location: 'Ho Chi Minh City',
  phone: '(+84) 333 510 597',
  email: 'hunganroiy123@gmail.com',
  github: 'https://github.com/Anroiy123',
  summary:
    'Multimedia Technology student at PTIT focused on cross-platform mobile development, React Native, Flutter, Firebase, and UI/UX design with Figma.',
}

const projects = [
  {
    name: 'AITALKMATE',
    type: 'React Native App',
    time: 'Jul 2025 - Feb 2026',
    preview: '/aitalkmate-preview.png',
    previews: ['/aitalkmate-preview.png'],
    description:
      'Cross-platform mobile app for English speaking practice. Designed UI/UX in Figma, implemented front-end features with React Native, and integrated Firebase realtime database and authentication.',
    links: [
      { label: 'Mobile app', href: 'https://github.com/Anroiy123/AITALKMATE' },
      { label: 'Backend', href: 'https://github.com/Anroiy123/AITALKMATE-BACKEND' },
    ],
    stack: ['React Native', 'Firebase', 'Figma', 'Authentication'],
  },
  {
    name: 'TrackingCaloApp',
    type: 'Android Java App',
    time: 'Dec 2025',
    preview: '/tracking-calo-preview.png',
    previews: [
      '/tracking-calo-food-modal.png',
      '/tracking-calo-preview.png',
      '/tracking-calo-diary-preview.png',
    ],
    description:
      'Mobile app for tracking daily calories and nutrition. Applied MVVM architecture and Room Database for local offline storage.',
    links: [{ label: 'Repository', href: 'https://github.com/Anroiy123/TrackingCaloApp' }],
    stack: ['Android', 'Java', 'MVVM', 'Room Database'],
  },
]

const skillGroups = [
  {
    title: 'Languages',
    items: ['JavaScript ES6+', 'TypeScript', 'Dart', 'Kotlin'],
  },
  {
    title: 'Mobile',
    items: ['React Native', 'Flutter', 'Android Kotlin'],
  },
  {
    title: 'Design and data',
    items: ['Figma UI/UX', 'Firebase Realtime Database', 'State Management'],
  },
  {
    title: 'Workflow',
    items: ['Git and GitHub', 'Vercel', 'Jira', 'Postman', 'AI-assisted productivity'],
  },
]

const quickQuestions = [
  'What projects has Hung built?',
  'What mobile skills does Hung have?',
  'How can I contact Hung?',
]

const metrics = [
  { label: 'Mobile projects', value: '02' },
  { label: 'Core stack', value: 'RN + Flutter' },
  { label: 'Graduation', value: '2027' },
]

function answerQuestion(question: string) {
  const normalized = question.toLowerCase()

  if (normalized.includes('project') || normalized.includes('built') || normalized.includes('app')) {
    return 'Hung has built AITALKMATE, a React Native app for English speaking practice using Firebase, and TrackingCaloApp, an Android Java nutrition tracker using MVVM and Room Database.'
  }

  if (
    normalized.includes('skill') ||
    normalized.includes('react') ||
    normalized.includes('flutter') ||
    normalized.includes('mobile')
  ) {
    return 'His strongest fit is mobile development: React Native, Flutter, Android Kotlin, Firebase, Figma UI/UX, TypeScript, and app workflow tools like Git, Jira, Postman, and Vercel.'
  }

  if (normalized.includes('contact') || normalized.includes('email') || normalized.includes('phone')) {
    return `You can contact Hung by email at ${profile.email}, phone ${profile.phone}, or GitHub at ${profile.github}.`
  }

  if (normalized.includes('education') || normalized.includes('study') || normalized.includes('ptit')) {
    return 'Hung is studying Multimedia Technology Engineering at PTIT, expected graduation in 2027, with focus on mobile UI optimization and user experience.'
  }

  return 'I can answer about Hung\'s projects, mobile skills, education, contact information, and internship fit. Try asking: "What projects has Hung built?"'
}

function App() {
  const [question, setQuestion] = useState(quickQuestions[0])
  const [answer, setAnswer] = useState(answerQuestion(quickQuestions[0]))
  const [answerPulse, setAnswerPulse] = useState(0)

  const featuredSkills = useMemo(
    () => skillGroups.flatMap((group) => group.items).slice(0, 9),
    [],
  )

  useEffect(() => {
    document.documentElement.classList.add('has-reveal')
    const revealItems = document.querySelectorAll<HTMLElement>('.reveal')
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('is-visible')
            observer.unobserve(entry.target)
          }
        })
      },
      { threshold: 0.18 },
    )

    revealItems.forEach((item) => observer.observe(item))
    return () => {
      observer.disconnect()
      document.documentElement.classList.remove('has-reveal')
    }
  }, [])

  function handleAsk(nextQuestion = question) {
    const trimmed = nextQuestion.trim()
    if (!trimmed) return
    setQuestion(trimmed)
    setAnswer(answerQuestion(trimmed))
    setAnswerPulse((current) => current + 1)
  }

  return (
    <main>
      <div className="ambient-grid" aria-hidden="true" />
      <nav className="topbar" aria-label="Primary navigation">
        <a className="brand" href="#hero">TQH</a>
        <div className="nav-links">
          <a href="#projects">Projects</a>
          <a href="#skills">Skills</a>
          <a href="#ai">AI</a>
          <a href="#contact">Contact</a>
        </div>
      </nav>

      <section className="hero" id="hero">
        <div className="hero-copy reveal">
          <p className="eyebrow">Mobile portfolio / React Native intern</p>
          <h1>
            <span>Tran</span>
            <span>Quang</span>
            <span>Hung</span>
          </h1>
          <p className="role">{profile.role}</p>
          <p className="summary">{profile.summary}</p>

          <div className="hero-actions">
            <a className="primary-action" href="#projects">
              View projects <ArrowUpRight size={18} />
            </a>
            <a className="secondary-action" href={profile.github} target="_blank" rel="noreferrer">
              <Code2 size={18} /> GitHub
            </a>
          </div>

          <div className="signal-row" aria-label="Profile highlights">
            <span>React Native</span>
            <span>Flutter</span>
            <span>Firebase</span>
            <span>Figma UI/UX</span>
          </div>

          <div className="hero-metrics" aria-label="Profile metrics">
            {metrics.map((metric) => (
              <div key={metric.label}>
                <strong>{metric.value}</strong>
                <span>{metric.label}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="hero-visual reveal" aria-label="CV preview">
          <div className="device-halo" aria-hidden="true" />
          <div className="phone-frame">
            <div className="phone-speaker" />
            <div className="screen-scan" aria-hidden="true" />
            <img
              src="/cv-preview.png?v=2"
              alt="Tran Quang Hung CV preview"
              width="894"
              height="1264"
              loading="eager"
              decoding="sync"
              fetchPriority="high"
            />
          </div>
          <div className="floating-note">
            <Sparkles size={18} />
            <span>AI-assisted mobile workflow</span>
          </div>
        </div>
      </section>

      <section className="section intro-grid reveal" aria-label="Profile summary">
        <div>
          <p className="section-kicker">Internship fit</p>
          <h2>Building mobile interfaces with product-minded UI decisions.</h2>
        </div>
        <p>
          I combine mobile engineering fundamentals with design thinking: planning UI in Figma,
          implementing screens in React Native or Flutter, connecting Firebase-backed features,
          and refining the experience for real users.
        </p>
      </section>

      <section className="section projects-section" id="projects">
        <div className="section-heading reveal">
          <p className="section-kicker">Selected work</p>
          <h2>Projects from my CV</h2>
        </div>

        <div className="project-grid">
          {projects.map((project, index) => (
            <article className="project-card reveal" key={project.name} style={{ '--delay': `${index * 110}ms` } as CSSProperties}>
              <div className="project-index">0{index + 1}</div>
              <div
                className={`project-preview project-preview-${index + 1} project-preview-count-${project.previews?.length ?? 1}`}
                aria-label={`${project.name} app preview`}
              >
                {(project.previews ?? [project.preview]).map((preview, previewIndex) => (
                  <img
                    src={preview}
                    alt={`${project.name} mobile app preview ${previewIndex + 1}`}
                    loading="lazy"
                    key={preview}
                  />
                ))}
              </div>
              <div className="project-meta">
                <span>{project.type}</span>
                <span>{project.time}</span>
              </div>
              <h3>{project.name}</h3>
              <p>{project.description}</p>
              <div className="stack-list">
                {project.stack.map((item) => (
                  <span key={item}>{item}</span>
                ))}
              </div>
              <div className="project-links">
                {project.links.map((link) => (
                  <a href={link.href} key={link.href} target="_blank" rel="noreferrer">
                    {link.label} <ArrowUpRight size={16} />
                  </a>
                ))}
              </div>
            </article>
          ))}
        </div>
      </section>

      <section className="section skills-section" id="skills">
        <div className="section-heading reveal">
          <p className="section-kicker">Capability map</p>
          <h2>Technical skills</h2>
        </div>

        <div className="skill-cloud">
          {featuredSkills.map((skill) => (
            <span key={skill}>{skill}</span>
          ))}
        </div>

        <div className="skill-groups">
          {skillGroups.map((group, index) => (
            <div className="skill-group reveal" key={group.title} style={{ '--delay': `${index * 80}ms` } as CSSProperties}>
              <h3>{group.title}</h3>
              <ul>
                {group.items.map((item) => (
                  <li key={item}>{item}</li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </section>

      <section className="section ai-panel" id="ai">
        <div className="ai-copy reveal">
          <p className="section-kicker">AI applied</p>
          <h2>Profile assistant</h2>
          <p>
            A small local assistant reads structured CV data and answers common recruiter
            questions about my projects, skills, education, and contact information.
          </p>
        </div>

        <div className="assistant-box reveal">
          <div className="assistant-header">
            <Bot size={22} />
            <span>Ask about Hung</span>
            <i aria-hidden="true" />
          </div>

          <div className="quick-questions">
            {quickQuestions.map((item) => (
              <button type="button" key={item} onClick={() => handleAsk(item)}>
                {item}
              </button>
            ))}
          </div>

          <label className="input-label" htmlFor="assistant-question">Question</label>
          <div className="ask-row">
            <input
              id="assistant-question"
              value={question}
              onChange={(event) => setQuestion(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === 'Enter') handleAsk()
              }}
            />
            <button type="button" aria-label="Ask assistant" onClick={() => handleAsk()}>
              <Send size={18} />
            </button>
          </div>

          <div className="answer-box" key={answerPulse}>
            <span>Answer</span>
            <p>{answer}</p>
          </div>
        </div>
      </section>

      <section className="section contact-section reveal" id="contact">
        <div>
          <p className="section-kicker">Contact</p>
          <h2>Ready for mobile app internship work.</h2>
        </div>
        <div className="contact-list">
          <a href={`mailto:${profile.email}`}>
            <Mail size={18} /> {profile.email}
          </a>
          <a href={`tel:${profile.phone.replace(/[^+\d]/g, '')}`}>
            <Phone size={18} /> {profile.phone}
          </a>
          <a href={profile.github} target="_blank" rel="noreferrer">
            <Code2 size={18} /> github.com/Anroiy123
          </a>
          <span>
            <MapPin size={18} /> {profile.location}
          </span>
        </div>
      </section>

      <footer>
        <span><BriefcaseBusiness size={16} /> Portfolio for Meu Solutions internship onboarding</span>
        <span>Built with React + Vite</span>
      </footer>
    </main>
  )
}

export default App
