/* eslint-disable @next/next/no-img-element -- External card image URLs; next/image migration is out of scope. */
import { useState } from 'react';
import { useRouter } from 'next/router';
import { VOCAB } from '../lib/collection-vocabulary.js';

// Expanding Add Button Component
function ExpandingAddButton({ card, onAddToCollection, onAddToDeck, onMarkAsOwned }) {
  const [isExpanded, setIsExpanded] = useState(false);

  const handleMainClick = (e) => {
    e.stopPropagation();
    if (!isExpanded) {
      setIsExpanded(true);
    } else {
      // Default action when expanded - add to collection
      onAddToCollection([card]);
      setIsExpanded(false);
    }
  };

  const handleOptionClick = (e, action) => {
    e.stopPropagation();
    action();
    setIsExpanded(false);
  };

  return (
    <div className="relative">
      {/* Expanded Options */}
      {isExpanded && (
        <div className="absolute bottom-full left-0 mb-1 flex flex-col space-y-1">
          <button
            onClick={(e) => handleOptionClick(e, () => onAddToCollection([card]))}
            className="p-1.5 rounded-md shadow-lg transition-all duration-150 hover:scale-105 flex items-center space-x-1 text-xs whitespace-nowrap"
            style={{ backgroundColor: 'var(--accent-flame)', color: 'white' }}
            title={VOCAB.ADD_TO_LIST}
          >
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
            </svg>
            <span>Collection</span>
          </button>
          
          <button
            onClick={(e) => handleOptionClick(e, () => onAddToDeck([card]))}
            className="p-1.5 rounded-md shadow-lg transition-all duration-150 hover:scale-105 flex items-center space-x-1 text-xs whitespace-nowrap"
            style={{ backgroundColor: 'var(--accent-gold)', color: 'white' }}
            title="Add to Deck"
          >
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
            </svg>
            <span>Deck</span>
          </button>
          
          <button
            onClick={(e) => handleOptionClick(e, onMarkAsOwned)}
            className="p-1.5 rounded-md shadow-lg transition-all duration-150 hover:scale-105 flex items-center space-x-1 text-xs whitespace-nowrap"
            style={{ backgroundColor: 'var(--accent-ember)', color: 'white' }}
            title={VOCAB.ADD_TO_MY_COLLECTION}
          >
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
            <span>Own</span>
          </button>
        </div>
      )}

      {/* Main Add Button */}
      <button
        onClick={handleMainClick}
        className="p-1.5 rounded-md shadow-lg transition-all duration-150 hover:scale-105 relative"
        style={{ 
          backgroundColor: 'var(--accent-ember)',
          color: 'white',
          boxShadow: '0 0 0 2px var(--accent-ember), 0 4px 6px -1px rgba(216, 67, 21, 0.3)'
        }}
        title={isExpanded ? VOCAB.ADD_TO_LIST : 'Show Options'}
      >
        <svg 
          className={`w-4 h-4 transition-transform duration-150 ${isExpanded ? 'rotate-45' : ''}`} 
          fill="none" 
          stroke="currentColor" 
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
        </svg>
      </button>

      {/* Click outside to close */}
      {isExpanded && (
        <div 
          className="fixed inset-0 z-[-1]" 
          onClick={(e) => {
            e.stopPropagation();
            setIsExpanded(false);
          }}
        />
      )}
    </div>
  );
}

