/**
 * Wizard Help Button
 * 
 * A "?" button that shows a tooltip/popover with a short
 * explanation of the current page the user is on.
 * 
 * The popover uses position: fixed and calculates its placement
 * based on the button's viewport position to avoid being clipped
 * by overflow: hidden on parent containers.
 * 
 * @package BoostBot
 */

import { useState, useRef, useEffect, useCallback } from 'react'
import { HelpCircle, X } from 'lucide-react'
import { useLocation } from 'react-router-dom'
import { createPortal } from 'react-dom'
import { getPageDescription } from './wizardSteps'
import { t, getDirection } from '@/lib/i18n'

interface WizardHelpButtonProps {
  className?: string
  standalone?: boolean
}

export function WizardHelpButton({ className = '', standalone = false }: WizardHelpButtonProps) {
  const [isOpen, setIsOpen] = useState(false)
  const popoverRef = useRef<HTMLDivElement>(null)
  const buttonRef = useRef<HTMLButtonElement>(null)
  const [popoverStyle, setPopoverStyle] = useState<React.CSSProperties>({})
  const location = useLocation()

  const searchParams = new URLSearchParams(location.search)
  const pageDesc = getPageDescription(location.pathname, searchParams)

  // Calculate popover position based on button's viewport location
  const updatePosition = useCallback(() => {
    if (!buttonRef.current) return

    const rect = buttonRef.current.getBoundingClientRect()
    const popoverWidth = 280
    const popoverMaxHeight = 200
    const margin = 8

    // Determine vertical placement: prefer above the button
    const spaceAbove = rect.top
    const placeAbove = spaceAbove > popoverMaxHeight + margin

    // Determine horizontal placement: prefer to the right (RTL: logical start)
    // Check if popover would go off the left edge of the viewport
    let left = rect.left
    if (left + popoverWidth > window.innerWidth - margin) {
      left = window.innerWidth - popoverWidth - margin
    }
    if (left < margin) {
      left = margin
    }

    setPopoverStyle({
      position: 'fixed',
      zIndex: 9999,
      width: `${popoverWidth}px`,
      left: `${left}px`,
      ...(placeAbove
        ? { bottom: `${window.innerHeight - rect.top + margin}px` }
        : { top: `${rect.bottom + margin}px` }
      ),
    })
  }, [])

  // Close on click outside
  useEffect(() => {
    if (!isOpen) return
    const handleClickOutside = (e: MouseEvent) => {
      if (
        popoverRef.current && !popoverRef.current.contains(e.target as Node) &&
        buttonRef.current && !buttonRef.current.contains(e.target as Node)
      ) {
        setIsOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [isOpen])

  // Recalculate position when opened or on scroll/resize
  useEffect(() => {
    if (!isOpen) return
    updatePosition()
    window.addEventListener('scroll', updatePosition, true)
    window.addEventListener('resize', updatePosition)
    return () => {
      window.removeEventListener('scroll', updatePosition, true)
      window.removeEventListener('resize', updatePosition)
    }
  }, [isOpen, updatePosition])

  // Close when navigating
  useEffect(() => {
    setIsOpen(false)
  }, [location.pathname, location.search])

  if (!pageDesc) return null

  const handleToggle = () => {
    if (!isOpen) {
      updatePosition()
    }
    setIsOpen(!isOpen)
  }

  return (
    <>
      <button
        ref={buttonRef}
        onClick={handleToggle}
        style={{
          width: standalone ? 'auto' : '32px',
          height: standalone ? 'auto' : '32px',
          padding: standalone ? '8px' : 0,
          borderRadius: '8px',
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          border: 'none',
          background: 'transparent',
          cursor: 'pointer',
        }}
        className={`hover:bg-gray-100 ${className}`}
        title={t('Help on current page')}
        type="button"
      >
        <HelpCircle style={{ width: standalone ? '20px' : '16px', height: standalone ? '20px' : '16px', color: '#9CA3AF' }} />
      </button>

      {isOpen && createPortal(
        <div
          ref={popoverRef}
          style={{
            ...popoverStyle,
            backgroundColor: '#fff',
            borderRadius: '12px',
            boxShadow: '0 20px 40px -8px rgba(0,0,0,0.15), 0 0 0 1px rgba(0,0,0,0.05)',
            padding: '16px',
          }}
          dir={getDirection()}
        >
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '8px', marginBottom: '8px' }}>
            <h4 style={{ fontSize: '14px', fontWeight: 600, color: '#111827', margin: 0 }}>{pageDesc.name}</h4>
            <button
              onClick={() => setIsOpen(false)}
              style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, color: '#9CA3AF' }}
              type="button"
            >
              <X style={{ width: '16px', height: '16px' }} />
            </button>
          </div>
          <p style={{ fontSize: '14px', color: '#4B5563', lineHeight: 1.6, margin: 0 }}>{pageDesc.description}</p>
        </div>,
        document.body
      )}
    </>
  )
}
