import { useState } from 'react'
import React from 'react'; // Added for useEffect

// --- Scratch Card Game Types and State ---
type Tier = {
  name: string;
  unlockPrice: number;
  buyPrice: number;
};

const TIERS: Tier[] = [
  { name: 'Bronze', unlockPrice: 2, buyPrice: 3 },
  { name: 'Silver', unlockPrice: 5, buyPrice: 7 },
  { name: 'Gold', unlockPrice: 10, buyPrice: 15 },
];

function App() {
  // --- Game State ---
  const [money, setMoney] = useState(20); // User starts with $20
  const [unlockedTiers, setUnlockedTiers] = useState<string[]>([]); // Unlocked tier names
  // Remove selectedTier state
  // const [selectedTier, setSelectedTier] = useState<string | null>(null); // Currently selected tier
  const [count, setCount] = useState(0)

  // --- Card State ---
  const [card, setCard] = useState<{
    winningNumbers: number[];
    fields: { value: number; scratched: boolean; won: number | null }[];
    tier: Tier | null;
  } | null>(null);

  // --- Play History State ---
  const [history, setHistory] = useState<{
    tier: string;
    winnings: number;
    winningNumbers: number[];
    fields: number[];
  }[]>([]);

  // --- Tier Unlock Logic ---
  const handleUnlockTier = (tier: Tier) => {
    if (money >= tier.unlockPrice && !unlockedTiers.includes(tier.name)) {
      setMoney(money - tier.unlockPrice);
      setUnlockedTiers([...unlockedTiers, tier.name]);
    }
  };

  // --- Tier Select Logic ---
  // Remove handleSelectTier
  // const handleSelectTier = (tier: Tier) => {
  //   if (unlockedTiers.includes(tier.name)) {
  //     setSelectedTier(tier.name);
  //   }
  // };

  // Update handleBuyCard to accept tier as argument
  const handleBuyCard = (tier: Tier) => {
    if (!unlockedTiers.includes(tier.name) || money < tier.buyPrice) return;
    // Generate 3 unique winning numbers (1-9)
    const winningNumbers: number[] = [];
    while (winningNumbers.length < 3) {
      const n = Math.floor(Math.random() * 9) + 1;
      if (!winningNumbers.includes(n)) winningNumbers.push(n);
    }
    // Generate 6 random fields (1-9)
    const fields = Array.from({ length: 6 }, () => ({ value: Math.floor(Math.random() * 9) + 1, scratched: false, won: null }));
    setMoney(money - tier.buyPrice);
    setCard({ winningNumbers, fields, tier });
    // Add to history (winnings will be updated after all fields scratched)
    setHistory((h) => [
      { tier: tier.name, winnings: 0, winningNumbers, fields: fields.map(f => f.value) },
      ...h.slice(0, 9)
    ]);
  };

  // --- Update history winnings after all fields scratched ---
  React.useEffect(() => {
    if (!card) return;
    const allScratched = card.fields.every(f => f.scratched);
    if (allScratched) {
      setHistory((h) => {
        const [latest, ...rest] = h;
        if (!latest || latest.winningNumbers !== card.winningNumbers) return h;
        return [
          { ...latest, winnings: card.fields.reduce((sum, f) => sum + (f.won || 0), 0) },
          ...rest
        ];
      });
    }
  }, [card]);

  // --- UI ---
  return (
    <div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center">
      <h1 className="text-3xl font-bold text-blue-600 mb-2">Scratch Card Game</h1>
      <div className="mb-4 text-lg">Money: <span className="font-mono font-bold">${money}</span></div>
      <div className="flex gap-6 mb-8">
        {TIERS.map((tier) => {
          const unlocked = unlockedTiers.includes(tier.name);
          return (
            <div key={tier.name} className="bg-white rounded-lg shadow p-4 flex flex-col items-center w-40">
              <div className="text-xl font-semibold mb-1">{tier.name}</div>
              <div className="text-gray-500 text-sm mb-2">Unlock: ${tier.unlockPrice}</div>
              <div className="text-gray-500 text-sm mb-2">Buy: ${tier.buyPrice}</div>
              {!unlocked ? (
                <button
                  className="bg-yellow-400 hover:bg-yellow-500 text-white font-bold px-4 py-1 rounded mb-1 disabled:opacity-50"
                  disabled={money < tier.unlockPrice}
                  onClick={() => handleUnlockTier(tier)}
                >
                  Unlock
                </button>
              ) : (
                <button
                  className="bg-green-500 hover:bg-green-600 text-white font-bold px-4 py-1 rounded mb-1 disabled:opacity-50"
                  disabled={money < tier.buyPrice}
                  onClick={() => handleBuyCard(tier)}
                >
                  Buy Card
                </button>
              )}
            </div>
          );
        })}
      </div>
      {/* Tier Info and Card Summary */}
      {/* Remove all selectedTier-dependent UI (selected tier info, buy button outside tier cards, etc.) */}
      {card && (
        <div className="mb-2 text-sm text-gray-600">
          <span className="font-semibold">Winnings this card: </span>
          ${card.fields.reduce((sum, f) => sum + (f.won || 0), 0)}
        </div>
      )}
      {/* Card UI */}
      {card && (
        <div className="bg-white rounded-lg shadow p-6 flex flex-col items-center mb-6 w-full max-w-md">
          <div className="mb-2 text-lg font-semibold text-gray-700">{card.tier?.name} Scratch Card</div>
          <div className="mb-4 flex gap-4 justify-center">
            {card.winningNumbers.map((num, i) => (
              <div key={i} className="w-12 h-12 flex items-center justify-center rounded-full bg-blue-100 text-blue-700 text-xl font-bold border-2 border-blue-400">
                {num}
              </div>
            ))}
          </div>
          <div className="grid grid-cols-3 gap-4 mb-2">
            {card.fields.map((field, idx) => (
              <button
                key={idx}
                className={`w-16 h-16 flex items-center justify-center rounded-lg border-2 text-2xl font-bold transition
                  ${field.scratched ? (field.won ? 'bg-green-200 border-green-500 text-green-700' : 'bg-gray-200 border-gray-400 text-gray-500') : 'bg-yellow-100 border-yellow-400 text-yellow-700 hover:bg-yellow-200'}`}
                disabled={field.scratched}
                onClick={() => {
                  if (field.scratched) return;
                  // Determine win amount
                  let won = null;
                  if (card.winningNumbers.includes(field.value)) {
                    if (idx < 2) won = Math.floor((card.tier?.buyPrice ?? 0) * 0.5);
                    else if (idx < 4) won = Math.floor((card.tier?.buyPrice ?? 0) * 0.8);
                    else won = Math.floor((card.tier?.buyPrice ?? 0) * 1.2);
                  }
                  setCard((prev) => {
                    if (!prev) return prev;
                    const newFields = prev.fields.map((f, i) => i === idx ? { ...f, scratched: true, won } : f);
                    return { ...prev, fields: newFields };
                  });
                  if (won) setMoney((m) => m + won);
                }}
              >
                {field.scratched ? (
                  <span>{field.value}{field.won ? <span className="block text-xs font-normal text-green-700">+${field.won}</span> : ''}</span>
                ) : (
                  <span className="text-3xl select-none">?</span>
                )}
              </button>
            ))}
          </div>
          <div className="text-xs text-gray-500">Scratch each field one at a time. Winnings: 1-2 = 50%, 3-4 = 80%, 5-6 = 120% of card price.</div>
        </div>
      )}
      {/* Play History */}
      {history.length > 0 && (
        <div className="w-full max-w-md mb-8">
          <div className="font-semibold text-gray-700 mb-2">Play History</div>
          <ul className="divide-y divide-gray-200 bg-white rounded-lg shadow">
            {history.map((h, i) => (
              <li key={i} className="p-3 flex flex-col sm:flex-row sm:items-center sm:justify-between">
                <div>
                  <span className="font-bold text-blue-600">{h.tier}</span>
                  <span className="ml-2 text-gray-500">Win: ${h.winnings}</span>
                </div>
                <div className="flex gap-2 mt-2 sm:mt-0">
                  {h.winningNumbers.map((n, j) => (
                    <span key={j} className="w-6 h-6 flex items-center justify-center rounded-full bg-blue-100 text-blue-700 text-xs font-bold border border-blue-300">{n}</span>
                  ))}
                </div>
                <div className="flex gap-1 mt-2 sm:mt-0">
                  {h.fields.map((n, j) => (
                    <span key={j} className="w-5 h-5 flex items-center justify-center rounded bg-gray-100 text-gray-700 text-xs border border-gray-300">{n}</span>
                  ))}
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  )
}

export default App
