"use client";

import { useEffect, useMemo, useState } from "react";

type Pizza = {
  id: number;
  name: string;
  sensei: string;
  description: string;
  price: number;
  accent: string;
  ingredients: string[];
  image: string;
  badge?: string;
};

type CartItem = Pizza & { quantity: number };
type DemoOrder = { number:string; date:string; items:string; total:number; mode:string };
type Nutrition = { serving:string; calories:string; fat:string; saturated:string; trans:string; cholesterol:string; sodium:string; carbs:string; fiber:string; sugars:string; protein:string; allergens:string };

const shellSquad = [
  { name: "Leonardo", color: "#2978c8", role: "Fearless leader", move: "The Rooftop Salute", icon: "L" },
  { name: "Michelangelo", color: "#ff8b25", role: "Pizza-loving party dude", move: "The Pizza Flip", icon: "M" },
  { name: "Donatello", color: "#8d5fd3", role: "Tech genius", move: "The Scanner Spin", icon: "D" },
  { name: "Raphael", color: "#e5342d", role: "Bold hothead", move: "The Shell Shuffle", icon: "R" },
];

const builderToppings = ["Pepperoni", "Sausage", "Mushrooms", "Peppers", "Jalapeños", "Spinach", "Artichokes", "Extra cheese"];

const pizzas: Pizza[] = [
  {
    id: 1,
    name: "The Sewer Supreme",
    sensei: "The crew’s go-to",
    description: "Cup-and-char pepperoni, fennel sausage, roasted peppers, mushrooms & mozzarella.",
    price: 24,
    accent: "#fb3b39",
    ingredients: ["pepperoni", "sausage", "pepper", "mushroom"],
    image: "/pizzas/sewer-supreme.jpg",
    badge: "Most wanted",
  },
  {
    id: 2,
    name: "Cowabunga Classic",
    sensei: "Cheese pull champion",
    description: "Whole-milk mozzarella, aged provolone, pecorino, basil & our slow-cooked red sauce.",
    price: 19,
    accent: "#f6a728",
    ingredients: ["cheese", "basil", "tomato"],
    image: "/pizzas/cowabunga-classic.jpg",
  },
  {
    id: 3,
    name: "Purple Techno",
    sensei: "Smart, bold & garlicky",
    description: "Roasted garlic cream, mozzarella, purple potato, caramelized onion & rosemary.",
    price: 23,
    accent: "#8d5fd3",
    ingredients: ["potato", "onion", "rosemary"],
    image: "/pizzas/purple-techno.jpg",
    badge: "New drop",
  },
  {
    id: 4,
    name: "Orange Party Dude",
    sensei: "Maximum fun per slice",
    description: "Double pepperoni, hot honey, pickled jalapeño, ranch dust & mozzarella.",
    price: 22,
    accent: "#ff8b25",
    ingredients: ["pepperoni", "jalapeño", "honey"],
    image: "/pizzas/orange-party-dude.jpg",
  },
  {
    id: 5,
    name: "Blue Leader",
    sensei: "A disciplined white pie",
    description: "Ricotta, mozzarella, roasted chicken, lemon zest, garlic & cracked pepper.",
    price: 25,
    accent: "#2978c8",
    ingredients: ["ricotta", "chicken", "lemon"],
    image: "/pizzas/blue-leader.jpg",
  },
  {
    id: 6,
    name: "Green Machine",
    sensei: "Plant-powered stealth",
    description: "Spinach, artichoke, broccolini, pesto, charred scallion & vegan mozzarella.",
    price: 23,
    accent: "#61c655",
    ingredients: ["spinach", "artichoke", "broccolini"],
    image: "/pizzas/green-machine.jpg",
    badge: "Vegan",
  },
];

const sides: Pizza[] = [
  { id:101, name:"Nunchuck Garlic Knots", sensei:"8 knots • marinara", description:"Oven-baked knots tossed with roasted garlic butter, pecorino, parsley, and red sauce.", price:8, accent:"#61c655", ingredients:["garlic","pecorino"], image:"/menu/items/garlic-knots.png", badge:"Crew pick" },
  { id:102, name:"Mozzarella Bo Staffs", sensei:"6 crispy sticks", description:"Golden mozzarella sticks with stretchy centers and a side of slow-cooked marinara.", price:10, accent:"#f6a728", ingredients:["mozzarella"], image:"/menu/items/mozzarella-sticks.png" },
  { id:103, name:"Sewer-Lid Fries", sensei:"Shareable basket", description:"Crispy seasoned fries with ranch dust and warm pizza sauce for dipping.", price:7, accent:"#e5342d", ingredients:["potato"], image:"/menu/items/fries.png" },
  { id:104, name:"Party Side Platter", sensei:"Serves 8–10", description:"Garlic knots, mozzarella sticks, fries, marinara, and ranch for the whole birthday crew.", price:34, accent:"#8d5fd3", ingredients:["party platter"], image:"/menu/items/side-platter.png", badge:"Party size" },
];

const drinks: Pizza[] = [
  { id:201, name:"Mutagen Punch", sensei:"20 oz • caffeine-free", description:"Electric-green lemon-lime punch over ice with fresh citrus. Refillable when dining in.", price:4, accent:"#61c655", ingredients:["lemon","lime"], image:"/menu/items/mutagen-punch.png", badge:"Kid favorite" },
  { id:202, name:"Fountain Power-Up", sensei:"20 oz", description:"Choose cola, diet cola, root beer, lemon-lime, orange, or unsweetened iced tea.", price:3.5, accent:"#2978c8", ingredients:["fountain drink"], image:"/menu/items/fountain-drink.png" },
  { id:203, name:"Junior Juice Box", sensei:"Apple or fruit punch", description:"A chilled, kid-size juice box with no artificial colors and an easy paper straw.", price:2.5, accent:"#ff8b25", ingredients:["juice"], image:"/menu/items/juice-box.png" },
  { id:204, name:"Party Punch Pitcher", sensei:"Serves 6–8", description:"A chilled pitcher of Mutagen Punch with cups, ice, citrus wheels, and silly straws.", price:16, accent:"#8d5fd3", ingredients:["party pitcher"], image:"/menu/items/punch-pitcher.png", badge:"Party size" },
];

const desserts: Pizza[] = [
  { id:301, name:"Ooze Brownie", sensei:"Warm & fudgy", description:"Chocolate brownie with green vanilla drizzle, chocolate crumbs, and whipped cream.", price:7, accent:"#61c655", ingredients:["chocolate"], image:"/menu/items/ooze-brownie.png", badge:"New" },
  { id:302, name:"Shell Sugar Cookies", sensei:"4 decorated cookies", description:"Buttery shell-shaped cookies finished with bright green vanilla icing.", price:8, accent:"#2978c8", ingredients:["cookie"], image:"/menu/items/dessert-tray.png" },
  { id:303, name:"Cinnamon Pizza", sensei:"8 sweet slices", description:"Warm cinnamon-sugar dessert pie with buttery streusel and vanilla glaze.", price:12, accent:"#ff8b25", ingredients:["cinnamon"], image:"/menu/items/cinnamon-pizza.png" },
  { id:304, name:"Birthday Dessert Tray", sensei:"Serves 10–12", description:"Ooze brownies, shell cookies, and colorful mini cupcakes ready for a party table.", price:38, accent:"#e5342d", ingredients:["party dessert"], image:"/menu/items/shell-cookies.png", badge:"Party size" },
];

const kidsCombos: Pizza[] = [
  { id:401, name:"Little Leo Combo", sensei:"Ages 12 & under", description:"Junior cheese pizza, garlic knots, fruit cup, and a kid-size fountain drink.", price:13, accent:"#2978c8", ingredients:["cheese pizza","fruit"], image:"/menu/items/little-leo.png", badge:"Complete meal" },
  { id:402, name:"Mikey’s Mini Mission", sensei:"Ages 12 & under", description:"Junior pepperoni pizza, fries, juice box, and a collectible activity sheet.", price:14, accent:"#ff8b25", ingredients:["pepperoni pizza","fries"], image:"/menu/items/mikey-mini.png" },
  { id:403, name:"Donnie’s Smart Snack", sensei:"Vegetarian", description:"Junior cheese pizza, fruit cup, shell cookie, and bottled water.", price:13, accent:"#8d5fd3", ingredients:["cheese pizza","fruit"], image:"/menu/items/donnie-snack.png" },
  { id:404, name:"Birthday Hero Meals", sensei:"10 boxed kids meals", description:"Ten junior cheese pizzas with fruit cups, drinks, cookies, and activity sheets.", price:110, accent:"#e5342d", ingredients:["party meals"], image:"/menu/items/birthday-meals.png", badge:"Party pack" },
];

