'use client'

import { useState } from 'react'
import { HelpCircle, X } from 'lucide-react'
import { useLanguage } from '@/lib/i18n'
import type { DashboardWidgetId } from '@/lib/dashboard/layout'

interface DashboardWidgetHelpProps {
  widgetId: DashboardWidgetId
  className?: string
}

export function DashboardWidgetHelp({ widgetId, className = '' }: DashboardWidgetHelpProps) {
  const { t } = useLanguage()
  const [open, setOpen] = useState(false)
  const helpKey = `homeDashboard.widgetHelp.${widgetId}`
  const text = t(helpKey)

  if (text === helpKey) return null

  return (
    <div className={`relative ${className}`}>
      <button
        type="button"
        onClick={() => setOpen(v => !v)}
        className={`p-1 rounded-full border transition-colors ${
          open
            ? 'border-brand-accent/40 bg-brand-accent/10 text-brand-accent'
            : 'border-border/30 bg-white/90 dark:bg-zinc-900/90 text-concrete hover:text-brand-accent hover:border-brand-accent/30'
        }`}
        aria-label={t('homeDashboard.widgetHelpLabel')}
        aria-expanded={open}
      >
        <HelpCircle size={12} strokeWidth={2} />
      </button>

      {open && (
        <div className="absolute top-full end-0 mt-1.5 z-30 w-[min(280px,calc(100vw-3rem))] p-3 rounded-xl border border-brand-accent/20 bg-white dark:bg-zinc-900 shadow-lg">
          <div className="flex items-start justify-between gap-2 mb-1">
            <p className="text-[8px] font-mono font-bold uppercase tracking-wider text-brand-accent">
              {t(`homeDashboard.widgets.${widgetId}`)}
            </p>
            <button
              type="button"
              onClick={() => setOpen(false)}
              className="text-concrete hover:text-ink shrink-0"
              aria-label={t('homeDashboard.widgetHelpClose')}
            >
              <X size={10} />
            </button>
          </div>
          <p className="text-[10px] text-concrete leading-relaxed">{text}</p>
        </div>
      )}
    </div>
  )
}
