// @design-system: domain/UseMyLocationButton

'use client';

import { useState, useCallback } from 'react';
import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { Icon } from '@/components/ui/icons/Icon';

/** All possible geolocation request states. */
export type LocationState = 'idle' | 'requesting' | 'granted' | 'denied' | 'unsupported';

export interface UseMyLocationButtonProps {
  /**
   * Called when coords are successfully obtained.
   * NEVER stored or logged by this component — caller decides what to do.
   */
  onCoords: (lat: number, lng: number) => void;
  /** Called when user denies permission. Optional — caller shows toast. */
  onDenied?: () => void;
  /** Icon-only mode for compact mobile headers. */
  iconOnly?: boolean;
  /** Additional class names. */
  className?: string;
}

/**
 * UseMyLocationButton — triggers browser geolocation with idle/requesting/granted/denied/unsupported states.
 *
 * Coordinates go straight to `onCoords` — never stored, logged, or persisted here.
 * 10-second timeout, enableHighAccuracy: false (battery friendly).
 *
 * a11y: native `<button>` with aria-label + aria-pressed for granted state.
 * SSR-safe: navigator.geolocation access is inside the click handler only.
 *
 * @example
 * ```tsx
 * <UseMyLocationButton onCoords={(lat, lng) => store.setCoords(lat, lng)} iconOnly />
 * ```
 */
export function UseMyLocationButton({
  onCoords,
  onDenied,
  iconOnly = false,
  className,
}: UseMyLocationButtonProps) {
  const t = useT('near_you');
  // Start idle — never read navigator/window in render (SSR safety)
  const [state, setState] = useState<LocationState>(() => {
    if (typeof navigator === 'undefined' || !('geolocation' in navigator)) {
      return 'unsupported';
    }
    return 'idle';
  });

  const handleClick = useCallback(() => {
    if (typeof navigator === 'undefined' || !('geolocation' in navigator)) {
      setState('unsupported');
      return;
    }

    setState('requesting');

    navigator.geolocation.getCurrentPosition(
      (position) => {
        setState('granted');
        onCoords(position.coords.latitude, position.coords.longitude);
      },
      () => {
        setState('denied');
        onDenied?.();
      },
      { timeout: 10_000, enableHighAccuracy: false, maximumAge: 60_000 },
    );
  }, [onCoords, onDenied]);

  const isRequesting = state === 'requesting';
  const isGranted = state === 'granted';
  const isUnsupported = state === 'unsupported';
  const label = t('useMyLocation');

  return (
    <button
      type="button"
      aria-label={label}
      aria-pressed={isGranted}
      aria-busy={isRequesting}
      disabled={isUnsupported || isRequesting}
      onClick={handleClick}
      className={cn(
        'inline-flex items-center justify-center gap-2 rounded-md',
        'text-sm font-medium transition-colors',
        'focus-visible:ring-brand-primary-500 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none',
        'disabled:cursor-not-allowed disabled:opacity-50',
        isGranted
          ? 'bg-brand-primary-100 text-brand-primary-700'
          : 'text-text-secondary hover:bg-surface-hover hover:text-text-primary',
        iconOnly ? 'h-8 w-8' : 'h-8 min-w-36 px-3',
        isRequesting && 'animate-pulse motion-reduce:animate-none',
        className,
      )}
    >
      <Icon
        name="MapPin"
        size="sm"
        aria-hidden
        className={cn(isGranted && 'text-brand-primary-600', isRequesting && 'text-text-muted')}
      />
      {!iconOnly && <span>{label}</span>}
    </button>
  );
}