const menuGroups = { Pizzas:pizzas, Sides:sides, Drinks:drinks, Desserts:desserts, "Kids Combos":kidsCombos };
type MenuCategory = keyof typeof menuGroups;

const nutritionData: Record<number, Nutrition> = {
  1:{serving:"1 slice (1/8 pie)",calories:"390",fat:"19g",saturated:"8g",trans:"0g",cholesterol:"45mg",sodium:"910mg",carbs:"38g",fiber:"3g",sugars:"5g",protein:"18g",allergens:"Milk, wheat"},
  2:{serving:"1 slice (1/8 pie)",calories:"310",fat:"13g",saturated:"7g",trans:"0g",cholesterol:"30mg",sodium:"690mg",carbs:"35g",fiber:"2g",sugars:"4g",protein:"15g",allergens:"Milk, wheat"},
  3:{serving:"1 slice (1/8 pie)",calories:"350",fat:"16g",saturated:"8g",trans:"0g",cholesterol:"35mg",sodium:"640mg",carbs:"42g",fiber:"3g",sugars:"5g",protein:"12g",allergens:"Milk, wheat"},
  4:{serving:"1 slice (1/8 pie)",calories:"380",fat:"18g",saturated:"7g",trans:"0g",cholesterol:"40mg",sodium:"870mg",carbs:"39g",fiber:"2g",sugars:"7g",protein:"16g",allergens:"Milk, wheat, egg"},
  5:{serving:"1 slice (1/8 pie)",calories:"370",fat:"17g",saturated:"9g",trans:"0g",cholesterol:"55mg",sodium:"760mg",carbs:"36g",fiber:"2g",sugars:"3g",protein:"20g",allergens:"Milk, wheat"},
  6:{serving:"1 slice (1/8 pie)",calories:"300",fat:"12g",saturated:"3g",trans:"0g",cholesterol:"0mg",sodium:"620mg",carbs:"39g",fiber:"4g",sugars:"4g",protein:"10g",allergens:"Wheat, tree nuts"},
  101:{serving:"4 knots + sauce",calories:"420",fat:"16g",saturated:"7g",trans:"0g",cholesterol:"25mg",sodium:"790mg",carbs:"57g",fiber:"3g",sugars:"5g",protein:"12g",allergens:"Milk, wheat"},
  102:{serving:"3 sticks + sauce",calories:"410",fat:"23g",saturated:"10g",trans:"0g",cholesterol:"45mg",sodium:"870mg",carbs:"34g",fiber:"2g",sugars:"4g",protein:"17g",allergens:"Milk, wheat, egg"},
  103:{serving:"1 basket",calories:"510",fat:"25g",saturated:"5g",trans:"0g",cholesterol:"5mg",sodium:"830mg",carbs:"65g",fiber:"6g",sugars:"4g",protein:"7g",allergens:"Milk; prepared in shared fryer"},
  104:{serving:"1/10 platter",calories:"460",fat:"23g",saturated:"8g",trans:"0g",cholesterol:"30mg",sodium:"880mg",carbs:"51g",fiber:"3g",sugars:"4g",protein:"13g",allergens:"Milk, wheat, egg"},
  201:{serving:"20 fl oz",calories:"210",fat:"0g",saturated:"0g",trans:"0g",cholesterol:"0mg",sodium:"40mg",carbs:"54g",fiber:"0g",sugars:"52g",protein:"0g",allergens:"None declared"},
  202:{serving:"20 fl oz",calories:"0–250",fat:"0g",saturated:"0g",trans:"0g",cholesterol:"0mg",sodium:"15–85mg",carbs:"0–67g",fiber:"0g",sugars:"0–65g",protein:"0g",allergens:"None declared"},
  203:{serving:"6.75 fl oz",calories:"80",fat:"0g",saturated:"0g",trans:"0g",cholesterol:"0mg",sodium:"15mg",carbs:"20g",fiber:"0g",sugars:"18g",protein:"0g",allergens:"None declared"},
  204:{serving:"8 fl oz (1/8 pitcher)",calories:"85",fat:"0g",saturated:"0g",trans:"0g",cholesterol:"0mg",sodium:"15mg",carbs:"22g",fiber:"0g",sugars:"21g",protein:"0g",allergens:"None declared"},
  301:{serving:"1 brownie",calories:"490",fat:"24g",saturated:"12g",trans:"0g",cholesterol:"75mg",sodium:"330mg",carbs:"67g",fiber:"4g",sugars:"48g",protein:"6g",allergens:"Milk, wheat, egg, soy"},
  302:{serving:"2 cookies",calories:"320",fat:"14g",saturated:"8g",trans:"0g",cholesterol:"40mg",sodium:"190mg",carbs:"46g",fiber:"1g",sugars:"29g",protein:"3g",allergens:"Milk, wheat, egg"},
  303:{serving:"1 slice (1/8 pie)",calories:"280",fat:"9g",saturated:"4g",trans:"0g",cholesterol:"15mg",sodium:"260mg",carbs:"47g",fiber:"1g",sugars:"25g",protein:"4g",allergens:"Milk, wheat"},
  304:{serving:"1/12 tray",calories:"410",fat:"19g",saturated:"10g",trans:"0g",cholesterol:"55mg",sodium:"280mg",carbs:"58g",fiber:"2g",sugars:"39g",protein:"5g",allergens:"Milk, wheat, egg, soy"},
  401:{serving:"1 complete meal",calories:"760",fat:"25g",saturated:"10g",trans:"0g",cholesterol:"45mg",sodium:"1180mg",carbs:"111g",fiber:"6g",sugars:"35g",protein:"24g",allergens:"Milk, wheat"},
  402:{serving:"1 complete meal",calories:"850",fat:"34g",saturated:"12g",trans:"0g",cholesterol:"55mg",sodium:"1460mg",carbs:"111g",fiber:"5g",sugars:"28g",protein:"27g",allergens:"Milk, wheat"},
  403:{serving:"1 complete meal",calories:"690",fat:"22g",saturated:"10g",trans:"0g",cholesterol:"45mg",sodium:"940mg",carbs:"102g",fiber:"6g",sugars:"31g",protein:"22g",allergens:"Milk, wheat, egg"},
  404:{serving:"1 boxed meal",calories:"720",fat:"24g",saturated:"10g",trans:"0g",cholesterol:"45mg",sodium:"1050mg",carbs:"105g",fiber:"6g",sugars:"33g",protein:"23g",allergens:"Milk, wheat, egg"},
};

const formatMoney = (value: number) => `$${value.toFixed(2)}`;

function PizzaArt({ pizza, priority = false }: { pizza: Pizza; priority?: boolean }) {
  return (
    <div className="pizza-art real-pizza">
      <img src={pizza.image} alt={`${pizza.name}: ${pizza.description}`} loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : "auto"} />
    </div>
  );
}

