import { useState, useEffect, useRef } from "react";
import { usePlayer } from "../providers/PlayerProvider";
import styles from "../styles/Army.module.css";

// Quote categories based on total minted GELD
const PROGRESSION_TIERS = {
  BEGINNER: BigInt("1000000"),
  NOVICE: BigInt("10000000"),
  INTERMEDIATE: BigInt("100000000"),
  EXPERIENCED: BigInt("1000000000"),
  EXPERT: BigInt("10000000000"),
  MASTER: BigInt("100000000000"),
  EPIC: BigInt("1000000000000"),
  LEGENDARY: BigInt("10000000000000"),
  GUILD_LEADER: BigInt("100000000000000"),
  DIVINE: BigInt("1000000000000000"),
  MAXIMUM: BigInt("10000000000000000"),
};

const quotes = {
  BEGINNER: [
    "Well, well... another fresh face looking to be a hero. At least you're holding your weapon the right way up.",
    "Ha! Your armor's so shiny I can see my reflection. Give it a week, rookie.",
    "Another raider? The rats in the cellar are trembling... with laughter.",
    "Ah, the optimism of the inexperienced. Refreshing, like a cool drink before a hard fall.",
    "Don't worry, we keep the bandages cheap for newcomers like yourself.",
    "I've seen tougher looking raiders, but hey, everyone starts somewhere!",
    "You, a raider? Well, beggars can't be choosers, I suppose.",
    "Try not to dent your armor on the doorframe on your way out.",
    "I remember when I was green as you. Actually, I don't.",
    "The practice dummy out back is taking bets against you. Just thought you should know.",
  ],
  NOVICE: [
    "Back again? You're lasting longer than most of the fresh blood.",
    "You're developing some calluses finally. Good, you'll need them.",
    "Well, you haven't disappeared yet. That's... something.",
    "Starting to walk with a bit of confidence, eh? Don't let it go to your head.",
    "Your reputation precedes you... mind you, it's not saying much.",
    "The local wolves don't laugh quite as hard when they see you coming now.",
    "You're making progress! The practice dummy finally lost some coins.",
    "I see your training is coming along. You only singed your eyebrows twice this week.",
    "Getting better with that weapon. You actually hit what you're aiming at... occasionally.",
    "The raiders have stopped taking bets on when you'll quit. Progress!",
  ],
  INTERMEDIATE: [
    "Now there's a familiar face that's earned their drink!",
    "The usual? You've been around long enough to have a usual!",
    "Looking more battle-worn these days. It suits you.",
    "Your reputation's growing. Heard some kids playing 'mighty raider' in the street.",
    "The local raiders actually know your name now. Well, most of it.",
    "That's quite a collection of scars you're building. Each one's a lesson, eh?",
    "You carry yourself like a real adventurer these days.",
    "Those monsters in the forest? They're starting to learn your name.",
    "Your deeds are becoming tavern tales. Small tales, but tales nonetheless.",
    "That gleam in your eye... you're starting to believe in yourself, aren't you?",
  ],
  EXPERIENCED: [
    "Honor to serve you, friend. Your exploits bring customers to my humble establishment.",
    "The bards are starting to write songs about you. Decent ones, too!",
    "Ah, the hero of the hour! Your usual table awaits.",
    "When they speak of a great raider these days, your name comes up!",
    "Your presence honors us. What tales will you bring today?",
    "The young ones whisper your name in awe. Remember when that was you?",
    "Your legend grows with each passing moon. As does my profit from telling your tales!",
    "The guild speak of your deeds with respect.",
    "You've come so far from that nervous newcomer who first walked through my door.",
    "They say you've met Moloch face to face. Now that's a tale worth hearing!",
  ],
  EXPERT: [
    "My most esteemed patron! The usual bottle of our finest?",
    "Blessed are we to host a hero of your caliber!",
    "Your very presence brings honor to this humble establishment.",
    "The stuff of legends walks among us, friends!",
    "They say you've slain dragons now. Dragons! In my tavern!",
    "Your name echoes through the kingdoms. Yet you still honor us with your presence.",
    "Ah, the mighty raider returns! Shall I dust off the good chalice?",
    "The bards fight over who gets to sing your tales first.",
    "Your achievements bring glory to all who follow your footsteps.",
    "Even the ancient raiders speak of your deeds with reverence.",
  ],
  MASTER: [
    "You humble us with your magnificent presence!",
    "Champions and heroes seek you out for guidance now. How far you've come!",
    "They say your name in whispers in the dark kingdoms of Moloch. In fear.",
    "Your legend spreads even to distant shores. Travelers speak of your deeds in awe.",
    "The very mountains seem to bow in your presence, great one.",
    "Your power radiates like the sun. You've mastered arts few can comprehend.",
    "To think, I've watched you grow from newcomer to living legend!",
    "They say you've went berserk naked in a raid. The gods must surely know your name.",
    "Your mastery of the raider's arts is unmatched in all the realms.",
    "The ancient prophecies speak of one such as you...",
  ],
  EPIC: [
    "They say you've mastered every weapon in the realm!",
    "Is it true you've tamed the ancient dragons?",
    "The Moloch speaks your name in terror!",
    "Your magic reshapes the very world!",
    "None have delved deeper into the ancient dungeons!",
  ],
  LEGENDARY: [
    "The greatest raider of our age graces us! All hail!",
    "Your presence blesses this humble tavern, O mighty one!",
    "Let it be known - a living legend walks among us!",
    "The realm's greatest champion returns to honor us!",
    "Your deeds will be told for a thousand years!",
    "Gods walk among us this day! Welcome, mighty hero!",
    "Champion of champions! Slayer of the Moloch!",
    "Your very footsteps shake the foundations of reality!",
    "None have achieved what you have, great one!",
    "The stars themselves dim in your presence!",
  ],
  GUILD_LEADER: [
    "The guild masters seek your counsel now, don't they?",
    "Your followers grow more numerous by the day!",
    "Even kings bow to your wisdom in matters of war!",
    "The greatest raider academy bears your name!",
    "Your teachings will guide generations to come!",
    "The realm was forever changed when you sealed the Dark Portal of Moloch!",
    "Peace reigns because you guard our lands!",
    "The ancient prophecies spoke true of your coming!",
    "Even the gods watch your journey with interest!",
    "The very fabric of magic bears your mark!",
  ],
  DIVINE: [
    "Even the Moloch fears your coming!",
    "The Cohort VI champions pale before your glory!",
    "The Moon shines brighter in your presence!",
    "The Golden Lady herself seeks your blessing!",
    "The elements themselves bend to your will!",
    "The Sword of Ages chosen YOU as its wielder!",
    "You've walked the Path of a Thousand Stars!",
    "The Ancient Trials bow before your mastery!",
    "Bearer of the Eternal Flame!",
    "Even Sayonara uses your deeds as images!",
  ],
  MAXIMUM: [
    "Hamsterverse itself bends in your presence, great one!",
    "Your power transcends mortal understanding!",
    "Moloch trembles at your footsteps!",
    "Your legend will outlive the gods themselves!",
    "In all my centuries, none have achieved what you have, mighty raider!",
  ],
};