export default function CardItem({ 
  card, 
  viewMode = 'grid', 
  isSelected = false, 
  onToggleSelect,
  onAddToCollection,
  onAddToDeck,
  onToggleFavorite,
  isFavorited = false
}) {
  const [imageError, setImageError] = useState(false);
  const router = useRouter();

  const handleSelectChange = (e) => {
    e.stopPropagation();
    onToggleSelect(card);
  };

  const handleImageError = () => {
    setImageError(true);
  };

  const handleCardClick = (e) => {
    // Don't navigate if clicking on interactive elements
    if (e.target.closest('input, button, a')) {
      return;
    }
    router.push(`/card/${card.id}`);
  };

  // Get rarity-based styling
  const getRarityEffects = (rarity) => {
    const rarityLower = rarity?.toLowerCase() || '';
    
    if (rarityLower.includes('mythic') || rarityLower.includes('legendary')) {
      return {
        glow: 'rarity-glow-mythic',
        particles: 'rarity-particles-mythic',
        border: 'border-yellow-400',
        shadow: 'shadow-yellow-400/50'
      };
    } else if (rarityLower.includes('rare') || rarityLower.includes('holo')) {
      return {
        glow: 'rarity-glow-rare',
        particles: 'rarity-particles-rare',
        border: 'border-purple-400',
        shadow: 'shadow-purple-400/50'
      };
    } else if (rarityLower.includes('uncommon')) {
      return {
        glow: 'rarity-glow-uncommon',
        particles: 'rarity-particles-uncommon',
        border: 'border-blue-400',
        shadow: 'shadow-blue-400/30'
      };
    } else if (rarityLower.includes('enchanted') || rarityLower.includes('secret')) {
      return {
        glow: 'rarity-glow-enchanted',
        particles: 'rarity-particles-enchanted',
        border: 'border-pink-400',
        shadow: 'shadow-pink-400/60'
      };
    }
    
    return {
      glow: '',
      particles: '',
      border: 'border-gray-200',
      shadow: ''
    };
  };

  const rarityEffects = getRarityEffects(card.rarity);

  // Panel positioning no longer needed - using simple hover buttons

  if (viewMode === 'list') {
    return (
      <div
        className="flex items-center p-4 rounded-xl transition-all duration-200 cursor-pointer nav-item-hover"
        style={{
          backgroundColor: isSelected
            ? 'rgba(255, 110, 0, 0.08)'
            : 'transparent',
          border: '1px solid',
          borderColor: isSelected ? 'var(--accent-ember)' : 'var(--border)',
          boxShadow: isSelected ? 'var(--rim-light-inner)' : 'none',
        }}
        onClick={handleCardClick}
      >
        {/* Selection Checkbox */}
        <div className="flex-shrink-0 mr-4">
          <input
            type="checkbox"
            checked={isSelected}
            onChange={handleSelectChange}
            className="w-4 h-4 rounded focus:ring-2"
            style={{
              accentColor: 'var(--accent-ember)',
              '--tw-ring-color': 'var(--accent-ember)',
            }}
          />
        </div>

        {/* Card Image */}
        <div className="flex-shrink-0 mr-4">
          <div
            className="w-16 h-22 rounded-lg overflow-hidden"
            style={{ backgroundColor: 'var(--bg-tertiary)' }}
          >
            {!imageError ? (
              <img
                src={card.image_url}
                alt={card.name}
                className="w-full h-full object-cover"
                onError={handleImageError}
              />
            ) : (
              <div
                className="w-full h-full flex items-center justify-center text-xs"
                style={{ color: 'var(--text-secondary)' }}
              >
                No Image
              </div>
            )}
          </div>
        </div>

        {/* Card Info */}
        <div className="flex-1 min-w-0">
          <h3
            className="font-semibold truncate"
            style={{ color: 'var(--text-primary)' }}
          >
            {card.name}
          </h3>
          <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
            {card.set_name} • {card.rarity}
          </p>
          <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
            {card.card_type}
          </p>
        </div>

        {/* Game Badge */}
        <div className="flex-shrink-0 mx-4">
          <span
            className="px-2 py-1 text-xs font-medium rounded-full"
            style={{
              backgroundColor: 'var(--bg-tertiary)',
              color: 'var(--text-primary)',
              border: '1px solid var(--border)',
            }}
          >
            {card.game}
          </span>
        </div>

        {/* Price */}
        <div className="flex-shrink-0 mx-4">
          <span
            className="text-lg font-bold"
            style={{ color: 'var(--accent-flame)' }}
          >
            ${card.market_price}
          </span>
        </div>

        {/* Actions */}
        <div className="flex-shrink-0 flex items-center space-x-2">
          <button
            onClick={(e) => {
              e.stopPropagation();
              onToggleFavorite(card);
            }}
            className="nav-item-hover p-2 rounded-xl transition-colors"
            style={{
              color: isFavorited
                ? 'var(--accent-ember)'
                : 'var(--text-secondary)',
            }}
          >
            <svg className="w-5 h-5" fill={isFavorited ? "currentColor" : "none"} stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
            </svg>
          </button>

          <button
            onClick={(e) => {
              e.stopPropagation();
              onAddToCollection(card);
            }}
            className="nav-item-hover p-2 rounded-xl transition-colors"
            style={{ color: 'var(--accent-ember)' }}
            title={VOCAB.ADD_TO_LIST}
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
            </svg>
          </button>

          <button
            onClick={(e) => {
              e.stopPropagation();
              onAddToDeck(card);
            }}
            className="nav-item-hover p-2 rounded-xl transition-colors"
            style={{ color: 'var(--accent-flame)' }}
            title="Add to Deck"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
            </svg>
          </button>
        </div>
      </div>
    );
  }

  // Grid view
  return (
    <div className="card-item-container card-grid-outer-glow relative group bg-transparent rounded-xl transition-all duration-150 overflow-visible transform hover:scale-102 hover:z-10">
      {/* Main Card Container */}
      <div 
        className={`relative rounded-xl border-2 transition-all duration-200 overflow-hidden cursor-pointer ${
          isSelected 
            ? 'shadow-xl ring-2 ring-opacity-50' 
            : 'group-hover:shadow-xl'
        } ${rarityEffects.glow}`}
        style={{
          backgroundColor: 'var(--bg-primary)',
          borderColor: isSelected ? 'var(--accent-ember)' : 'var(--border)',
          '--tw-ring-color': isSelected ? 'var(--accent-ember)' : 'transparent'
        }}
        onClick={handleCardClick}
      >
        
        {/* Rarity Particles */}
        {rarityEffects.particles && (
          <div className={`absolute inset-0 pointer-events-none ${rarityEffects.particles}`}></div>
        )}



        {/* Card Image */}
        <div className="aspect-[2.5/3.5] bg-gray-200 overflow-hidden">
          {!imageError ? (
            <img
              src={card.image_url}
              alt={card.name}
              className="w-full h-full object-cover"
              onError={handleImageError}
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center text-gray-400">
              <div className="text-center">
                <svg className="w-12 h-12 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
                <p className="text-xs">No Image</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Hover Action Buttons */}
      {/* Top Left - Checkbox */}
      <div className="absolute top-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity duration-150 z-20">
        <button
          onClick={(e) => {
            e.stopPropagation();
            onToggleSelect(card);
          }}
          className="p-1 rounded-md shadow-lg transition-all duration-150 hover:scale-105"
          style={{ backgroundColor: 'var(--bg-primary)' }}
        >
          <input
            type="checkbox"
            checked={isSelected}
            onChange={() => {}}
            className="w-4 h-4 rounded focus:ring-1 focus:ring-offset-1"
            style={{ 
              accentColor: 'var(--accent-ember)',
              backgroundColor: 'var(--bg-primary)',
              borderColor: 'var(--border)'
            }}
          />
        </button>
      </div>

      {/* Top Right - Favorite */}
      <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-150 z-20">
        <button
          onClick={(e) => {
            e.stopPropagation();
            onToggleFavorite(card);
          }}
          className="p-1 rounded-md shadow-lg transition-all duration-150 hover:scale-105"
          style={{ 
            backgroundColor: isFavorited ? 'var(--accent-ember)' : 'var(--bg-primary)',
            color: isFavorited ? 'white' : 'var(--accent-ember)'
          }}
          title="Toggle Favorite"
        >
          <svg className="w-4 h-4" fill={isFavorited ? "currentColor" : "none"} stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
          </svg>
        </button>
      </div>

      {/* Bottom Left - Expanding Add Button */}
      <div className="absolute bottom-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity duration-150 z-20">
        <ExpandingAddButton 
          card={card}
          onAddToCollection={onAddToCollection}
          onAddToDeck={onAddToDeck}
          onMarkAsOwned={() => alert(`${VOCAB.ADD_TO_MY_COLLECTION} (coming soon)`)}
        />
      </div>
    </div>
  );
} 