import { useRouterState } from '@tanstack/react-router'
import { useTestStore } from '@/store/test-store'
import { UserMenu } from '@/components/UserMenu'

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' },
}

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

  // 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>
    )
  }

  const { eyebrow, title, accent } = matchRouteLabel(pathname)
  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>
  )
}