const EARLY_GAME_QUOTES = [
  "There is always Moloch to be slain here...",
  "We prioritize Shipping at All Costs!",
  "Get out there RAIDER, Moloch won't Slay Himself!",
];

function PixelatedQuote() {
  const { player } = usePlayer();
  const [isShown, setIsShown] = useState(true);
  const [currentQuote, setCurrentQuote] = useState(
    "Welcome to the Dark Forest!"
  );
  const intervalIdRef = useRef<NodeJS.Timeout | null>(null);
  const hasShownWelcome = useRef(false);

  // Determine which tier of quotes to use based on total minted
  const getQuoteTier = (totalMinted: bigint) => {
    if (totalMinted >= PROGRESSION_TIERS.MAXIMUM) return "MAXIMUM";
    if (totalMinted >= PROGRESSION_TIERS.DIVINE) return "DIVINE";
    if (totalMinted >= PROGRESSION_TIERS.GUILD_LEADER) return "GUILD_LEADER";
    if (totalMinted >= PROGRESSION_TIERS.LEGENDARY) return "LEGENDARY";
    if (totalMinted >= PROGRESSION_TIERS.EPIC) return "EPIC";
    if (totalMinted >= PROGRESSION_TIERS.MASTER) return "MASTER";
    if (totalMinted >= PROGRESSION_TIERS.EXPERT) return "EXPERT";
    if (totalMinted >= PROGRESSION_TIERS.EXPERIENCED) return "EXPERIENCED";
    if (totalMinted >= PROGRESSION_TIERS.INTERMEDIATE) return "INTERMEDIATE";
    if (totalMinted >= PROGRESSION_TIERS.NOVICE) return "NOVICE";
    return "BEGINNER";
  };

  useEffect(() => {
    if (intervalIdRef.current !== null) {
      clearInterval(intervalIdRef.current);
    }

    intervalIdRef.current = setInterval(() => {
      const totalMinted = player?.total_minted ?? BigInt(0);

      // Show welcome message only once at the start
      if (!hasShownWelcome.current) {
        setCurrentQuote("Welcome to the Dark Forest!");
        hasShownWelcome.current = true;
      } else if (totalMinted < PROGRESSION_TIERS.BEGINNER) {
        // Show early game quotes until player reaches beginner level
        setCurrentQuote(
          EARLY_GAME_QUOTES[
            Math.floor(Math.random() * EARLY_GAME_QUOTES.length)
          ]
        );
      } else {
        const tier = getQuoteTier(totalMinted);
        const tierQuotes = quotes[tier];
        setCurrentQuote(
          tierQuotes[Math.floor(Math.random() * tierQuotes.length)]
        );
      }
      setIsShown(true);

      setTimeout(() => {
        setIsShown(false);
      }, 5000);
    }, 10000);

    return () => {
      if (intervalIdRef.current !== null) {
        clearInterval(intervalIdRef.current);
        intervalIdRef.current = null;
      }
    };
  }, [player?.total_minted]);

  return (
    <div>
      <div
        className={`pixel-borders pixel-borders--2 pixelFont ${styles.pixelQuote}`}
        style={{ opacity: isShown ? 1 : 0 }}
      >
        {currentQuote}
      </div>
    </div>
  );
}

export default PixelatedQuote;
