'use client'

import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useTour } from '@/contexts/TourContext'
import { cn } from '@/lib/utils'

type Rect = { top: number; left: number; width: number; height: number }

export function TourOverlay() {
  const { t } = useTranslation()
  const { isOpen, activeTour, step, stepIndex, next, prev, close } = useTour()
  const [rect, setRect] = useState<Rect | null>(null)

  useEffect(() => {
    if (!isOpen || !step) {
      setRect(null)
      return
    }

    const measure = () => {
      if (!step.target) {
        setRect(null)
        return
      }
      const el = document.querySelector(step.target) as HTMLElement | null
      if (!el) {
        setRect(null)
        return
      }
      el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' })
      const r = el.getBoundingClientRect()
      setRect({
        top: r.top,
        left: r.left,
        width: r.width,
        height: r.height,
      })
    }

    const timer = window.setTimeout(measure, 280)
    window.addEventListener('resize', measure)
    window.addEventListener('scroll', measure, true)
    return () => {
      window.clearTimeout(timer)
      window.removeEventListener('resize', measure)
      window.removeEventListener('scroll', measure, true)
    }
  }, [isOpen, step, stepIndex])

  if (!isOpen || !activeTour || !step) return null

  const total = activeTour.steps.length
  const pad = 8
  const spot = rect
    ? {
        top: Math.max(8, rect.top - pad),
        left: Math.max(8, rect.left - pad),
        width: rect.width + pad * 2,
        height: rect.height + pad * 2,
      }
    : null

  const tooltipStyle = (() => {
    if (!spot) {
      return {
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
      } as const
    }
    const placement = step.placement ?? 'bottom'
    const tipWidth = 320
    const gap = 12
    if (placement === 'right') {
      return {
        top: spot.top,
        left: Math.min(window.innerWidth - tipWidth - 16, spot.left + spot.width + gap),
      }
    }
    if (placement === 'left') {
      return {
        top: spot.top,
        left: Math.max(16, spot.left - tipWidth - gap),
      }
    }
    if (placement === 'top') {
      return {
        top: Math.max(16, spot.top - 160),
        left: Math.min(window.innerWidth - tipWidth - 16, Math.max(16, spot.left)),
      }
    }
    return {
      top: Math.min(window.innerHeight - 200, spot.top + spot.height + gap),
      left: Math.min(window.innerWidth - tipWidth - 16, Math.max(16, spot.left)),
    }
  })()

  return (
    <div className="fixed inset-0 z-[100]" role="dialog" aria-modal="true">
      <div className="absolute inset-0 bg-black/55" onClick={close} />

      {spot && (
        <div
          className="pointer-events-none absolute rounded-2xl ring-2 ring-brand-400 ring-offset-2 ring-offset-transparent transition-all duration-200"
          style={{
            top: spot.top,
            left: spot.left,
            width: spot.width,
            height: spot.height,
            boxShadow: '0 0 0 9999px rgba(0,0,0,0.55)',
          }}
        />
      )}

      <div
        className={cn(
          'absolute z-[101] w-[min(92vw,320px)] rounded-2xl border border-[var(--premium-border)] bg-[var(--premium-card-bg,var(--bg))] p-4 shadow-xl',
        )}
        style={tooltipStyle}
      >
        <div className="mb-1 text-[10px] font-bold uppercase tracking-[0.16em] text-brand-600">
          {t(activeTour.titleKey)} · {stepIndex + 1}/{total}
        </div>
        <h3 className="text-base font-semibold text-[var(--premium-text)]">{t(step.titleKey)}</h3>
        <p className="mt-2 text-sm leading-relaxed text-[var(--premium-muted-text)]">
          {t(step.bodyKey)}
        </p>
        <div className="mt-4 flex items-center justify-between gap-2">
          <button
            type="button"
            onClick={close}
            className="text-xs font-semibold text-[var(--premium-muted-text)] hover:text-[var(--premium-text)]"
          >
            {t('tour.skip')}
          </button>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={prev}
              disabled={stepIndex === 0}
              className="rounded-lg border border-[var(--premium-border)] px-3 py-1.5 text-xs font-semibold disabled:opacity-40"
            >
              {t('tour.back')}
            </button>
            <button
              type="button"
              onClick={next}
              className="rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-700"
            >
              {stepIndex >= total - 1 ? t('tour.done') : t('tour.next')}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