export default function Home() {
  const [interactive, setInteractive] = useState(false);
  const [cart, setCart] = useState<CartItem[]>([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [reviewsOpen, setReviewsOpen] = useState(false);
  const [deliveryInfoOpen, setDeliveryInfoOpen] = useState(false);
  const [quizOpen, setQuizOpen] = useState(false);
  const [quizStep, setQuizStep] = useState(0);
  const [quizScore, setQuizScore] = useState(0);
  const [confirmation, setConfirmation] = useState<string | null>(null);
  const [deliveryMode, setDeliveryMode] = useState<"delivery" | "pickup">("delivery");
  const [toast, setToast] = useState<string | null>(null);
  const [selectedHero, setSelectedHero] = useState("Surprise me");
  const [lairOpen, setLairOpen] = useState(false);
  const [builderOpen, setBuilderOpen] = useState(false);
  const [partyOpen, setPartyOpen] = useState(false);
  const [partyConfirmed, setPartyConfirmed] = useState(false);
  const [partyRoom, setPartyRoom] = useState<"Arcade Alley"|"Sewer Lair"|"Rooftop HQ">("Arcade Alley");
  const [partyGuests, setPartyGuests] = useState(10);
  const [partyHero, setPartyHero] = useState("Michelangelo");
  const [partyCake, setPartyCake] = useState("Pizza-shaped vanilla");
  const [partyPizzas, setPartyPizzas] = useState(3);
  const [partyArcade, setPartyArcade] = useState(20);
  const [customSize, setCustomSize] = useState<"12" | "16">("16");
  const [customToppings, setCustomToppings] = useState<string[]>(["Extra cheese"]);
  const [tipRate, setTipRate] = useState(0.18);
  const [promoCode, setPromoCode] = useState("");
  const [promoApplied, setPromoApplied] = useState(false);
  const [trackerStep, setTrackerStep] = useState(0);
  const [orderDetails, setOrderDetails] = useState({ name: "", address: "", time: "ASAP", paid: 0 });
  const [pointsOpen, setPointsOpen] = useState(false);
  const [shellPoints, setShellPoints] = useState(125);
  const [memberId, setMemberId] = useState("SHELL-0000");
  const [mobileNavOpen, setMobileNavOpen] = useState(false);
  const [historyOpen, setHistoryOpen] = useState(false);
  const [menuCategory, setMenuCategory] = useState<MenuCategory>("Pizzas");
  const [nutritionItem, setNutritionItem] = useState<Pizza | null>(null);
  const [orderHistory, setOrderHistory] = useState<DemoOrder[]>([]);

  useEffect(() => {
    setInteractive(true);
    const stored = window.localStorage.getItem("ntpp-cart");
    if (stored) setCart(JSON.parse(stored));
    const savedPoints = window.localStorage.getItem("ntpp-shell-points");
    if (savedPoints) setShellPoints(Number(savedPoints));
    let savedMember = window.localStorage.getItem("ntpp-member-id");
    if (!savedMember) { savedMember = `SHELL-${Math.floor(1000 + Math.random() * 9000)}`; window.localStorage.setItem("ntpp-member-id", savedMember); }
    setMemberId(savedMember);
    const savedHistory = window.localStorage.getItem("ntpp-order-history");
    if (savedHistory) setOrderHistory(JSON.parse(savedHistory));
  }, []);

  useEffect(() => {
    window.localStorage.setItem("ntpp-cart", JSON.stringify(cart));
  }, [cart]);

  useEffect(() => { if (interactive) window.localStorage.setItem("ntpp-shell-points", String(shellPoints)); }, [shellPoints, interactive]);
  useEffect(() => { if (interactive) window.localStorage.setItem("ntpp-order-history", JSON.stringify(orderHistory)); }, [orderHistory, interactive]);

  useEffect(() => { if (quizStep === 3) addPoints(75, "Ninja quiz complete"); }, [quizStep]);
  useEffect(() => { if (lairOpen) addPoints(100, "Secret lair discovered"); }, [lairOpen]);
  useEffect(() => { if (partyConfirmed) addPoints(200, "Party mission planned"); }, [partyConfirmed]);

  useEffect(() => {
    if (!confirmation) return;
    setTrackerStep(0);
    const timers = [window.setTimeout(() => setTrackerStep(1), 3500), window.setTimeout(() => setTrackerStep(2), 7000), window.setTimeout(() => setTrackerStep(3), 10500)];
    return () => timers.forEach(window.clearTimeout);
  }, [confirmation]);

  const itemCount = cart.reduce((sum, item) => sum + item.quantity, 0);
  const subtotal = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  const delivery = deliveryMode === "delivery" && cart.length ? 4.99 : 0;
  const discount = promoApplied ? subtotal * 0.1 : 0;
  const tax = (subtotal - discount) * 0.08;
  const tip = (subtotal - discount) * tipRate;
  const total = subtotal - discount + delivery + tax + tip;

  const cartSummary = useMemo(() => cart.map(item => `${item.quantity}× ${item.name}`).join(", "), [cart]);
  const nextReward = shellPoints < 250 ? 250 : shellPoints < 500 ? 500 : shellPoints < 750 ? 750 : 1000;
  const partyBase = partyRoom === "Arcade Alley" ? 199 : partyRoom === "Sewer Lair" ? 299 : 449;
  const partyTotal = partyBase + Math.max(0, partyGuests - 8) * 15 + partyPizzas * 18 + partyArcade + (partyHero === "No character visit" ? 0 : 65) + (partyCake === "Bring our own" ? 0 : 45);

  function addPoints(amount: number, reason: string) {
    setShellPoints(current => current + amount);
    setToast(`+${amount} SHELL POINTS • ${reason}`);
    window.setTimeout(() => setToast(null), 2600);
  }

  function addToCart(pizza: Pizza) {
    setCart(items => {
      const found = items.find(item => item.id === pizza.id);
      return found ? items.map(item => item.id === pizza.id ? { ...item, quantity: item.quantity + 1 } : item) : [...items, { ...pizza, quantity: 1 }];
    });
    setToast(`ORDER UP! ${pizza.name} added to your stash`);
    window.setTimeout(() => setToast(null), 2200);
  }

  function updateQuantity(id: number, delta: number) {
    setCart(items => items.map(item => item.id === id ? { ...item, quantity: item.quantity + delta } : item).filter(item => item.quantity > 0));
  }

  function toggleTopping(topping: string) {
    setCustomToppings(current => current.includes(topping) ? current.filter(item => item !== topping) : [...current, topping]);
  }

  function addCustomPizza() {
    const base = customSize === "16" ? 19 : 15;
    addToCart({ id: Date.now(), name: "My Hero Pizza", sensei: `${customSize}-inch custom pie`, description: customToppings.length ? customToppings.join(", ") : "Classic cheese", price: base + customToppings.length * 1.75, accent: "#6fd33d", ingredients: customToppings, image: "/pizzas/cowabunga-classic.jpg", badge: "Custom" });
    setBuilderOpen(false);
    setCartOpen(true);
    addPoints(25, "Pizza Lab Scientist");
  }

  function placeOrder(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const orderNumber = `NTP-${Math.floor(1000 + Math.random() * 9000)}`;
    setOrderHistory(history => [{ number:orderNumber, date:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"}), items:cartSummary, total, mode:deliveryMode }, ...history].slice(0,5));
    setOrderDetails({ name: `${data.get("firstName")} ${data.get("lastName")}`, address: deliveryMode === "delivery" ? `${data.get("address")}, Rochester, NY ${data.get("zip")}` : "330 East Avenue, Rochester, NY", time: String(data.get("orderTime") || "ASAP"), paid: total });
    setConfirmation(orderNumber);
    setCart([]);
    setCheckoutOpen(false);
    setCartOpen(false);
    addPoints(150, "Demo order complete");
  }

  return (
    <main>
      <div className="simulation-bar">DEMO RESTAURANT • NO REAL ORDERS OR PAYMENTS ARE PROCESSED</div>
      <header className="site-header">
        <a href="#top" className="brand" aria-label="Ninja Turtle Pizza Parlor home">
          <span className="brand-kicker">NINJA TURTLE</span>
          <span className="brand-main">PIZZA PARLOR</span>
        </a>
        <nav className={mobileNavOpen ? "open" : ""} aria-label="Main navigation">
          <a href="#menu">Menu</a><a href="#fun">Kids & parties</a><a href="#squad">Turtles</a><a href="#story">Our story</a><a href="#visit">Visit</a>
          <button onClick={() => {setHistoryOpen(true);setMobileNavOpen(false)}}>Order history</button></nav>
        <button className="mobile-menu" onClick={() => setMobileNavOpen(open => !open)} aria-expanded={mobileNavOpen} aria-label="Toggle navigation">{mobileNavOpen ? "×" : "☰"}</button>
        <button className="points-button" onClick={() => setPointsOpen(true)} aria-label={`Open Shell Points dashboard with ${shellPoints} points`}><span>Shell Points</span><b>{shellPoints}</b></button><button className="cart-button" onClick={() => setCartOpen(true)} aria-label={`Open cart with ${itemCount} items`}>
          <span>Cart</span><b>{itemCount}</b>
        </button>
      </header>

      <section className="hero" id="top">
        <div className="comic-dots" />
        <div className="hero-copy">
          <span className="eyebrow">Henrietta, NY • Hero-sized</span>
          <h1>SLICE.<br/><span>STRIKE.</span><br/>REPEAT.</h1>
          <p>Rochester’s stone-fired pies, underground energy, and costumed character delivery turn pizza night into an event.</p>
          <div className="hero-actions">
            <a className="primary-button" href="#menu">Order pizza <span>→</span></a>
            <a className="text-link" href="#experience">See the experience</a>
          </div>
          <div className="trust-row"><button onClick={() => setReviewsOpen(true)} aria-label="Read simulated Rochester reviews"><b>★ 4.9</b> Rochester favorite <i>Read reviews →</i></button><button onClick={() => setDeliveryInfoOpen(true)} aria-label="Learn how Turtle Delivery works"><b>25–35</b> min local delivery <i>How it works →</i></button></div>
        </div>
        <div className="hero-visual" aria-label="Hot pizza illustration">
          <span className="sound-effect">COWA<br/>BUNGA!</span>
          <div className="pizza-box"><span>HOT • FRESH • HEROIC</span></div>
          <div className="hero-pizza"><PizzaArt pizza={pizzas[0]} priority /></div>
          <div className="steam steam-one">~</div><div className="steam steam-two">~</div>
        </div>
      </section>

      <section className="fun-zone" id="fun">
        <div className="fun-zone-title"><span className="eyebrow dark">More ways to play</span><h2>THE FUN<br/>DOESN’T STOP.</h2></div>
        <button className="fun-card builder-card" onClick={() => setBuilderOpen(true)}><span className="fun-number">01</span><b>BUILD YOUR<br/>OWN PIZZA</b><p>Pick a size, pile on toppings, and add your creation straight to the cart.</p><i>Enter the pizza lab →</i><span className="fun-icon">🍕</span></button>
        <button className="fun-card party-card" onClick={() => { setPartyConfirmed(false); setPartyOpen(true); }}><span className="fun-number">02</span><b>BOOK A<br/>TURTLE PARTY</b><p>Reserve arcade time, pizza, cake, and a visit from your favorite turtle.</p><i>Plan a birthday →</i><span className="fun-icon">🎉</span></button>
        <a href="#ninja-quiz-station" className="fun-card quiz-card" onClick={() => { setQuizStep(0); setQuizScore(0); }}><span className="fun-number">03</span><b>WHICH NINJA<br/>ARE YOU?</b><p>Take a three-question personality quiz and meet your perfect pizza match.</p><i>Start the quiz →</i><span className="fun-icon">🥷</span></a>
      </section>

      <section className="ticker" aria-label="Restaurant highlights">
        <div>STONE-FIRED <i>◆</i> COSTUMED DELIVERY <i>◆</i> NEVER FROZEN <i>◆</i> OPEN LATE <i>◆</i> STONE-FIRED <i>◆</i> COSTUMED DELIVERY</div>
      </section>

      <section className="menu-section" id="menu">
        <div className="section-heading">
          <div><span className="eyebrow dark">Fuel the whole crew</span><h2>THE FULL MENU</h2></div>
          <p>Stone-fired pizzas plus party-ready sides, cold drinks, desserts, and complete kids meals.</p>
        </div>
        <div className="menu-tabs" role="tablist" aria-label="Menu categories">
          {(Object.keys(menuGroups) as MenuCategory[]).map(category => <button key={category} role="tab" aria-selected={menuCategory === category} className={menuCategory === category ? "active" : ""} onClick={() => setMenuCategory(category)}>{category}<small>{menuGroups[category].length}</small></button>)}
        </div>
        <div className={`menu-grid menu-grid-${menuCategory.toLowerCase().replace(" ", "-")}`} role="tabpanel">
          {menuGroups[menuCategory].map((item, index) => (
            <article className={`pizza-card card-${(index % 6) + 1} item-${item.id} ${menuCategory === "Pizzas" ? "" : "menu-item-card"}`} key={item.id}>
              {item.badge && <span className="badge">{item.badge}</span>}
              <PizzaArt pizza={item} />
              <div className="card-copy"><span>{item.sensei}</span><h3>{item.name}</h3><p>{item.description}</p><button className="nutrition-link" onClick={() => setNutritionItem(item)}>Nutrition & allergens <span>→</span></button></div>
              <div className="card-footer"><b>{formatMoney(item.price)}</b><button onClick={() => addToCart(item)} aria-label={`Add ${item.name} to cart`}>Add to cart <span>+</span></button></div>
              <span className="calorie-count">{nutritionData[item.id]?.calories} CAL</span>
            </article>
          ))}
        </div>
        <div className="menu-nutrition-note"><b>2,000 calories a day is used for general nutrition advice, but calorie needs vary.</b><span>Nutrition values are fictional estimates created for this educational restaurant simulation. Additional nutrition and allergen information is available for every item.</span></div>
      </section>

      <section id="ninja-quiz-station" className="quiz-station" aria-label="Which Ninja Are You personality quiz"><div className="quiz-modal">{quizStep < 3 ? <><span className="eyebrow">Question {quizStep + 1} of 3</span><div className="quiz-progress"><i style={{width:`${(quizStep + 1) * 33.33}%`}}/></div><h2>{["Your crew hits a roadblock. What do you do?","Pick your ideal Friday-night energy.","What belongs on a truly heroic pizza?"][quizStep]}</h2><div className="quiz-answers">{[[["Make a plan",0],["Crack a joke",1],["Build a clever fix",2],["Charge ahead",3]],[["Focused and organized",0],["Loud and playful",1],["Games and gadgets",2],["Bold and competitive",3]],[["Clean, classic flavors",0],["Pepperoni and a wild twist",1],["Something unexpected",2],["Big flavor with heat",3]]][quizStep].map(([label,score]) => <button key={String(label)} onClick={() => { setQuizScore(current => current + Number(score)); setQuizStep(step => step + 1); }}>{label}<span>→</span></button>)}</div></> : (() => { const index=quizScore%4; const hero=shellSquad[index]; const match=[pizzas[4],pizzas[3],pizzas[2],pizzas[0]][index]; return <div className="quiz-result" style={{"--quiz-color":hero.color} as React.CSSProperties}><span className="comic-pop">CRUNCH!</span><div className="hero-monogram">{hero.icon}</div><span className="eyebrow dark">Your ninja match</span><h2>{hero.name.toUpperCase()}</h2><p>{hero.role}. Your answers show that your signature move is <b>{hero.move}</b>.</p><div className="pizza-match"><img src={match.image} alt={match.name}/><div><small>Your perfect pizza</small><strong>{match.name}</strong><span>{match.description}</span></div></div><button className="primary-button" onClick={() => { addToCart(match); setCartOpen(true); }}>Add my match • {formatMoney(match.price)} <span>+</span></button><button className="quiz-restart" onClick={() => {setQuizStep(0);setQuizScore(0);}}>Retake quiz</button></div>; })()}</div></section>

      <section className="experience" id="experience">
        <div className="experience-card delivery-card">
          <span className="number">01</span><span className="eyebrow">Doorstep drama</span>
          <h2>DELIVERED<br/>IN CHARACTER.</h2>
          <p>Choose “Ninja Arrival” at checkout and one of our trained costumed heroes will deliver your order with a photo-ready entrance and signature battle pose.</p>
          <ul><li>Family-friendly performances</li><li>Contactless option available</li><li>Costume appearance is always a surprise</li></ul>
        </div>
        <div className="experience-card dine-card">
          <span className="number">02</span><span className="eyebrow">The underground lair</span>
          <h2>DINE IN.<br/>POWER UP.</h2>
          <p>Grab a booth beneath the city, watch old-school arcade battles, and ring the shell bell when your table finishes a whole pie.</p>
          <a href="#visit" className="primary-button light">Plan your visit <span>→</span></a>
        </div>
      </section>

      <section className="squad-section" id="squad">
        <div className="squad-intro">
          <span className="eyebrow">Meet the delivery heroes</span>
          <h2>THE SHELL<br/>SQUAD.</h2>
          <p>Four Rochester performers. Four signature entrances. One seriously unforgettable pizza delivery. Pick your favorite at checkout—or let the lair surprise you.</p>
          <a href="#menu" className="primary-button">Start an order <span>→</span></a>
        </div>
        <div className="squad-photo"><img src="/characters/shell-squad.jpg" alt="Leonardo in blue, Michelangelo in orange, Donatello in purple, and Raphael in red as costumed delivery performers" loading="lazy" /><span className="photo-sticker">100%<br/>HEROIC</span></div>
        <div className="squad-cards">
          {shellSquad.map(hero => <button key={hero.name} className="squad-card" style={{ "--hero": hero.color } as React.CSSProperties} onClick={() => { setSelectedHero(hero.name); setToast(`${hero.name} selected for your next Ninja Arrival`); window.setTimeout(() => setToast(null), 2200); }}>
            <span className="hero-monogram">{hero.icon}</span><span><small>{hero.role}</small><b>{hero.name}</b><em>Signature: {hero.move}</em></span><i>Choose</i>
          </button>)}
        </div>
      </section>

      <section className="origin-story" id="story">
        <div className="origin-mark">585</div>
        <div className="origin-heading"><span className="eyebrow">Born in Henrietta</span><h2>A LOCAL IDEA.<br/>A BIGGER MISSION.</h2></div>
        <div className="origin-copy">
          <p>Ninja Turtle Pizza Parlor began in Henrietta when former venture-capital advisor and ZaZaPizza business partner Michael D’Angelo saw a chance to make family pizza night far more memorable. The name? With a CEO named D’Angelo, the theme practically chose itself.</p>
          <p>Today, our Rochester-area lair brings together dine-in arcade energy, stone-fired pizza, and our signature costumed home-delivery experience—with a long-term mission to bring the fun to families nationwide.</p>
          <div className="founder-dossier"><div className="founder-photo"><img src="/people/michael-dangelo.png" alt="Michael D’Angelo, fictional founder and CEO"/><span>FOUNDER<br/>FILE 001</span></div><div className="founder-quote"><i>“Make pizza night<br/>a full-blown mission.”</i><div className="founder-signoff"><b>Michael D’Angelo</b><span>Founder & CEO • Chief Pizza Strategist</span></div></div></div>
        </div>
      </section>

      <section className="visit" id="visit">
        <div className="visit-title"><span className="eyebrow dark">Your secret entrance</span><h2>FIND THE LAIR</h2></div>
        <div className="map-panel"><iframe title="Map of the fictional Ninja Turtle Pizza Parlor location in Rochester's East End" src="https://www.google.com/maps?q=330+East+Avenue,+Rochester,+NY+14604&z=14&output=embed" loading="lazy" referrerPolicy="no-referrer-when-downgrade" /><div className="map-label"><b>🍕 NTPP</b><span>Fictional storefront • East End</span></div></div>
        <div className="visit-details">
          <div><span>Fictional location</span><strong>330 East Avenue<br/>Rochester, NY 14604</strong><em>East End • Downtown Rochester</em></div>
          <div><span>Hours</span><strong>Sun–Thu 11am–11pm<br/>Fri–Sat 11am–1am</strong></div>
          <div><span>Call the lair</span><strong><a href="tel:+15858440007">(585) 844-0007</a></strong></div>
          <a className="primary-button" href="https://www.google.com/maps/search/?api=1&query=330+East+Avenue%2C+Rochester%2C+NY+14604" target="_blank" rel="noreferrer">Get directions <span>↗</span></a>
        </div>
      </section>

      <footer>
        <div className="brand footer-brand"><span className="brand-kicker">NINJA TURTLE</span><span className="brand-main">PIZZA PARLOR</span></div>
        <p>Pizza this good doesn’t need a disguise.</p>
        <div className="footer-links"><a href="#menu">Menu</a><a href="#fun">Kids & parties</a><a href="#squad">Turtles</a><a href="#story">Our story</a><a href="#visit">Visit</a></div>
        <button className="manhole-button" onClick={() => setLairOpen(true)} aria-label="Open the secret lair"><span>▦</span> Psst… secret lair</button>
        <small>Educational, fan-made fictional restaurant simulation. Shell Points and rewards have no monetary value. Not affiliated with or endorsed by the Teenage Mutant Ninja Turtles franchise or its rights holders.</small>
      </footer>

      {toast && <div className="toast" role="status">✓ {toast}</div>}

      {historyOpen && <div className="modal-shell checkout-shell" role="dialog" aria-modal="true" aria-label="Demo order history"><div className="history-modal"><button className="close-button" onClick={() => setHistoryOpen(false)} aria-label="Close order history">×</button><span className="eyebrow dark">Saved on this device</span><h2>MISSION HISTORY</h2>{orderHistory.length ? <div className="history-list">{orderHistory.map(order => <article key={order.number}><div><b>{order.number}</b><small>{order.date} • {order.mode}</small></div><p>{order.items}</p><strong>{formatMoney(order.total)}</strong></article>)}</div> : <div className="history-empty"><span>📦</span><h3>No completed missions yet.</h3><p>Place a demo order and its receipt will appear here.</p></div>}<small className="history-note">Simulation only. History is stored locally on this device.</small></div></div>}

      {pointsOpen && <div className="modal-shell checkout-shell" role="dialog" aria-modal="true" aria-label="Shell Points loyalty dashboard"><div className="loyalty-modal"><button className="close-button" onClick={() => setPointsOpen(false)} aria-label="Close Shell Points">×</button><div className="member-card"><span>NINJA TURTLE PIZZA PARLOR</span><b>SHELL SQUAD</b><strong>{memberId}</strong><small>Demo membership • saved on this device</small><i>🍕</i></div><div className="loyalty-content"><span className="eyebrow dark">Arcade-style loyalty</span><h2>{shellPoints} SHELL POINTS</h2><p>Earn fictional points by completing demo missions across the site. Points and rewards have no cash value.</p><div className="reward-progress"><div><i style={{width:`${Math.min(100,(shellPoints/nextReward)*100)}%`}}/></div><span>{Math.max(0,nextReward-shellPoints)} points until your next reward</span></div><h3>UNLOCKED BADGES</h3><div className="badge-grid">{[{icon:"🍕",name:"First Slice",need:0},{icon:"🧪",name:"Pizza Lab Scientist",need:150},{icon:"🥷",name:"Ninja Personality",need:250},{icon:"▦",name:"Lair Finder",need:500}].map(badge => <div key={badge.name} className={shellPoints >= badge.need ? "unlocked" : "locked"}><span>{badge.icon}</span><b>{badge.name}</b><small>{shellPoints >= badge.need ? "Unlocked" : `${badge.need} points`}</small></div>)}</div><h3>FICTIONAL REWARDS</h3><div className="reward-list">{[{points:250,name:"Free topping"},{points:500,name:"20 arcade credits"},{points:750,name:"Priority character request"},{points:1000,name:"Ultimate Lair upgrade"}].map(reward => <div key={reward.name} className={shellPoints >= reward.points ? "ready" : ""}><b>{reward.points}</b><span>{reward.name}</span><em>{shellPoints >= reward.points ? "Ready!" : "Locked"}</em></div>)}</div><div className="earn-list"><b>WAYS TO EARN</b><span>Demo order +150</span><span>Pizza Lab +25</span><span>Ninja quiz +75</span><span>Secret lair +100</span></div></div></div></div>}

      {reviewsOpen && <div className="modal-shell checkout-shell" role="dialog" aria-modal="true" aria-label="Reviews and Turtle Delivery information" onMouseDown={event => { if (event.target === event.currentTarget) setReviewsOpen(false); }}><div className="reviews-modal"><button className="close-button" onClick={() => setReviewsOpen(false)} aria-label="Close reviews">×</button><div className="reviews-hero"><span className="eyebrow">Fictional simulation reviews</span><div className="rating-lockup"><b>4.9</b><div><span>★★★★★</span><small>Based on 247 simulated Rochester reviews</small></div></div><p>Families love the pizza. Kids remember who brought it to the door.</p></div><div className="reviews-body"><section><div className="review-heading"><h2>WHAT ROCHESTER IS SAYING</h2><span>All reviews are fictional and shown for this educational simulation.</span></div><div className="review-grid">{[{name:"Jenna M.",area:"Park Avenue",quote:"Leonardo made our son’s birthday feel like a movie premiere—and the pizza arrived genuinely hot."},{name:"Marcus T.",area:"South Wedge",quote:"The ordering process was easy, the arrival was respectful, and the kids talked about it all weekend."},{name:"Priya R.",area:"Brighton",quote:"I appreciated knowing exactly what to expect. Donatello stayed in character, posed for a photo, and kept the visit brief."}].map(review => <article key={review.name}><span>★★★★★</span><p>“{review.quote}”</p><b>{review.name}</b><small>Verified demo order • {review.area}</small></article>)}</div></section><section className="delivery-explainer"><span className="eyebrow dark">Before you book the hero</span><h2>HOW TURTLE DELIVERY WORKS</h2><div className="delivery-steps"><div><b>1</b><strong>Build your order</strong><p>Choose pizza, delivery time, and a preferred turtle—or let the lair surprise you.</p></div><div><b>2</b><strong>We confirm the mission</strong><p>A real service would verify your address, character availability, allergies, and arrival notes.</p></div><div><b>3</b><strong>Your hero arrives</strong><p>A trained costumed performer delivers the food, greets the family, and poses for one quick photo.</p></div><div><b>4</b><strong>Pizza night continues</strong><p>The visit lasts about 3–5 minutes. No performer enters the home, and an adult must be present.</p></div></div><div className="safety-note"><b>Parent-friendly promise</b><span>Performers would be background-checked, food would travel in sealed packaging, and character requests would remain subject to availability. This website is a simulation—no actual delivery is scheduled.</span></div><button className="primary-button" onClick={() => { setReviewsOpen(false); document.querySelector("#menu")?.scrollIntoView({ behavior:"smooth" }); }}>I’m ready—show me the menu <span>→</span></button></section></div></div></div>}

      {deliveryInfoOpen && <div className="modal-shell checkout-shell" role="dialog" aria-modal="true" aria-label="How Turtle Delivery works" onMouseDown={event => { if(event.target === event.currentTarget) setDeliveryInfoOpen(false); }}><div className="reviews-modal delivery-info-modal"><button className="close-button" onClick={() => setDeliveryInfoOpen(false)} aria-label="Close delivery information">×</button><div className="reviews-hero"><span className="comic-pop">BOOYAKASHA!</span><span className="eyebrow">Before you book the hero</span><h2>HOW TURTLE DELIVERY WORKS</h2><p>A quick, parent-friendly character visit built around a hot pizza delivery.</p></div><div className="reviews-body delivery-explainer"><div className="delivery-steps"><div><b>1</b><strong>Build your order</strong><p>Choose pizza, delivery time, and a preferred turtle—or let the lair surprise you.</p></div><div><b>2</b><strong>We confirm the mission</strong><p>A real service would verify your address, character availability, allergies, and arrival notes.</p></div><div><b>3</b><strong>Your hero arrives</strong><p>A trained costumed performer delivers sealed food, greets the family, and poses for one quick photo.</p></div><div><b>4</b><strong>Pizza night continues</strong><p>The visit lasts about 3–5 minutes. No performer enters the home, and an adult must be present.</p></div></div><div className="safety-note"><b>Parent-friendly promise</b><span>Performers would be background-checked, food would travel in sealed packaging, and character requests would remain subject to availability. This website is a simulation—no actual delivery is scheduled.</span></div><button className="primary-button" onClick={() => { setDeliveryInfoOpen(false); document.querySelector("#menu")?.scrollIntoView({behavior:"smooth"}); }}>I’m ready—show me the menu <span>→</span></button></div></div></div>}

      {quizOpen && <div className="modal-shell confirmation-shell" role="dialog" aria-modal="true" aria-label="Which Ninja Are You personality quiz"><div className="quiz-modal"><button className="close-button" onClick={() => setQuizOpen(false)} aria-label="Close quiz">×</button>{quizStep < 3 ? <><span className="eyebrow">Question {quizStep + 1} of 3</span><div className="quiz-progress"><i style={{width:`${(quizStep + 1) * 33.33}%`}}/></div><h2>{["Your crew hits a roadblock. What do you do?","Pick your ideal Friday-night energy.","What belongs on a truly heroic pizza?"][quizStep]}</h2><div className="quiz-answers">{[[["Make a plan",0],["Crack a joke",1],["Build a clever fix",2],["Charge ahead",3]],[["Focused and organized",0],["Loud and playful",1],["Games and gadgets",2],["Bold and competitive",3]],[["Clean, classic flavors",0],["Pepperoni and a wild twist",1],["Something unexpected",2],["Big flavor with heat",3]]][quizStep].map(([label,score]) => <button key={String(label)} onClick={() => { setQuizScore(current => current + Number(score)); setQuizStep(step => step + 1); }}>{label}<span>→</span></button>)}</div></> : (() => { const index=quizScore%4; const hero=shellSquad[index]; const match=[pizzas[4],pizzas[3],pizzas[2],pizzas[0]][index]; return <div className="quiz-result" style={{"--quiz-color":hero.color} as React.CSSProperties}><span className="comic-pop">CRUNCH!</span><div className="hero-monogram">{hero.icon}</div><span className="eyebrow dark">Your ninja match</span><h2>{hero.name.toUpperCase()}</h2><p>{hero.role}. Your answers show that your signature move is <b>{hero.move}</b>.</p><div className="pizza-match"><img src={match.image} alt={match.name}/><div><small>Your perfect pizza</small><strong>{match.name}</strong><span>{match.description}</span></div></div><button className="primary-button" onClick={() => { addToCart(match); setQuizOpen(false); setCartOpen(true); }}>Add my match • {formatMoney(match.price)} <span>+</span></button><button className="quiz-restart" onClick={() => {setQuizStep(0);setQuizScore(0);}}>Retake quiz</button></div>; })()}</div></div>}

      {cartOpen && <div className="modal-shell" role="dialog" aria-modal="true" aria-label="Your cart" onMouseDown={(event) => { if (event.target === event.currentTarget) setCartOpen(false); }}>
        <aside className="cart-drawer">
          <div className="drawer-header"><div><span className="eyebrow dark">Your pizza stash</span><h2>CART ({itemCount})</h2></div><button className="close-button" onClick={() => setCartOpen(false)} aria-label="Close cart">×</button></div>
          {!cart.length ? <div className="empty-cart"><span>🍕</span><h3>Your box is empty.</h3><p>Choose a legendary pie and get this mission moving.</p><button className="primary-button" onClick={() => setCartOpen(false)}>Browse menu</button></div> : <>
            <div className="cart-items">{cart.map(item => <div className="cart-item" key={item.id}><img className="mini-pizza" src={item.image} alt=""/><div><h3>{item.name}</h3><span>{formatMoney(item.price)}</span><div className="quantity"><button onClick={() => updateQuantity(item.id, -1)} aria-label={`Remove one ${item.name}`}>−</button><b>{item.quantity}</b><button onClick={() => updateQuantity(item.id, 1)} aria-label={`Add one ${item.name}`}>+</button></div></div><b>{formatMoney(item.price * item.quantity)}</b></div>)}</div>
            <div className="cart-totals"><div><span>Subtotal</span><b>{formatMoney(subtotal)}</b></div><p>Taxes and delivery calculated at checkout.</p><button className="primary-button checkout-button" onClick={() => setCheckoutOpen(true)}>Checkout <span>{formatMoney(subtotal)}</span></button></div>
          </>}
        </aside>
      </div>}

      {nutritionItem && (() => { const n=nutritionData[nutritionItem.id]; return <div className="modal-shell confirmation-shell" role="dialog" aria-modal="true" aria-label={`Nutrition information for ${nutritionItem.name}`} onMouseDown={event => { if(event.target === event.currentTarget) setNutritionItem(null); }}><div className={`nutrition-modal item-${nutritionItem.id}`}><button className="close-button" onClick={() => setNutritionItem(null)} aria-label="Close nutrition information">×</button><div className="nutrition-photo"><img src={nutritionItem.image} alt=""/><span>SIMULATED VALUES</span></div><div className="nutrition-content"><span className="eyebrow dark">Nutrition & allergens</span><h2>{nutritionItem.name}</h2><p className="nutrition-serving">Serving size <b>{n.serving}</b></p><div className="nutrition-calories"><span>Calories</span><b>{n.calories}</b></div><div className="nutrition-facts"><div><span>Total Fat</span><b>{n.fat}</b></div><div><span>Saturated Fat</span><b>{n.saturated}</b></div><div><span>Trans Fat</span><b>{n.trans}</b></div><div><span>Cholesterol</span><b>{n.cholesterol}</b></div><div><span>Sodium</span><b>{n.sodium}</b></div><div><span>Total Carbohydrate</span><b>{n.carbs}</b></div><div><span>Dietary Fiber</span><b>{n.fiber}</b></div><div><span>Total Sugars</span><b>{n.sugars}</b></div><div><span>Protein</span><b>{n.protein}</b></div></div><div className="allergen-box"><b>Major allergens</b><span>{n.allergens}</span></div><small>Fictional estimates for this educational simulation—not laboratory-tested values or medical advice. Cross-contact may occur in a shared kitchen.</small><button className="primary-button" onClick={() => {addToCart(nutritionItem);setNutritionItem(null)}}>Add to cart • {formatMoney(nutritionItem.price)} <span>+</span></button></div></div></div> })()}

      {checkoutOpen && <div className="modal-shell checkout-shell" role="dialog" aria-modal="true" aria-label="Checkout">
        <div className="checkout-modal">
          <div className="checkout-top"><div><span className="eyebrow dark">Final mission</span><h2>CHECKOUT</h2></div><button className="close-button" onClick={() => setCheckoutOpen(false)} aria-label="Close checkout">×</button></div>
          <form onSubmit={placeOrder}>
            <div className="mode-toggle"><button type="button" className={deliveryMode === "delivery" ? "active" : ""} onClick={() => setDeliveryMode("delivery")}>Costumed delivery</button><button type="button" className={deliveryMode === "pickup" ? "active" : ""} onClick={() => setDeliveryMode("pickup")}>Pickup</button></div>
            {deliveryMode === "delivery" && <fieldset className="hero-picker"><legend>Choose your delivery hero</legend><div>{["Surprise me", ...shellSquad.map(hero => hero.name)].map(name => <button type="button" key={name} className={selectedHero === name ? "selected" : ""} onClick={() => setSelectedHero(name)}>{name === "Surprise me" ? "🎲" : name.slice(0,1)}<span>{name}</span></button>)}</div><p>Character requests are simulated and subject to availability.</p></fieldset>}
            <div className="field-grid"><label>First name<input required name="firstName" placeholder="April" autoComplete="given-name" /></label><label>Last name<input required name="lastName" placeholder="O’Neil" autoComplete="family-name" /></label><label>Email<input required type="email" name="email" placeholder="april@example.com" autoComplete="email" /></label><label>Phone<input required type="tel" name="phone" placeholder="(585) 555-0142" autoComplete="tel" /></label>{deliveryMode === "delivery" && <><label className="wide">Street address<input required name="address" placeholder="123 East Avenue" autoComplete="street-address" /></label><label>City<input value="Rochester" readOnly aria-label="Delivery city" /></label><label>ZIP code<input required name="zip" inputMode="numeric" pattern="1460[4-9]|1461[0-9]|1462[0-6]" placeholder="14604" title="Enter a Rochester-area ZIP code from 14604–14626" /></label></>}<label>Requested time<select name="orderTime" defaultValue="ASAP"><option>ASAP</option><option>In 45 minutes</option><option>In 1 hour</option><option>In 90 minutes</option></select></label><label>Order notes<input name="notes" placeholder="Buzzer, allergies, etc." /></label></div>
            <label className="checkbox-label"><input type="checkbox" defaultChecked /> Make it a Ninja Arrival (included)</label>
            <div className="checkout-options"><div className="promo-row"><label>Promo code<input value={promoCode} onChange={event => setPromoCode(event.target.value.toUpperCase())} placeholder="Try SHELL10" /></label><button type="button" onClick={() => setPromoApplied(promoCode.trim() === "SHELL10")}>{promoApplied ? "Applied ✓" : "Apply"}</button></div>{promoCode && !promoApplied && promoCode !== "SHELL10" && <small>That code is hiding in another sewer. Try SHELL10.</small>}<fieldset className="tip-picker"><legend>Add a tip for the crew</legend>{[0, .15, .18, .22].map(rate => <button type="button" key={rate} className={tipRate === rate ? "active" : ""} onClick={() => setTipRate(rate)}>{rate ? `${Math.round(rate * 100)}%` : "No tip"}</button>)}</fieldset></div>
            <div className="demo-payment"><span>Simulation payment — no real charge</span><p>Use any fictional values below. Nothing is stored, transmitted, or processed.</p><div className="fake-card"><label>Name on card<input required name="cardName" placeholder="April O’Neil" autoComplete="off" /></label><label>Demo card number<input required name="cardNumber" inputMode="numeric" pattern="[0-9 ]{15,19}" placeholder="4242 4242 4242 4242" autoComplete="off" /></label><label>Expires<input required name="expiry" pattern="[0-9]{2}/[0-9]{2}" placeholder="12/30" autoComplete="off" /></label><label>CVV<input required name="cvv" inputMode="numeric" pattern="[0-9]{3,4}" placeholder="123" autoComplete="off" /></label></div></div>
            <div className="checkout-summary"><p>{cartSummary}</p><div><span>Subtotal</span><b>{formatMoney(subtotal)}</b></div>{promoApplied && <div className="savings"><span>SHELL10 discount</span><b>−{formatMoney(discount)}</b></div>}<div><span>{deliveryMode === "delivery" ? "Delivery" : "Pickup"}</span><b>{delivery ? formatMoney(delivery) : "Free"}</b></div><div><span>Rochester sales tax</span><b>{formatMoney(tax)}</b></div><div><span>Crew tip ({Math.round(tipRate * 100)}%)</span><b>{formatMoney(tip)}</b></div><div className="grand-total"><span>Total</span><b>{formatMoney(total)}</b></div></div>
            <button className="primary-button place-order" type="submit">Place demo order <span>→</span></button>
          </form>
        </div>
      </div>}

      {confirmation && <div className="modal-shell confirmation-shell" role="dialog" aria-modal="true" aria-label="Order confirmed">
        <div className="confirmation receipt"><div className="burst">✓</div><span className="eyebrow dark">Mission accepted • simulation</span><h2>BOOYAKASHA!</h2><p>Thanks, <b>{orderDetails.name}</b>. Order <b>{confirmation}</b> is confirmed. {deliveryMode === "delivery" && <>{selectedHero === "Surprise me" ? "A surprise Shell Squad hero" : selectedHero} is getting mission-ready.</>}</p><div className={`delivery-tracker step-${trackerStep}`}><div className="tracker-line"><i/><i/><i/><i/></div><div className="tracker-labels"><span className={trackerStep >= 0 ? "active" : ""}>Received</span><span className={trackerStep >= 1 ? "active" : ""}>In the oven</span><span className={trackerStep >= 2 ? "active" : ""}>{deliveryMode === "delivery" ? "Out for delivery" : "Ready soon"}</span><span className={trackerStep >= 3 ? "active" : ""}>{deliveryMode === "delivery" ? "At your door" : "Ready"}</span></div></div><div className="eta"><span>{orderDetails.time === "ASAP" ? "Estimated arrival" : "Requested time"}<small>{deliveryMode === "delivery" ? orderDetails.address : "Pickup at the East Avenue lair"}</small></span><strong>{orderDetails.time === "ASAP" ? "28–38 MIN" : orderDetails.time}</strong></div><div className="receipt-total"><span>Demo payment</span><b>{formatMoney(orderDetails.paid)}</b><small>No real charge was made</small></div><button className="primary-button" onClick={() => setConfirmation(null)}>Done</button></div>
      </div>}

      {lairOpen && <div className="modal-shell confirmation-shell" role="dialog" aria-modal="true" aria-label="Secret lair"><div className="secret-lair"><button className="close-button" onClick={() => setLairOpen(false)} aria-label="Close secret lair">×</button><span className="lair-glow">🍕</span><span className="eyebrow">You found it!</span><h2>SECRET LAIR<br/>UNLOCKED</h2><p>Code <b>SHELLSHOCK</b> earns 250 imaginary Shell Points in this simulation.</p><div className="lair-challenge"><strong>KID MISSION</strong><span>Can you spot all four Shell Squad colors on this page?</span><div><i/><i/><i/><i/></div></div><button className="primary-button" onClick={() => { setLairOpen(false); setToast("Secret achievement unlocked: Lair Finder!"); window.setTimeout(() => setToast(null), 2500); }}>Claim demo badge</button></div></div>}

      {builderOpen && <div className="modal-shell confirmation-shell" role="dialog" aria-modal="true" aria-label="Build your own pizza"><div className="builder-modal"><button className="close-button" onClick={() => setBuilderOpen(false)} aria-label="Close pizza builder">×</button><div className="builder-preview"><div className={`custom-pizza size-${customSize}`} aria-label={`Realistic preview with ${customToppings.join(", ") || "cheese"}`}>{customToppings.map(topping => <div key={topping} className={`topping-layer topping-${builderToppings.indexOf(topping)}`} title={topping}>{Array.from({ length: 8 }, (_, piece) => <i key={piece}/>)}</div>)}</div><span>{customSize}″ • {customToppings.length || "Cheese"} {customToppings.length === 1 ? "topping" : "toppings"}</span><small>Preview uses real food photography</small></div><div className="builder-controls"><span className="eyebrow dark">Pizza laboratory</span><h2>BUILD YOUR HERO</h2><fieldset><legend>1. Choose a size</legend><div className="choice-row"><button className={customSize === "12" ? "active" : ""} onClick={() => setCustomSize("12")}>12″ Junior</button><button className={customSize === "16" ? "active" : ""} onClick={() => setCustomSize("16")}>16″ Hero</button></div></fieldset><fieldset><legend>2. Choose toppings • $1.75 each</legend><div className="topping-grid">{builderToppings.map(topping => <button key={topping} className={customToppings.includes(topping) ? "active" : ""} onClick={() => toggleTopping(topping)}>{customToppings.includes(topping) ? "✓ " : "+ "}{topping}</button>)}</div></fieldset><div className="builder-total"><span>Your custom pie</span><b>{formatMoney((customSize === "16" ? 19 : 15) + customToppings.length * 1.75)}</b></div><button className="primary-button" onClick={addCustomPizza}>Add creation to cart <span>→</span></button></div></div></div>}

      {partyOpen && <div className="modal-shell checkout-shell" role="dialog" aria-modal="true" aria-label="Birthday party booking"><div className="party-modal"><button className="close-button" onClick={() => setPartyOpen(false)} aria-label="Close party booking">×</button>{partyConfirmed ? <div className="party-success"><span>🎉</span><h2>PARTY MISSION RECEIVED!</h2><p>Your demo request has been saved. A real party captain would call within one business day to confirm the date, package, and turtle appearance.</p><button className="primary-button" onClick={() => setPartyOpen(false)}>Awesome!</button></div> : <><div className="party-header"><span className="eyebrow">Birthday headquarters</span><h2>PLAN AN EPIC PARTY</h2><p>Every package includes reserved lair seating, pizza, soft drinks, and arcade play.</p></div><form onSubmit={(event) => { event.preventDefault(); setPartyConfirmed(true); }}><div className="party-planner-grid"><div><h3>1. CHOOSE A PARTY ROOM</h3><div className="party-rooms">{[{name:"Arcade Alley",icon:"🕹️",note:"Neon games • up to 10",price:199},{name:"Sewer Lair",icon:"🍕",note:"Private booth • up to 16",price:299},{name:"Rooftop HQ",icon:"🌆",note:"Premium room • up to 24",price:449}].map(room => <button type="button" key={room.name} className={partyRoom === room.name ? "selected" : ""} onClick={() => setPartyRoom(room.name as typeof partyRoom)}><span>{room.icon}</span><b>{room.name}</b><small>{room.note}</small><em>From {formatMoney(room.price)}</em></button>)}</div><h3>2. BUILD THE MISSION</h3><div className="field-grid"><label>Number of guests<input type="number" min="4" max="24" value={partyGuests} onChange={e => setPartyGuests(Number(e.target.value))}/></label><label>Available time<select required><option>11:30 AM — Available</option><option>2:00 PM — Available</option><option>4:30 PM — Only 1 left</option><option disabled>6:00 PM — Booked</option></select></label><label>Character visit<select value={partyHero} onChange={e => setPartyHero(e.target.value)}><option>No character visit</option>{shellSquad.map(hero => <option key={hero.name}>{hero.name}</option>)}</select></label><label>Cake option<select value={partyCake} onChange={e => setPartyCake(e.target.value)}><option>Pizza-shaped vanilla</option><option>Chocolate sewer cake</option><option>Green slime funfetti</option><option>Bring our own</option></select></label><label>Large pizzas<input type="number" min="2" max="10" value={partyPizzas} onChange={e => setPartyPizzas(Number(e.target.value))}/></label><label>Arcade credit pack<select value={partyArcade} onChange={e => setPartyArcade(Number(e.target.value))}><option value="0">Included credits</option><option value="20">+100 credits • $20</option><option value="40">+250 credits • $40</option><option value="65">Unlimited hour • $65</option></select></label><label>Parent or guardian<input required placeholder="Your name" /></label><label>Email<input required type="email" placeholder="parent@example.com" /></label><label>Child’s first name<input required placeholder="Birthday hero" /></label><label>Preferred date<input required type="date" /></label></div><fieldset className="accommodation-options"><legend>Accessibility & food needs</legend><label><input type="checkbox"/> Wheelchair-accessible seating</label><label><input type="checkbox"/> Low-sensory setup</label><label><input type="checkbox"/> Gluten-sensitive food</label><label><input type="checkbox"/> Dairy-free food</label></fieldset><label className="party-notes">Allergies or special requests<textarea placeholder="Tell the party captain what we should know" /></label></div><aside className="party-summary"><span className="eyebrow dark">Live demo estimate</span><h3>{partyRoom}</h3><div><span>{partyGuests} guests</span><b>{formatMoney(partyBase + Math.max(0,partyGuests-8)*15)}</b></div><div><span>{partyPizzas} large pizzas</span><b>{formatMoney(partyPizzas*18)}</b></div><div><span>{partyHero}</span><b>{partyHero === "No character visit" ? "—" : "$65.00"}</b></div><div><span>{partyCake}</span><b>{partyCake === "Bring our own" ? "—" : "$45.00"}</b></div><div><span>Arcade upgrade</span><b>{partyArcade ? formatMoney(partyArcade) : "Included"}</b></div><strong><span>Estimated total</span>{formatMoney(partyTotal)}</strong><small>Simulation estimate. No reservation or charge will occur.</small><button className="primary-button place-order" type="submit">Reserve demo party <span>→</span></button></aside></div></form></>}</div></div>}
    </main>
  );
}
