'use client';

import { useMapStore } from '@/stores/mapStore';
import { useGameStore } from '@/stores/gameStore';

interface MapContextMenuProps {
  onMove: (lat: number, lon: number) => void;
  onMoveGangster?: (gangId: string, gangsterPlayerId: string, lat: number, lon: number) => void;
  onMoveMultiGangsters?: (gangsterKeys: string[], lat: number, lon: number) => void;
  onAction: (actionCode: string, targetType: string, targetId: string) => void;
  onEnterVehicle: (vehicleId: string) => void;
  onExitVehicle: () => void;
  onOpenPOI: (poiId: string) => void;
}

const ACTION_ICONS: Record<string, string> = {
  move: '\u{1F6B6}',
  visit: '\u{1F441}',
  rob_person: '\u{1F4B0}',
  assassinate: '\u{1F3AF}',
  rob_business: '\u{1F4B5}',
  sabotage: '\u{1F525}',
  burgle_residence: '\u{1F510}',
  donate: '\u{2764}',
  trade: '\u{1F91D}',
  recruit: '\u{1F464}',
  enter_vehicle: '\u{1F697}',
  rentrer: '\u{1F3E0}',
};

export function MapContextMenu({ onMove, onMoveGangster, onMoveMultiGangsters, onAction, onEnterVehicle, onExitVehicle, onOpenPOI }: MapContextMenuProps) {
  const contextMenu = useMapStore((s) => s.contextMenu);
  const closeContextMenu = useMapStore((s) => s.closeContextMenu);
  const player = useGameStore((s) => s.player);
  const inVehicle = !!player?.active_vehicle_id;
  const selectedGangsterIds = useMapStore((s) => s.selectedGangsterIds);
  const selectionMode = useMapStore((s) => s.selectionMode);
  const clearGangsterSelection = useMapStore((s) => s.clearGangsterSelection);

  if (!contextMenu.open || !contextMenu.target) return null;

  const { x, y, target, actions } = contextMenu;

  // Build menu items based on target type
  const items: Array<{ label: string; icon: string; onClick: () => void; color?: string }> = [];

  if (target.type === 'map') {
    // Right-click on empty map = move
    items.push({
      label: 'Se deplacer ici',
      icon: ACTION_ICONS.move || '',
      onClick: () => { onMove(target.lat, target.lon); closeContextMenu(); },
    });
    // Multi-gangster: envoyer les selectionnes ici
    if (selectionMode && selectedGangsterIds.length > 0) {
      items.push({
        label: `Envoyer ${selectedGangsterIds.length} gangster(s) ici`,
        icon: ACTION_ICONS.move || '',
        color: '#22c55e',
        onClick: () => {
          onMoveMultiGangsters?.(selectedGangsterIds, target.lat, target.lon);
          clearGangsterSelection();
          closeContextMenu();
        },
      });
    }
    // If in vehicle, add exit option
    if (inVehicle) {
      items.push({
        label: 'Descendre du vehicule',
        icon: ACTION_ICONS.enter_vehicle || '',
        onClick: () => { onExitVehicle(); closeContextMenu(); },
      });
    }
  } else if (target.type === 'territory') {
    // Own territory context menu
    items.push({
      label: 'Rentrer defendre',
      icon: ACTION_ICONS.rentrer || '',
      onClick: () => {
        onMove(target.lat, target.lon);
        closeContextMenu();
      },
    });
    // Multi-gangster: rappeler les troupes selectionnees
    if (selectionMode && selectedGangsterIds.length > 0) {
      items.push({
        label: `Rappeler ${selectedGangsterIds.length} gangster(s)`,
        icon: ACTION_ICONS.move || '',
        color: '#22c55e',
        onClick: () => {
          onMoveMultiGangsters?.(selectedGangsterIds, target.lat, target.lon);
          clearGangsterSelection();
          closeContextMenu();
        },
      });
    }
    // Legacy: single gangster recall
    const gs = useMapStore.getState().selectedGangster;
    if (gs && !selectionMode) {
      items.push({
        label: 'Rappeler ce gangster',
        icon: ACTION_ICONS.move || '',
        onClick: () => {
          if (onMoveGangster && gs.gangId) {
            onMoveGangster(gs.gangId, gs.playerId, target.lat, target.lon);
          }
          closeContextMenu();
        },
      });
    }
  } else if (target.type === 'poi') {
    items.push({
      label: 'Voir les details',
      icon: ACTION_ICONS.visit || '',
      onClick: () => { onOpenPOI(target.id); closeContextMenu(); },
    });
  } else if (target.type === 'vehicle') {
    // Phase 15 v2 (2026-04-22) — options selon ownership :
    //   À moi → Monter dedans OU Garer au garage (si pas déjà en location)
    //   À un rival → Voler (carjack) OU Récupérer si on m'a volé la mienne
    const ownedByMe = !!(target as any).is_owned_by_me;
    if (ownedByMe) {
      items.push({
        label: 'Monter dans le vehicule',
        icon: ACTION_ICONS.enter_vehicle || '',
        onClick: () => { onEnterVehicle(target.id); closeContextMenu(); },
      });
      items.push({
        label: 'Garer au garage (louer)',
        icon: '\u{1F3E2}',
        onClick: () => {
          window.dispatchEvent(new CustomEvent('open-garage-rental', {
            detail: { vehicle_id: target.id, lat: target.lat, lon: target.lon },
          }));
          closeContextMenu();
        },
      });
    } else {
      items.push({
        label: 'Voler ce véhicule',
        icon: '\u{1F575}',
        color: '#ef4444',
        onClick: () => {
          if (!confirm('Voler ce véhicule ? Combat si un conducteur est présent.')) {
            closeContextMenu();
            return;
          }
          window.dispatchEvent(new CustomEvent('carjack-start', {
            detail: { vehicle_id: target.id },
          }));
          closeContextMenu();
        },
      });
    }
    // Récupérer — disponible si conditions remplies (backend validera)
    items.push({
      label: 'Récupérer',
      icon: '\u{1F69B}',
      color: '#22c55e',
      onClick: () => {
        window.dispatchEvent(new CustomEvent('recovery-start', {
          detail: { vehicle_id: target.id },
        }));
        closeContextMenu();
      },
    });
  } else if (target.type === 'gangster' && target.allied) {
    // Allied gangster context menu — tactical controls
    if (!target.hospitalized) {
      items.push({
        label: 'Deplacer ce gangster',
        icon: ACTION_ICONS.move || '',
        onClick: () => {
          // Store the gangster info for the next map click
          if (target.gang_id) {
            useMapStore.getState().setSelectedGangster({
              gangId: target.gang_id,
              playerId: target.id,
              name: target.name || 'Gangster',
            });
          }
          closeContextMenu();
        },
      });
    }
    if (target.hospitalized) {
      items.push({
        label: 'Hospitalise — indisponible',
        icon: '',
        onClick: closeContextMenu,
        color: '#6b7280',
      });
    }
  } else if (target.type === 'gangster' && !target.allied) {
    // Enemy gangster
    items.push({
      label: 'Gangster ennemi',
      icon: '',
      onClick: closeContextMenu,
      color: '#ef4444',
    });
  }

  // Add backend-provided actions
  for (const action of actions) {
    items.push({
      label: action.label,
      icon: ACTION_ICONS[action.code] || '',
      color: action.police_risk > 30 ? '#ef4444' : action.police_risk > 0 ? '#f59e0b' : undefined,
      onClick: () => {
        onAction(action.code, target.type, target.id);
        closeContextMenu();
      },
    });
  }

  if (items.length === 0) {
    items.push({ label: 'Aucune action', icon: '', onClick: closeContextMenu });
  }

  // Position menu, keep within viewport
  const menuStyle: React.CSSProperties = {
    position: 'fixed',
    left: Math.min(x, window.innerWidth - 200),
    top: Math.min(y, window.innerHeight - items.length * 36 - 20),
    zIndex: 3000,
    minWidth: 180,
  };

  return (
    <>
      {/* Backdrop to close */}
      <div
        className="fixed inset-0"
        style={{ zIndex: 2999 }}
        onClick={closeContextMenu}
        onContextMenu={(e) => { e.preventDefault(); closeContextMenu(); }}
      />

      {/* Menu */}
      <div
        style={menuStyle}
        className="rounded-xl overflow-hidden shadow-2xl"
      >
        {/* Header with target name */}
        <div className="px-3 py-2 text-[10px] font-bold truncate" style={{
          background: 'var(--bg-secondary)',
          color: 'var(--text-muted)',
          borderBottom: '1px solid var(--border-dark)',
        }}>
          {target.name || target.type}
        </div>

        {/* Actions */}
        <div style={{ background: 'var(--bg-panel)' }}>
          {items.map((item, i) => (
            <button
              key={i}
              onClick={item.onClick}
              className="w-full flex items-center gap-2 px-3 py-2 text-xs text-left transition-colors hover:bg-white/5"
              style={{
                color: item.color || 'var(--text-primary)',
                borderBottom: i < items.length - 1 ? '1px solid var(--border-dark)' : 'none',
              }}
            >
              <span className="text-sm w-5 text-center">{item.icon}</span>
              <span>{item.label}</span>
            </button>
          ))}
        </div>
      </div>
    </>
  );
}
