import { useRouterState } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useTestStore } from '@/store/test-store'
import { UserMenu } from '@/components/UserMenu'
import { fetchTestWithParts } from '@/features/toeic/api/test-list-api'

const ROUTE_TITLES: Record<string, { eyebrow: string; title: string; accent?: string }> = {
  '/':             { eyebrow: 'Học TOEIC cùng AI',   title: 'Trang chủ' },
  '/archivement':  { eyebrow: 'Thành tích của bạn',  title: 'Tôi học', accent: 'học' },
  '/toeic':        { eyebrow: 'Luyện đề',            title: 'TOEIC Mock Tests', accent: 'Mock' },
  '/writing':      { eyebrow: 'AI Coach',            title: 'Chấm Writing', accent: 'Writing' },
  '/flash-card':   { eyebrow: 'Từ vựng TOEIC',       title: 'Flash Card', accent: 'Card' },
  '/settings':     { eyebrow: 'Tuỳ chỉnh',           title: 'Cài đặt' },
}

// Match `/toeic/<numeric-id>` but not `/toeic/session`, `/toeic/result`, `/toeic/part/...`
const TEST_DETAIL_RE = /^\/toeic\/(\d+)$/

function matchRouteLabel(pathname: string) {
  if (ROUTE_TITLES[pathname]) return ROUTE_TITLES[pathname]
  const keys = Object.keys(ROUTE_TITLES).sort((a, b) => b.length - a.length)
  for (const k of keys) {
    if (k !== '/' && pathname.startsWith(k)) return ROUTE_TITLES[k]
  }
  return { eyebrow: 'EnglishAI', title: 'EnglishAI' }
}

export function AppHeader() {
  const { location } = useRouterState()
  const { testName, parts, answers } = useTestStore()
  const pathname = location.pathname

  // Show test title in header when viewing a specific test's part-selection page.
  const testDetailMatch = pathname.match(TEST_DETAIL_RE)
  const testId = testDetailMatch ? Number(testDetailMatch[1]) : null
  const { data: testDetail } = useQuery({
    queryKey: ['test-detail', testId],
    queryFn: () => fetchTestWithParts(testId!),
    enabled: testId !== null,
  })

  // In-session mode: show test progress instead of route title
  if (pathname === '/toeic/session') {
    const totalQuestions = parts.reduce((sum, p) => sum + p.questions.length, 0)
    const answered = Object.values(answers).filter((a) => a !== null).length
    return (
      <header
        className="fixed top-0 right-0 left-0 lg:left-60 h-16 z-40 flex items-center justify-between px-6 backdrop-blur-md"
        style={{
          background: 'color-mix(in oklab, var(--at-paper) 88%, transparent)',
          borderBottom: '1px solid var(--at-line)',
        }}
      >
        <div>
          <div className="at-eyebrow" style={{ fontSize: 10, marginBottom: 2 }}>Phiên thi</div>
          <div className="at-serif text-[15px]" style={{ color: 'var(--at-ink)', fontWeight: 500, letterSpacing: '-0.01em' }}>
            {testName} · <i className="italic" style={{ color: 'var(--at-brand)' }}>{answered}/{totalQuestions}</i> câu
          </div>
        </div>
        <UserMenu />
      </header>
    )
  }

  // Test-detail page: show test title in header
  const routeLabel = testDetail
    ? { eyebrow: 'Luyện đề TOEIC', title: testDetail.test.title }
    : matchRouteLabel(pathname)
  const { eyebrow, title } = routeLabel
  const accent = 'accent' in routeLabel ? routeLabel.accent : undefined
  const renderTitle = () => {
    if (!accent || !title.includes(accent)) return title
    const [before, after] = title.split(accent)
    return (
      <>
        {before}
        <i className="italic" style={{ color: 'var(--at-brand)' }}>{accent}</i>
        {after}
      </>
    )
  }

  return (
    <header
      className="fixed top-0 right-0 left-0 lg:left-60 h-16 z-40 flex items-center justify-between px-6 backdrop-blur-md"
      style={{
        background: 'color-mix(in oklab, var(--at-paper) 88%, transparent)',
        borderBottom: '1px solid var(--at-line)',
      }}
    >
      <div>
        <div className="at-eyebrow" style={{ fontSize: 10, marginBottom: 2 }}>{eyebrow}</div>
        <div className="at-serif text-[15px]" style={{ color: 'var(--at-ink)', fontWeight: 500, letterSpacing: '-0.01em' }}>
          {renderTitle()}
        </div>
      </div>
      <UserMenu />
    </header>
  )
}
