/**
 * MarketCard Component
 * The "Intelligence Layer" - Shows market items with Dream Match badges and ROI calculations
 * Part of the Universal Archive System v7.0
 */

const { ExternalLink, AlertCircle, TrendingUp, CheckCircle2, Copy, Eye, Star } = lucide;

/**
 * MarketItem type (based on Universal Schema):
 * {
 *   id: string,
 *   title: string,
 *   price_listed: number,
 *   estimated_value: number,
 *   image_url: string,
 *   source_type: 'vestiaire_scrape' | 'collector_scrape',
 *   collection_code: string, // e.g. "95P", "23A"
 *   matched_dream_count: number,
 *   condition_grade: string,
 *   external_url: string,
 *   category: string,
 *   material: string,
 *   color: string
 * }
 */

function MarketCard({ item }) {
  // Calculate Arbitrage (Potential Profit)
  const margin = (item.estimated_value || 0) - item.price_listed;
  const roi = item.price_listed > 0 ? ((margin / item.price_listed) * 100).toFixed(0) : 0;
  const isGoodDeal = margin > 200; // Threshold for "Good Deal"
  
  // Format source badge
  const sourceLabel = {
    'vestiaire_scrape': 'Vestiaire',
    'collector_scrape': 'Collector Sq',
    'reseller': 'Partner',
    'manual': 'Manual'
  }[item.source_type] || item.source_type;

  // Handle add to vault
  const handleAddToVault = async () => {
    try {
      const response = await fetch(`/api/items/${item.id}/convert`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ target_type: 'wardrobe' })
      });
      
      if (response.ok) {
        alert('Added to your wardrobe!');
      } else {
        alert('Failed to add item. Please try again.');
      }
    } catch (error) {
      console.error('Error adding to vault:', error);
      alert('Failed to add item. Please try again.');
    }
  };

  return (
    <div className="group bg-white rounded-xl border border-stone-200 shadow-sm hover:shadow-md transition-all overflow-hidden flex flex-col h-full">
      
      {/* 1. Visual Header */}
      <div className="relative aspect-[4/3] bg-stone-100 overflow-hidden">
        <img 
          src={item.image_url || 'https://via.placeholder.com/400x300?text=No+Image'} 
          alt={item.title} 
          className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
          onError={(e) => {
            e.target.src = 'https://via.placeholder.com/400x300?text=No+Image';
          }}
        />
        
        {/* Source Badge */}
        <span className="absolute top-2 left-2 bg-black/50 backdrop-blur text-white text-[10px] font-bold px-2 py-1 rounded uppercase tracking-wider">
          {sourceLabel}
        </span>

        {/* Collection Code (The Collector's Key) */}
        {item.collection_code && (
          <span className="absolute top-2 right-2 bg-white/90 text-black text-[10px] font-mono font-bold px-2 py-1 rounded border border-stone-200 shadow-sm">
            {item.collection_code}
          </span>
        )}
        
        {/* Category Badge */}
        {item.category && (
          <span className="absolute bottom-2 left-2 bg-white/90 text-stone-700 text-[9px] font-bold px-2 py-1 rounded uppercase tracking-wider">
            {item.category}
          </span>
        )}
      </div>

      {/* 2. Intelligence Layer */}
      <div className="p-4 flex-1 flex flex-col">
        <div className="mb-3">
          <h3 className="font-medium text-stone-900 leading-tight line-clamp-2 h-10 mb-2">
            {item.title}
          </h3>
          <div className="flex flex-wrap gap-1.5 text-xs">
            {item.condition_grade && (
              <span className="bg-stone-100 px-2 py-0.5 rounded text-stone-600">{item.condition_grade}</span>
            )}
            {item.material && (
              <span className="bg-stone-50 px-2 py-0.5 rounded text-stone-500 text-[10px]">{item.material}</span>
            )}
            {item.color && (
              <span className="bg-stone-50 px-2 py-0.5 rounded text-stone-500 text-[10px]">{item.color}</span>
            )}
          </div>
        </div>

        {/* The "Money" Section */}
        <div className="mt-auto border-t border-stone-100 pt-3">
          <div className="flex justify-between items-end mb-2">
            <div>
              <span className="block text-[10px] font-bold text-stone-400 uppercase tracking-wider">Ask Price</span>
              <span className="text-lg font-serif font-bold text-stone-900">€{item.price_listed.toLocaleString()}</span>
            </div>
            {item.estimated_value && (
              <div className="text-right">
                <span className="block text-[10px] font-bold text-stone-400 uppercase tracking-wider">Est. Value</span>
                <span className="text-sm font-mono text-stone-600">€{item.estimated_value.toLocaleString()}</span>
              </div>
            )}
          </div>

          {/* Dream Match Indicator (The "Instant Sale" Signal) */}
          {item.matched_dream_count > 0 ? (
            <div className="bg-indigo-50 border border-indigo-200 rounded-lg p-2 flex items-center gap-2 mb-3">
              <CheckCircle2 className="w-4 h-4 text-indigo-600" />
              <span className="text-xs font-bold text-indigo-700">
                {item.matched_dream_count} {item.matched_dream_count === 1 ? 'User' : 'Users'} Hunting This
              </span>
            </div>
          ) : (
            // Arbitrage Indicator
            isGoodDeal && (
              <div className="bg-emerald-50 border border-emerald-200 rounded-lg p-2 flex items-center gap-2 mb-3">
                <TrendingUp className="w-4 h-4 text-emerald-600" />
                <span className="text-xs font-bold text-emerald-700">
                  +{roi}% Potential ROI
                </span>
              </div>
            )
          )}

          {/* Actions */}
          <div className="grid grid-cols-2 gap-2">
            {item.external_url ? (
              <a 
                href={item.external_url} 
                target="_blank" 
                rel="noreferrer noopener"
                className="flex items-center justify-center gap-1.5 bg-stone-900 text-white py-2 rounded text-xs font-bold hover:bg-stone-800 transition"
              >
                Buy Source <ExternalLink className="w-3 h-3" />
              </a>
            ) : (
              <button 
                disabled
                className="flex items-center justify-center gap-1.5 bg-stone-300 text-stone-500 py-2 rounded text-xs font-bold cursor-not-allowed"
              >
                No Link
              </button>
            )}
            <button 
              onClick={handleAddToVault}
              className="flex items-center justify-center gap-1.5 border border-stone-200 text-stone-600 py-2 rounded text-xs font-bold hover:bg-stone-50 transition"
            >
              Add to Vault <Copy className="w-3 h-3" />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Export for use in other components
window.MarketCard = MarketCard;
