import React, { useState, useEffect } from 'react'; import { initializeApp } from 'firebase/app'; import { getAuth, signInAnonymously, signInWithCustomToken, onAuthStateChanged } from 'firebase/auth'; import { getFirestore, doc, setDoc, onSnapshot } from 'firebase/firestore';

// Define Firebase configuration and app ID (will be provided by the environment) const firebaseConfig = typeof __firebase_config !== 'undefined' ? JSON.parse(__firebase_config) : {}; const appId = typeof __app_id !== 'undefined' ? __app_id : 'default-warhammer-app'; const initialAuthToken = typeof __initial_auth_token !== 'undefined' ? __initial_auth_token : null;

// Initialize Firebase (will be done once in useEffect) let app; let db; let auth;

function App() { const [userId, setUserId] = useState(null); const [isAuthReady, setIsAuthReady] = useState(false); const [battleLog, setBattleLog] = useState(''); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [expandedBookSummary, setExpandedBookSummary] = useState({ id: null, summary: null }); const [summaryLoading, setSummaryLoading] = useState(false);

// Initialize Firebase and set up auth listener
useEffect(() => {
    let unsubscribeAuth = () => {};

    const initFirebaseAndAuth = async () => {
        try {
            app = initializeApp(firebaseConfig);
            db = getFirestore(app);
            auth = getAuth(app);

            unsubscribeAuth = onAuthStateChanged(auth, (user) => {
                if (user) {
                    setUserId(user.uid);
                } else {
                    setUserId(null);
                }
                setIsAuthReady(true);
            });

            if (initialAuthToken) {
                try {
                    await signInWithCustomToken(auth, initialAuthToken);
                } catch (e) {
                    console.error("Error signing in with custom token (auth/invalid-claims likely):", e.message, "Falling back to anonymous sign-in.");
                    await signInAnonymously(auth);
                }
            } else {
                await signInAnonymously(auth);
            }

        } catch (e) {
            console.error("Critical Error during Firebase initialization or sign-in:", e);
            setError("Failed to initialize the application. Please try again later.");
            setLoading(false);
        }
    };

    initFirebaseAndAuth();

    return () => {
        unsubscribeAuth();
    };
}, []);

// Listen for real-time battle log updates
useEffect(() => {
    if (!db || !isAuthReady || !userId) {
        return;
    }

    const battleLogRef = doc(db, `artifacts/${appId}/public/data/battleLogs`, 'currentBattle');
    const unsubscribe = onSnapshot(battleLogRef, (docSnap) => {
        if (docSnap.exists()) {
            setBattleLog(docSnap.data().log || '');
        } else {
            setDoc(battleLogRef, { log: 'The battlefield is quiet... for now.' }, { merge: true })
                .catch(e => console.error("Error creating initial battle log:", e));
        }
        setLoading(false);
    }, (e) => {
        console.error("Error fetching battle log:", e);
        setError("Failed to load battle log. Please check your connection.");
        setLoading(false);
    });

    return () => unsubscribe();
}, [db, isAuthReady, userId]);

// Function to fetch book summary using Gemini API
const handleFetchSummary = async (bookTitle, bookId) => {
    if (expandedBookSummary.id === bookId) {
        // Collapse if already expanded
        setExpandedBookSummary({ id: null, summary: null });
        return;
    }

    setSummaryLoading(true);
    setExpandedBookSummary({ id: bookId, summary: "Generating summary..." }); // Show temporary loading text
    setError(null);

    const prompt = `Provide a concise summary of the Warhammer book: "${bookTitle}". Keep it to 2-3 sentences.`;
    try {
        let chatHistory = [];
        chatHistory.push({ role: "user", parts: [{ text: prompt }] });
        const payload = { contents: chatHistory };
        const apiKey = ""; // Canvas will provide this during runtime
        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const result = await response.json();
        if (result.candidates && result.candidates.length > 0 &&
            result.candidates[0].content && result.candidates[0].content.parts &&
            result.candidates[0].content.parts.length > 0) {
            const summaryText = result.candidates[0].content.parts[0].text;
            setExpandedBookSummary({ id: bookId, summary: summaryText });
        } else {
            throw new Error("Invalid response from AI for book summary generation.");
        }
    } catch (e) {
        console.error("Error generating book summary:", e);
        setError(`Failed to generate summary: ${e.message}`);
        setExpandedBookSummary({ id: bookId, summary: "Failed to load summary. Please try again." });
    } finally {
        setSummaryLoading(false);
    }
};


const handleUpdateBattleLog = async () => {
    if (!db || !userId) {
        setError("Firebase not ready or user not authenticated.");
        return;
    }

    setLoading(true);
    setError(null);

    const prompt = "Generate a short, epic battle scene description for a Warhammer 40k conflict between the Imperium and Chaos forces. Focus on action and the feel of the universe.";
    try {
        let chatHistory = [];
        chatHistory.push({ role: "user", parts: [{ text: prompt }] });
        const payload = { contents: chatHistory };
        const apiKey = "";
        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const result = await response.json();
        if (result.candidates && result.candidates.length > 0 &&
            result.candidates[0].content && result.candidates[0].content.parts &&
            result.candidates[0].content.parts.length > 0) {
            const newScene = result.candidates[0].content.parts[0].text;
            const battleLogRef = doc(db, `artifacts/${appId}/public/data/battleLogs`, 'currentBattle');
            await setDoc(battleLogRef, { log: newScene, lastUpdated: new Date().toISOString(), by: userId }, { merge: true });
        } else {
            throw new Error("Invalid response from AI for battle scene generation.");
        }
    } catch (e) {
        console.error("Error generating or updating battle log:", e);
        setError(`Failed to generate new battle scene: ${e.message}`);
    } finally {
        setLoading(false);
    }
};


const warhammer40kBooks = [
    "The Horus Heresy Saga (Chronological order):",
    "  1. Horus Rising (Dan Abnett)",
    "  2. False Gods (Graham McNeill)",
    "  3. Galaxy in Flames (Ben Counter)",
    "  4. The Flight of the Eisenstein (James Swallow)",
    "  5. Fulgrim (Graham McNeill)",
    "  6. Descent of Angels (Gav Thorpe)",
    "  7. Legion (Dan Abnett)",
    "  8. Battle for the Abyss (Ben Counter)",
    "  9. Mechanicum (Graham McNeill)",
    "  10. Fallen Angels (Mike Lee)",
    "  11. A Thousand Sons (Graham McNeill)",
    "  12. Prospero Burns (Dan Abnett)",
    "  13. The First Heretic (Aaron Dembski-Bowden)",
    "  14. Nemesis (James Swallow)",
    "  15. The Outcast Dead (Graham McNeill)",
    "  16. Deliverance Lost (Gav Thorpe)",
    "  17. Know No Fear (Dan Abnett)",
    "  18. Fear to Tread (Gav Thorpe)",
    "  19. Angel Exterminatus (Graham McNeill)",
    "  20. Betrayer (Aaron Dembski-Bowden)",
    "  21. Vulkan Lives (Nick Kyme)",
    "  22. The Unremembered Empire (Dan Abnett)",
    "  23. Scars (Chris Wraight)",
    "  24. Vengeful Spirit (Graham McNeill)",
    "  25. Pharos (Guy Haley)",
    "  26. The Damnation of Pythos (David Annandale)",
    "  27. Deathfire (Nick Kyme)",
    "  28. Tallarn (John French)",
    "  29. Ruinstorm (David Annandale)",
    "  30. Old Earth (Nick Kyme)",
    "  31. The Burden of Loyalty (Anthology)",
    "  32. Wolfsbane (Guy Haley)",
    "  33. Born of Flame (Anthology)",
    "  34. Speasr of Macragge (Guy Haley)",
    "  35. The Crimson King (Graham McNeill)",
    "  36. Garro (James Swallow)",
    "  37. Eye of Terra (Anthology)",
    "  38. The Master of Mankind (Aaron Dembski-Bowden)",
    "  39. Perturabo (Guy Haley)",
    "  40. Lorgar (Gav Thorpe)",
    "  41. Ferrus Manus (Josh Reynolds)",
    "  42. Fulgrim (Josh Reynolds)",
    "  43. Corax (Gav Thorpe)",
    "  44. Angron (Phil Kelly)",
    "  45. Jaghatai Khan (Chris Wraight)",
    "  46. Alpharius (Mike Brooks)",
    "  47. Konrad Curze (Guy Haley)",
    "  48. Vulkan (Gav Thorpe)",
    "  49. Mortarion (Robbie MacNiven)",
    "  50. Lion El'Jonson (David Guymer)",
    "  51. Leman Russ (Chris Wraight)",
    "  52. Roboute Guilliman (David Annandale)",
    "  53. Valdor (Chris Wraight)",
    "  54. The Solar War (John French) - Siege of Terra Book 1",
    "  55. The Lost and the Damned (Guy Haley) - Siege of Terra Book 2",
    "  56. The First Wall (Gav Thorpe) - Siege of Terra Book 3",
    "  57. Saturnine (Dan Abnett) - Siege of Terra Book 4",
    "  58. Mortis (John French) - Siege of Terra Book 5",
    "  59. Warhawk (Chris Wraight) - Siege of Terra Book 6",
    "  60. Echoes of Eternity (Aaron Dembski-Bowden) - Siege of Terra Book 7",
    "  61. The End and the Death Vol. 1 (Dan Abnett) - Siege of Terra Book 8",
    "  62. The End and the Death Vol. 2 (Dan Abnett) - Siege of Terra Book 9",
    "  63. The End and the Death Vol. 3 (Dan Abnett) - Siege of Terra Book 10",
    "",
    "The Beast Arises Series (32nd Millennium):",
    "  1. I Am Slaughter (Dan Abnett)",
    "  2. Predator, Prey (Robbie MacNiven)",
    "  3. The Emperor Expects (Gav Thorpe)",
    "  4. The Last Wall (David Annandale)",
    "  5. Throneworld (Guy Haley)",
    "  6. Echoes of the Long War (David Guymer)",
    "  7. The Hunt for Vulkan (David Annandale)",
    "  8. The Beast Must Die (Gav Thorpe)",
    "  9. Watchers in Death (David Guymer)",
    "  10. The Last Son of Dorn (David Annandale)",
    "  11. Shadow of Ullanor (Robbie MacNiven)",
    "  12. The Beheading (Guy Haley)",
    "",
    "The Dark Imperium & Dawn of Fire (42nd Millennium):",
    "  - Dark Imperium (Guy Haley)",
    "  - Dark Imperium: Plague War (Guy Haley)",
    "  - Dark Imperium: Godblight (Guy Haley)",
    "  - Dawn of Fire: Avenging Son (Guy Haley)",
    "  - Dawn of Fire: The Gate of Bones (Andy Clark)",
    "  - Dawn of Fire: Wolftime (Gav Thorpe)",
    "  - Dawn of Fire: Throne of Light (Guy Haley)",
    "  - Dawn of Fire: The Iron Kingdom (Nick Kyme)",
    "  - Dawn of Fire: The Martyr's Tomb (Phil Kelly)",
    "  - Dawn of Fire: Sea of Souls (Chris Wraight)",
    "  - Dawn of Fire: Hand of Abaddon (Robbie MacNiven)",
    "  - Dawn of Fire: The Silent King (Nick Kyme)",
    "",
    "Other Notable Series (Chronological within their own arcs):",
    "  - Gaunt's Ghosts (Dan Abnett - many books, starts with First and Only)",
    "  - Eisenhorn Trilogy (Dan Abnett - Xenos, Malleus, Hereticus)",
    "  - Ravenor Trilogy (Dan Abnett - Ravenor, Ravenor Returned, Ravenor Rogue)",
    "  - Vaults of Terra Trilogy (Chris Wraight - The Carrion Throne, The Hollow Mountain, The Dark City)",
    "  - Watchers of the Throne Trilogy (Chris Wraight - The Emperor's Legion, The Regent's Shadow, The Spire of Dawn)",
];

const warhammerFantasyBooks = [
    "Warhammer Chronicles (Chronological groupings):",
    "  - The Legend of Sigmar (Graham McNeill) - Heldenhammer, Empire, God King",
    "  - The Rise of Nagash (Mike Lee) - Nagash the Sorcerer, Nagash the Undying, Nagash the Immortal",
    "  - Vampire Wars: The von Carstein Trilogy (Steven Savile) - Inheritors of Midnight, Mournblade, Undead",
    "  - The Sundering (Gav Thorpe) - Aenarion, Malekith, Caledor",
    "  - Champions of Chaos (Various authors) - Archaon, Blood for the Blood God, Lord of Chaos",
    "  - The War of Vengeance (Nick Kyme) - The Great Betrayal, Master of Dragons, The Curse of the Phoenix Crown",
    "  - Mathias Thulmann: Witch Hunter (C. L. Werner) - Witch Hunter, Witch Finder, Witch Killer",
    "  - Ulrika the Vampire (Nathan Long) - Bloodborn, Bloodforged, Bloodsworn",
    "  - Masters of Stone and Steel (Various authors) - Dwarfs Omnibus",
    "  - The Tyrion & Teclis Omnibus (William King) - Blood of Aenarion, Sword of Caledor, Bane of Malekith",
    "  - Skaven Wars: The Black Plague Trilogy (C. L. Werner) - Dead Winter, Plague Lord, Skaven Slayer",
    "  - The End Times Series (Follows a specific reading order within itself):",
    "    - Sigmar's Blood",
    "    - Kinslayer",
    "    - The Return of Nagash",
    "    - The Fall of Altdorf",
    "    - Deathblade",
    "    - The Curse of Khaine",
    "    - The Rise of the Horned Rat",
    "    - The Lord of the End Times"
];

const primarchs = [
    // Loyalist Primarchs (with attack and defense descriptions)
    {
        name: "Lion El'Jonson",
        legion: "Dark Angels",
        description: "The enigmatic Primarch of the Dark Angels. A master of strategy and a formidable warrior, he recently re-emerged from his long slumber to confront the challenges facing the Imperium.",
        attack: "Unleashes precise, devastating strikes with the Lion Sword, capable of cleaving through even the heaviest armor. Adept at identifying and exploiting enemy weaknesses.",
        defense: "Possesses formidable dueling skill and tactical foresight, allowing him to anticipate and parry attacks. His unwavering resolve provides significant resilience to his forces."
    },
    {
        name: "Jaghatai Khan",
        legion: "White Scars",
        description: "The Great Khan of the White Scars, master of lightning warfare and peerless strategist. His legion specialized in swift attacks and hit-and-run tactics.",
        attack: "Launches overwhelming, lightning-fast assaults with jetbike and storm-sabre, striking vulnerable flanks and breaking enemy lines before they can react.",
        defense: "Relies on extreme mobility and evasive maneuvers, making him incredibly difficult to pin down. His forces are masters of disengagement and rapid redeployment."
    },
    {
        name: "Leman Russ",
        legion: "Space Wolves",
        description: "The Wolf King, Primarch of the Space Wolves. A fierce and proud warrior, he embodies the savage nobility of Fenris, his homeworld. He vanished after the Horus Heresy.",
        attack: "Engages in brutal, close-quarters combat, tearing through foes with raw power and primal ferocity, often leading a devastating charge.",
        defense: "Unmatched physical resilience and a fearsome will to endure, shrugging off grievous wounds. Inspires fanatic loyalty and courage in his surrounding warriors."
    },
    {
        name: "Rogal Dorn",
        legion: "Imperial Fists",
        description: "The Praetorian of Terra, Primarch of the Imperial Fists. A master of siegecraft and defense, known for his unyielding resolve and stoic devotion to the Emperor.",
        attack: "Coordinates devastating orbital bombardments and highly disciplined assaults, excelling at breaching any fortification or enemy line.",
        defense: "Unrivaled in establishing impenetrable defensive positions and fortifications. Can withstand prolonged sieges and coordinated assaults with minimal casualties."
    },
    {
        name: "Roboute Guilliman",
        legion: "Ultramarines",
        description: "The Lord Commander of the Imperium and Primarch of the Ultramarines. A genius organizer and statesman, he returned in the 41st Millennium to lead humanity's resurgence.",
        attack: "Orchestrates highly coordinated combined-arms strategies, utilizing every unit efficiently to achieve maximum systemic damage to enemy forces.",
        defense: "Establishes robust logistical networks and maintains strict adherence to the Codex Astartes, ensuring his forces are always supplied, reinforced, and tactically superior in defense."
    },
    {
        name: "Vulkan",
        legion: "Salamanders",
        description: "The Lord of Drakes, Primarch of the Salamanders. Known for his compassion and craftsmanship, he values the lives of civilians above all else. He is presumed to return in humanity's greatest need.",
        attack: "Wields the colossal Dawnbringer hammer with earth-shattering force, devastating armored targets and enemy formations with torrents of fire.",
        defense: "Possesses immense durability and regenerative capabilities, making him nearly indestructible. Radiates an aura of indomitable courage that fortifies nearby allies against fear."
    },
    {
        name: "Ferrus Manus",
        legion: "Iron Hands",
        description: "The Gorgon, Primarch of the Iron Hands. A master artificer with hands of living metal, he believed in strength through bionics and suffered a tragic fate during the Horus Heresy.",
        attack: "Delivers pulverizing blows with his metallic hands, crushing foes and rending vehicles with ease. Commands his legion to unleash overwhelming mechanical firepower.",
        defense: "His body, fused with adamantium, grants him extraordinary resilience to damage. His legion's focus on bionics and heavy armor makes them extremely difficult to break."
    },
    {
        name: "Sanguinius",
        legion: "Blood Angels",
        description: "The Great Angel, Primarch of the Blood Angels. Possessing angelic wings and an unparalleled nobility, he was the purest and most beloved of the Primarchs, sacrificing himself to save the Emperor.",
        attack: "Strikes with blinding speed and precision from the skies, tearing through foes with the Blade Encarmine and his innate psychic power.",
        defense: "His angelic grace allows him to evade attacks with impossible agility. His presence inspires his forces to fight with unmatched zeal, defying odds and overwhelming enemies through sheer devotion."
    },
    {
        name: "Corvus Corax",
        legion: "Raven Guard",
        description: "The Raven Lord, Primarch of the Raven Guard. A master of stealth, infiltration, and insurgency, he vanished into the Eye of Terror after the Heresy, seeking vengeance against his traitorous brothers.",
        attack: "Executes swift, surgical strikes from unexpected directions, crippling enemy command and logistical networks with precision and psychological warfare.",
        defense: "Utilizes unparalleled stealth and misdirection, making him and his forces virtually undetectable until it's too late. Avoids direct confrontations, favoring ambushes and calculated retreats."
    },
    // Traitor Primarchs (with attack and defense descriptions)
    {
        name: "Fulgrim",
        legion: "Emperor's Children",
        description: "The Phoenician, Daemon Primarch of the Emperor's Children. Once the embodiment of perfection, he fell to Slaanesh, becoming a grotesque daemon prince obsessed with excess and decadence.",
        attack: "Wields a daemon weapon that inflicts agonizing, soul-rending attacks, delighting in the suffering of his foes. Drives his legion into a frenzy of excessive violence.",
        defense: "Moves with unnatural grace and speed, making him difficult to target. His Slaaneshi blessings grant him grotesque resilience, regenerating from wounds that would fell lesser beings."
    },
    {
        name: "Perturabo",
        legion: "Iron Warriors",
        description: "The Lord of Iron, Daemon Primarch of the Iron Warriors. A master of siege warfare and logistics, his resentment and desire for recognition led him to side with Horus during the Heresy.",
        attack: "Deploys overwhelming artillery bombardments and highly methodical siege tactics, grinding down any resistance with relentless and brutal efficiency.",
        defense: "Fortifies positions with nigh-impenetrable defenses and complex trench networks. His resilience and mastery of engineering make breaching his lines an almost impossible task."
    },
    {
        name: "Konrad Curze",
        legion: "Night Lords",
        description: "The Night Haunter, Primarch of the Night Lords. A grim and nihilistic figure haunted by visions of the future, he believed in terror as the ultimate weapon and reveled in cruelty.",
        attack: "Strikes from the shadows with horrific brutality, sowing widespread terror and despair among enemy ranks, causing them to break and flee in disarray.",
        defense: "Utilizes psychological warfare and fear as a primary defense, often causing enemies to rout before a true engagement. His unpredictability makes him hard to counter."
    },
    {
        name: "Angron",
        legion: "World Eaters",
        description: "The Red Angel, Daemon Primarch of the World Eaters. Consumed by the 'Butcher's Nails,' he is a being of pure, unfettered rage, leading his legion in bloody, close-quarters combat.",
        attack: "Engages in ceaseless, uncontrolled acts of savage violence, tearing apart foes with his bare hands or colossal daemon axe, fueling his rage with every kill.",
        defense: "Impervious to pain and fear due to the Butcher's Nails, making him an unstoppable force that cannot be deterred by damage. His raw, daemonic power deflects many attacks."
    },
    {
        name: "Mortarion",
        legion: "Death Guard",
        description: "The Death Lord, Daemon Primarch of the Death Guard. A grim and resilient figure who sought freedom from oppression, he fell to Nurgle, becoming a harbinger of plague and despair.",
        attack: "Spreads crippling plagues and noxious fumes, weakening enemies before engaging in slow, inevitable close-combat where his scythe reaps souls.",
        defense: "Immensely resilient to all forms of damage and attrition due to Nurgle's blessings. His corrupted form shrugs off wounds and toxins, making him nearly impossible to kill."
    },
    {
        name: "Magnus the Red",
        legion: "Thousand Sons",
        description: "The Crimson King, Daemon Primarch of the Thousand Sons. A powerful psyker and scholar who sought forbidden knowledge, his attempts to warn the Emperor led to his legion's ruin and his fall to Tzeentch.",
        attack: "Unleashes devastating psychic barrages capable of incinerating entire formations or twisting reality itself, often teleporting across the battlefield to strike vulnerable targets.",
        defense: "Shields himself with powerful warp energies, deflecting incoming attacks with arcane might. His foresight allows him to anticipate enemy moves, nullifying threats before they materialize."
    },
    {
        name: "Horus Lupercal",
        legion: "Sons of Horus",
        description: "The Warmaster, Primarch of the Sons of Horus. Once the most beloved son and chosen successor of the Emperor, he was corrupted by Chaos and led the galaxy-wide rebellion that bears his name.",
        attack: "Wields the Warmaster's Talon and Worldbreaker, delivering crushing blows and energy blasts. His strategic genius allows him to outmaneuver and devastate any opposing force.",
        defense: "Protected by warp-enhanced power armor and formidable combat skills. His charisma bends wills, turning allies and enemies alike into pawns or shields."
    },
    {
        name: "Lorgar Aurelian",
        legion: "Word Bearers",
        description: "The Urizen, Daemon Primarch of the Word Bearers. A devout seeker of truth and faith, his initial devotion to the Emperor turned to zealotry for the Chaos Gods after his censure at Monarchia.",
        attack: "Incites his forces into fanatical frenzies, unleashing daemonic pacts and blasphemous rituals to empower his attacks and break enemy morale.",
        defense: "His unshakeable faith in the Ruinous Powers grants him spiritual protection. His zealots act as a living shield, absorbing vast amounts of damage in his name."
    },
    {
        name: "Alpharius Omegon",
        legion: "Alpha Legion",
        description: "The Twin Serpents, Primarch(s) of the Alpha Legion. Masters of deception, subterfuge, and misdirection, their true loyalties and motivations remain shrouded in mystery to this day.",
        attack: "Strikes through elaborate, multi-layered plans, using feints, hidden units, and psychological operations to destabilize and dismantle enemy forces from within.",
        defense: "Relies on unparalleled subterfuge and misdirection. His true location and identity are almost impossible to ascertain, making direct counter-attacks futile as he slips away unseen."
    },
    // The Lost Primarchs (with placeholder descriptions for attack and defense)
    {
        name: "The Second Primarch",
        legion: "II Legion (Purged)",
        description: "All records of the Second Primarch and their Legion have been expunged from Imperial history. Their fate remains one of the greatest mysteries of the Warhammer 40,000 universe.",
        attack: "Unknown: All records of their combat prowess were purged.",
        defense: "Unknown: Their defensive capabilities are lost to history."
    },
    {
        name: "The Eleventh Primarch",
        legion: "XI Legion (Purged)",
        description: "Like the Second, all information regarding the Eleventh Primarch and their Legion has been systematically removed from Imperial records. Their existence is only hinted at in ancient texts.",
        attack: "Unknown: No combat records of this Primarch exist.",
        defense: "Unknown: Their methods of defense are unrecorded."
    }
];

const techWarriors = [
    {
        name: "Adeptus Astartes (Space Marine)",
        description: "Genetically engineered super-soldiers, equipped with power armor and an array of devastating weaponry. Humanity's finest.",
        attack: "Armed with boltguns, chainswords, and power fists, they deliver rapid, precise ranged volleys and brutal close-combat charges.",
        defense: "Protected by ceramite power armor, offering excellent resistance to small arms fire and even heavy weapons. Their transhuman physiology allows them to endure severe wounds."
    },
    {
        name: "Skitarii Ranger",
        description: "Cybernetic infantry of the Adeptus Mechanicus, their bodies enhanced with arcane technology to serve the Omnissiah.",
        attack: "Utilize galvanic rifles for long-range, focused energy shots that strip enemies of their defenses. Can employ specialized data-tethers to disrupt enemy systems.",
        defense: "Their augmetic enhancements and bionic components provide enhanced durability. Employ 'Cognis Saves' to react to and mitigate incoming attacks with pre-programmed reflexes."
    },
    {
        name: "Adeptus Custodes (Custodian)",
        description: "The Emperor's personal guard, far more powerful and rare than even Space Marines. Gold-clad guardians of Holy Terra.",
        attack: "Wield guardian spears that integrate bolters and power blades, delivering precision attacks with overwhelming force in both melee and ranged combat. Their attacks are highly lethal to any foe.",
        defense: "Clad in auramite armor, making them virtually impervious to most conventional weaponry. Possess unparalleled agility and combat prowess, deflecting or enduring attacks with ease. Their 'Aegis of the Emperor' ability provides psychic protection."
    }
];

const legendaryHeroes = [
    {
        name: "Commander Dante (40k)",
        description: "Chapter Master of the Blood Angels, one of the oldest and most revered Space Marines. A living legend of the Imperium.",
        attack: "Leads Golden Host charges with the Axe Mortalis, inspiring his forces to deliver overwhelming shock assaults. Master of deep strike tactics.",
        defense: "His ancient jump pack allows for rapid repositioning, avoiding heavy fire. Wears the Death Mask of Sanguinius, causing fear in enemies."
    },
    {
        name: "Lord Kroak (Fantasy/AoS)",
        description: "The first and most powerful of the Slann Mage-Priests, a remnant of a bygone era with immense magical power.",
        attack: "Unleashes devastating celestial magic, summoning meteor showers and reality-bending spells that obliterate entire enemy units.",
        defense: "Protected by an ancient, indestructible magical barrier. His mummified form is impervious to most physical harm, regenerating from near destruction."
    },
    {
        name: "Ghazghkull Thraka (40k)",
        description: "The prophet of the WAAAGH!, an Ork Warboss of unprecedented power and ambition, aiming to bring an age of endless war to the galaxy.",
        attack: "Wields the colossal Gork's Klaw and Mork's Roar, tearing through tanks and infantry with brutal, unyielding force. Inspires a 'Great WAAAGH!' that boosts nearby Orks.",
        defense: "Protected by an immense force field and thick adamantium plating. His sheer will and Ork belief make him incredibly resilient, shrugging off damage that would destroy lesser beings."
    }
];

const spaceMarineLegions = [
    // Loyalist Legions
    {
        name: "Ultramarines",
        founding: "First Founding",
        primarch: "Roboute Guilliman",
        traits: "Highly organized, adaptable, and disciplined, strict adherence to the Codex Astartes. Masters of tactical warfare.",
        attack: "Execute flexible combined-arms assaults, leveraging superior tactical positioning and coordinated fire to break enemy formations. Excels in rapid objective seizure.",
        defense: "Maintain rigid battle lines, utilizing strong unit cohesion and established defensive doctrines to hold ground and repel counter-attacks with minimal losses."
    },
    {
        name: "Imperial Fists",
        founding: "First Founding",
        primarch: "Rogal Dorn",
        traits: "Masters of siege warfare and defensive operations. Stoic, unyielding, and known for their unwavering resolve.",
        attack: "Specialize in relentless, grinding assaults on fortified positions, employing overwhelming firepower and engineering expertise to crack open even the most formidable defenses.",
        defense: "Unparalleled in static defense. Can transform any position into an impenetrable bastion, with layered fields of fire and unbreakable resolve, making them nearly impossible to dislodge."
    },
    {
        name: "Blood Angels",
        founding: "First Founding",
        primarch: "Sanguinius",
        traits: "Noble, artistic, but afflicted by the 'Red Thirst' and 'Black Rage.' Masters of close combat and shock assaults.",
        attack: "Unleash furious, bloodthirsty charges, often via jump pack assaults, delivering devastating blows in close quarters. Their rage makes their attacks incredibly potent.",
        defense: "Their zeal and ferocity in combat often deter frontal assaults. Even when severely wounded, the Black Rage can make them fight on with terrifying, unyielding aggression."
    },
    {
        name: "Space Wolves",
        founding: "First Founding",
        primarch: "Leman Russ",
        traits: "Fierce, independent, and proud warriors from Fenris. Known for their feral combat style and close bonds.",
        attack: "Engage in savage, aggressive close-quarters combat, often foregoing ranged attacks for brutal, direct assaults with chainswords and frost axes. Benefit from 'Saga' bonuses.",
        defense: "Their primal endurance and contempt for fear make them incredibly resilient. They fight harder as casualties mount, refusing to break even in the direst circumstances."
    },
    {
        name: "Dark Angels",
        founding: "First Founding",
        primarch: "Lion El'Jonson",
        traits: "Secretive, monastic, obsessed with hunting 'The Fallen.' Excellent tactical flexibility and powerful elite units.",
        attack: "Execute precise, devastating assaults, often focusing on eliminating key enemy targets with surgical efficiency. Their Deathwing and Ravenwing formations are masters of shock tactics.",
        defense: "Maintain unbreakable discipline and grim determination, rarely yielding ground. Their ancient knowledge and secretive nature make them tactically unpredictable to enemies."
    },
    // Traitor Legions
    {
        name: "World Eaters",
        founding: "First Founding",
        primarch: "Angron",
        traits: "Devoted to Khorne, obsessed with close combat and slaughter. Fueled by the 'Butcher's Nails.'",
        attack: "Charge headlong into the enemy, forsaking all caution for relentless, blood-soaked melee. Every kill fuels their berserk fury, making them terrifyingly effective in close combat.",
        defense: "Their absolute lack of fear and pain receptors due to the Butcher's Nails makes them almost impossible to stop once engaged. They will fight to the last, no matter the casualties."
    },
    {
        name: "Death Guard",
        founding: "First Founding",
        primarch: "Mortarion",
        traits: "Devoted to Nurgle, masters of attrition and biological warfare. Indomitable and resilient.",
        attack: "Advance slowly but unstoppably, spreading debilitating plagues and noxious fumes that weaken and corrode the enemy before engaging in relentless, grinding close-quarters combat.",
        defense: "Incredibly tough and resilient, shrugging off damage and enduring the most punishing fire. Nurgle's blessings make them immune to many forms of psychological and physical debuffs."
    },
    {
        name: "Thousand Sons",
        founding: "First Founding",
        primarch: "Magnus the Red",
        traits: "Devoted to Tzeentch, masters of sorcery and arcane lore. Most are now automatons (Rubric Marines).",
        attack: "Unleash devastating psychic powers that warp reality, conjure fire, and blast enemies with raw warp energy. Rubric Marines provide precise, arcane ranged fire.",
        defense: "Protected by powerful psychic wards and the unthinking resolve of their Rubricae. They can manipulate fate to some extent, making them difficult to target or affect with enemy powers."
    },
    {
        name: "Iron Warriors",
        founding: "First Founding",
        primarch: "Perturabo",
        traits: "Masters of siege warfare, fortifications, and artillery. Bitter rivals of the Imperial Fists.",
        attack: "Engage in brutal, methodical sieges, pounding enemy positions with overwhelming artillery barrages and armored assaults. Excels at breaking down any defense.",
        defense: "Construct and occupy formidable defensive strongpoints. Their heavily armored forces are experts at holding ground against even the most determined assaults, utilizing their engineering skill to their advantage."
    },
    {
        name: "Alpha Legion",
        founding: "First Founding",
        primarch: "Alpharius Omegon",
        traits: "Masters of subterfuge, deception, and infiltration. Their true loyalties are unknown.",
        attack: "Employ complex, multi-layered strategies involving feints, ambushes, and targeted assassinations to dismantle enemy command and morale, often attacking from unexpected angles.",
        defense: "Their elusive nature makes them incredibly difficult to pin down. They spread disinformation and confusion, making it hard for enemies to launch effective counter-attacks or discern their true strength."
    }
];


if (loading) {
    return (
        <div className="flex items-center justify-center min-h-screen bg-gray-900 text-gray-100">
            <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-red-600"></div>
            <p className="ml-4 text-xl">Loading... For the Emperor!</p>
        </div>
    );
}

const renderBookList = (books, type) => {
    return (
        <ul className="list-disc list-inside space-y-1 text-gray-200">
            {books.map((book, index) => {
                const isSectionHeader = !book.startsWith("  ");
                const bookId = `${type}-${index}`;
                const isExpanded = expandedBookSummary.id === bookId;

                return (
                    <li key={bookId} className={`${isSectionHeader ? "font-bold text-red-300 mt-3" : "ml-4"} flex flex-col`}>
                        <div className="flex items-center justify-between w-full">
                            <span>{book}</span>
                            {!isSectionHeader && (
                                <button
                                    onClick={() => handleFetchSummary(book.replace(/^\s*\d+\.\s*/, ''), bookId)} // Clean title for prompt
                                    className="ml-4 bg-blue-700 hover:bg-blue-800 text-white text-xs py-1 px-2 rounded-md transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-75"
                                    disabled={summaryLoading && expandedBookSummary.id !== bookId}
                                >
                                    {isExpanded ? "Hide Summary" : (summaryLoading && expandedBookSummary.id === bookId ? "Loading..." : "Show Summary")}
                                </button>
                            )}
                        </div>
                        {isExpanded && (
                            <p className="text-sm text-gray-400 mt-2 p-2 bg-gray-700 rounded-md">
                                {expandedBookSummary.summary}
                            </p>
                        )}
                    </li>
                );
            })}
        </ul>
    );
};


return (
    <div className="min-h-screen bg-gray-900 text-gray-100 font-inter p-4 sm:p-8 flex flex-col items-center">
        <div className="w-full max-w-6xl">
            {/* Header */}
            <header className="text-center mb-10">
                <h1 className="text-4xl sm:text-5xl font-bold text-red-600 mb-2">Warhammer Universe Compendium</h1>
                <p className="text-lg sm:text-xl text-gray-400">Your guide to the grim dark future and the fantasy realms!</p>
                {userId && (
                    <p className="text-xs text-gray-500 mt-2">User ID: {userId}</p>
                )}
                {error && (
                    <p className="text-red-400 mt-2 text-sm">{error}</p>
                )}
            </header>

            {/* Warhammer History Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">A Brief History of the Warhammer Universes</h2>
                <div className="text-gray-300 space-y-4">
                    <h3 className="text-xl font-semibold text-red-400">Warhammer 40,000 - The Grim Darkness</h3>
                    <p>
                        The 41st Millennium is an era of unending war and untold suffering. Humanity, led by the immortal God-Emperor,
                        clings to survival against myriad threats: xenos empires, traitor legions, and the insidious forces of Chaos.
                        Spanning over ten thousand years, the history is vast, from the Age of Strife and the Great Crusade led by the Primarchs,
                        to the devastating Horus Heresy, which nearly brought humanity to its knees. Even after the Heresy, the Imperium
                        remains besieged, constantly fighting for its very existence in a galaxy that knows only war.
                    </p>
                    <h3 className="text-xl font-semibold text-red-400">Warhammer Fantasy - The Old World</h3>
                    <p>
                        Before the Age of Sigmar, the Warhammer Fantasy setting was a brutal world of magic, monsters, and grim
                        battles. The Old World was a dark reflection of medieval Europe, plagued by Chaos incursions, Skaven swarms,
                        Greenskin Waaaghs!, and the endless machinations of Dark Elves and Vampire Counts. The history is marked
                        by ancient wars between Elves and Dwarfs, the rise and fall of empires, and the constant struggle against
                        destruction, culminating in the apocalyptic End Times that brought about the world's demise.
                    </p>
                </div>
            </section>

            {/* The Primarchs Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">The Primarchs</h2>
                <p className="text-gray-300 mb-6">The twenty demigod sons of the Emperor of Mankind, each leading one of the Space Marine Legions during the Great Crusade and the Horus Heresy. Below are their in-game attack and defense capabilities.</p>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    {primarchs.map((primarch, index) => (
                        <div key={index} className="bg-gray-900 rounded-lg overflow-hidden shadow-md border border-gray-700 p-4">
                            <h3 className="font-semibold text-xl text-red-400 mb-2">{primarch.name}</h3>
                            <p className="text-gray-300 text-sm mb-2">
                                <span className="font-bold">Legion:</span> {primarch.legion}
                            </p>
                            <p className="text-gray-300 text-sm mb-2">
                                {primarch.description}
                            </p>
                            <p className="text-gray-200 text-sm mt-3">
                                <span className="font-bold text-green-400">Attack:</span> {primarch.attack}
                            </p>
                            <p className="text-gray-200 text-sm mt-1">
                                <span className="font-bold text-blue-400">Defense:</span> {primarch.defense}
                            </p>
                        </div>
                    ))}
                </div>
            </section>

            {/* Tech Warriors Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">Tech Warriors of the Imperium</h2>
                <p className="text-gray-300 mb-6">These are the technologically advanced soldiers upholding the Emperor's will, featuring their in-game attack and defense capabilities.</p>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    {techWarriors.map((warrior, index) => (
                        <div key={index} className="bg-gray-900 rounded-lg overflow-hidden shadow-md border border-gray-700 p-4">
                            <h3 className="font-semibold text-xl text-red-400 mb-2">{warrior.name}</h3>
                            <p className="text-gray-300 text-sm mb-2">
                                {warrior.description}
                            </p>
                            <p className="text-gray-200 text-sm mt-3">
                                <span className="font-bold text-green-400">Attack:</span> {warrior.attack}
                            </p>
                            <p className="text-gray-200 text-sm mt-1">
                                <span className="font-bold text-blue-400">Defense:</span> {warrior.defense}
                            </p>
                        </div>
                    ))}
                </div>
            </section>

            {/* Space Marine Legions Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">Space Marine Legions</h2>
                <p className="text-gray-300 mb-6">The mighty legions of the Adeptus Astartes, detailing their key traits and their in-game attack and defense specializations.</p>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    {spaceMarineLegions.map((legion, index) => (
                        <div key={index} className="bg-gray-900 rounded-lg overflow-hidden shadow-md border border-gray-700 p-4">
                            <h3 className="font-semibold text-xl text-red-400 mb-2">{legion.name}</h3>
                            <p className="text-gray-300 text-sm mb-1">
                                <span className="font-bold">Founding:</span> {legion.founding}
                            </p>
                            <p className="text-gray-300 text-sm mb-2">
                                <span className="font-bold">Primarch:</span> {legion.primarch}
                            </p>
                            <p className="text-gray-300 text-sm mb-2">
                                <span className="font-bold">Traits:</span> {legion.traits}
                            </p>
                            <p className="text-gray-200 text-sm mt-3">
                                <span className="font-bold text-green-400">Attack:</span> {legion.attack}
                            </p>
                            <p className="text-gray-200 text-sm mt-1">
                                <span className="font-bold text-blue-400">Defense:</span> {legion.defense}
                            </p>
                        </div>
                    ))}
                </div>
            </section>

            {/* Warhammer 40k Books Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">Warhammer 40,000 Book List</h2>
                <p className="text-gray-300 mb-4">A chronological reading order for key Warhammer 40,000 series. Click 'Show Summary' to learn more about each book!</p>
                <div className="overflow-x-auto">
                    {renderBookList(warhammer40kBooks, '40k')}
                </div>
            </section>

            {/* Warhammer Fantasy Books Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">Warhammer Fantasy Book List</h2>
                <p className="text-gray-300 mb-4">A recommended chronological reading order for the rich tales of the Old World. Click 'Show Summary' to learn more about each book!</p>
                <div className="overflow-x-auto">
                    {renderBookList(warhammerFantasyBooks, 'fantasy')}
                </div>
            </section>

            {/* Battle Scenes Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">Battle Scenes</h2>
                <p className="text-gray-300 mb-4">Experience the unending conflict and brutal majesty of the Warhammer universe through dynamic battle log entries. Click 'Generate New Scene' to witness a different moment of war!</p>
                <div className="bg-gray-900 p-4 rounded-lg border border-gray-700 mb-4">
                    <p className="text-gray-200 whitespace-pre-wrap">{battleLog}</p>
                </div>
                <button
                    onClick={handleUpdateBattleLog}
                    className="w-full bg-red-700 hover:bg-red-800 text-white font-bold py-3 px-6 rounded-xl shadow-lg transition duration-300 ease-in-out transform hover:scale-105
                               focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-75"
                    disabled={loading}
                >
                    {loading ? 'Generating...' : 'Generate New Battle Scene'}
                </button>
            </section>

            {/* Legendary Heroes Section */}
            <section className="bg-gray-800 p-6 rounded-xl shadow-lg mb-8 border border-red-700">
                <h2 className="text-3xl font-semibold text-red-500 mb-4 text-center">Legendary Heroes of Warhammer</h2>
                <p className="text-gray-300 mb-6">From both the grimdark 41st Millennium and the perilous Old World, these heroes have shaped their universes. Below are their in-game attack and defense capabilities.</p>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                    {legendaryHeroes.map((hero, index) => (
                        <div key={index} className="bg-gray-900 rounded-lg overflow-hidden shadow-md border border-gray-700 p-4">
                            <h3 className="font-semibold text-xl text-red-400 mb-2">{hero.name}</h3>
                            <p className="text-gray-300 text-sm mb-2">
                                {hero.description}
                            </p>
                            <p className="text-gray-200 text-sm mt-3">
                                <span className="font-bold text-green-400">Attack:</span> {hero.attack}
                            </p>
                            <p className="text-gray-200 text-sm mt-1">
                                <span className="font-bold text-blue-400">Defense:</span> {hero.defense}
                            </p>
                        </div>
                    ))}
                </div>
            </section>
        </div>
    </div>
);

}

export default App;

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support