const { useState, useEffect } = React;

// ─── MOCK DATA ─────────────────────────────────────────────
const MOCK_ORDERS = [
  {
    id: "CMD-4821", customer: "Gary Bretegnier", phone: "76.12.34", type: "delivery", time: "16:15", total: 3250,
    pendingSince: Date.now() - 45000, prepTimeLeft: 8, loyalty: "diamond",
    statusHistory: [
      { status: "pending", at: "16:12", label: "Commande reçue" },
    ],
    items: [
      { name: "Burger Classic", category: "Burgers", qty: 2, unitPrice: 950, options: [
        { name: "Sauce BBQ", qty: 2, unitPrice: 0 },
        { name: "Extra fromage", qty: 2, unitPrice: 150 },
      ]},
      { name: "Frites maison", category: "Accompagnements", qty: 2, unitPrice: 450, options: [] },
      { name: "Coca-Cola 33cl", category: "Boissons", qty: 2, unitPrice: 350, options: [] },
    ],
    address: "12 rue de Sébastopol, Nouméa", note: "Pas de cornichons svp", status: "pending", createdAt: "16:12",
  },
  {
    id: "CMD-4820", customer: "Thibaud Crougneau", phone: "77.45.89", type: "pickup", time: "16:30", total: 1850,
    pendingSince: Date.now() - 22000, prepTimeLeft: 14, loyalty: "new",
    statusHistory: [
      { status: "pending", at: "16:08", label: "Commande reçue" },
    ],
    items: [
      { name: "Wrap Poulet", category: "Wraps", qty: 1, unitPrice: 1100, options: [
        { name: "Sauce algérienne", qty: 1, unitPrice: 0 },
        { name: "Supplément avocat", qty: 1, unitPrice: 200 },
      ]},
      { name: "Salade César", category: "Salades", qty: 1, unitPrice: 750, options: [] },
    ],
    note: "", status: "pending", createdAt: "16:08",
  },
  {
    id: "CMD-4822", customer: "Sophie Martin", phone: "78.90.12", type: "delivery", time: "16:20", total: 2700,
    pendingSince: Date.now() - 65000, prepTimeLeft: 5,
    statusHistory: [
      { status: "pending", at: "16:14", label: "Commande reçue" },
    ],
    items: [
      { name: "Pizza 4 Fromages", category: "Pizzas", qty: 1, unitPrice: 1700, options: [
        { name: "Pâte fine", qty: 1, unitPrice: 0 },
      ]},
      { name: "Tiramisu", category: "Desserts", qty: 1, unitPrice: 750, options: [] },
      { name: "Eau plate 50cl", category: "Boissons", qty: 1, unitPrice: 200, options: [] },
    ],
    address: "8 rue Jean Jaurès, Nouméa", note: "Interphone cassé, appeler au 76.12.34", status: "pending", createdAt: "16:14",
  },
  {
    id: "CMD-4823", customer: "Lucas Blanc", phone: "79.33.56", type: "pickup", time: "16:25", total: 1950,
    pendingSince: Date.now() - 18000, prepTimeLeft: 10, loyalty: "diamond",
    statusHistory: [
      { status: "pending", at: "16:10", label: "Commande reçue" },
    ],
    items: [
      { name: "Burger Bacon", category: "Burgers", qty: 1, unitPrice: 1200, options: [
        { name: "Sans oignons", qty: 1, unitPrice: 0 },
        { name: "Double steak", qty: 1, unitPrice: 400 },
      ]},
      { name: "Frites maison", category: "Accompagnements", qty: 1, unitPrice: 450, options: [] },
      { name: "Ice Tea 33cl", category: "Boissons", qty: 1, unitPrice: 300, options: [] },
    ],
    note: "Sans oignons", status: "pending", createdAt: "16:10",
  },
  {
    id: "CMD-4824", customer: "Nathalie Girard", phone: "80.11.44", type: "delivery", time: "16:35", total: 4200,
    pendingSince: Date.now() - 10000, prepTimeLeft: 20, loyalty: "new", scheduled: "17:00",
    statusHistory: [
      { status: "pending", at: "16:16", label: "Commande reçue" },
    ],
    items: [
      { name: "Burger Classic", category: "Burgers", qty: 1, unitPrice: 950, options: [] },
      { name: "Wrap Saumon", category: "Wraps", qty: 2, unitPrice: 1350, options: [
        { name: "Sauce tartare", qty: 2, unitPrice: 0 },
      ]},
      { name: "Fondant Chocolat", category: "Desserts", qty: 1, unitPrice: 800, options: [] },
    ],
    address: "3 allée des Flamboyants, Magenta", note: "", status: "pending", createdAt: "16:16",
  },
  {
    id: "CMD-4819", customer: "Auxence Thomas", phone: "75.88.21", type: "delivery", time: "16:45", total: 4700,
    prepTimeLeft: 12, loyalty: "diamond", driver: { name: "Kévin M.", status: "en_route", eta: null },
    acceptedAt: Date.now() - 300000,
    statusHistory: [
      { status: "pending", at: "15:50", label: "Commande reçue" },
      { status: "preparing", at: "15:55", label: "Acceptée · 20 min" },
    ],
    items: [
      { name: "Pizza Margherita", category: "Pizzas", qty: 1, unitPrice: 1500, options: [] },
      { name: "Pizza 4 Fromages", category: "Pizzas", qty: 1, unitPrice: 1700, options: [] },
      { name: "Tiramisu", category: "Desserts", qty: 2, unitPrice: 750, options: [] },
    ],
    address: "45 av. du Maréchal Foch, Nouméa", note: "Sonner 2 fois", status: "preparing", createdAt: "15:55",
  },
  {
    id: "CMD-4818", customer: "Cyriaque Thomas", phone: "74.55.67", type: "pickup", time: "16:00", total: 2200, prepTimeLeft: 3,
    acceptedAt: Date.now() - 60000,
    statusHistory: [
      { status: "pending", at: "15:42", label: "Commande reçue" },
      { status: "preparing", at: "15:48", label: "Acceptée · 15 min" },
    ],
    items: [
      { name: "Burger Bacon", category: "Burgers", qty: 1, unitPrice: 1200, options: [] },
      { name: "Onion Rings", category: "Accompagnements", qty: 1, unitPrice: 550, options: [] },
      { name: "Ice Tea 33cl", category: "Boissons", qty: 1, unitPrice: 450, options: [] },
    ],
    note: "", status: "preparing", createdAt: "15:48",
  },
  {
    id: "CMD-4817", customer: "Marie Lefèvre", phone: "73.22.90", type: "delivery", time: "16:10", total: 3100,
    prepTimeLeft: -3, driver: { name: "Julien R.", status: "late", delay: 3 },
    acceptedAt: Date.now() - 600000,
    statusHistory: [
      { status: "pending", at: "15:44", label: "Commande reçue" },
      { status: "preparing", at: "15:50", label: "Acceptée · 20 min" },
    ],
    items: [
      { name: "Wrap Poulet", category: "Wraps", qty: 2, unitPrice: 1100, options: [] },
      { name: "Salade César", category: "Salades", qty: 1, unitPrice: 750, options: [] },
      { name: "Coca-Cola 33cl", category: "Boissons", qty: 1, unitPrice: 350, options: [] },
    ],
    address: "22 rue de Verdun, Nouméa", note: "", status: "preparing", createdAt: "15:50",
  },
  {
    id: "CMD-4816", customer: "Jean-Pierre Duval", phone: "82.44.11", type: "pickup", time: "16:05", total: 1450, prepTimeLeft: 1,
    acceptedAt: Date.now() - 480000,
    statusHistory: [
      { status: "pending", at: "15:35", label: "Commande reçue" },
      { status: "preparing", at: "15:42", label: "Acceptée · 10 min" },
    ],
    items: [
      { name: "Pizza Margherita", category: "Pizzas", qty: 1, unitPrice: 1500, options: [] },
    ],
    note: "Bien cuite svp", status: "preparing", createdAt: "15:42",
  },
  {
    id: "CMD-4815", customer: "Camille Rousseau", phone: "71.99.33", type: "delivery", time: "16:15", total: 5200,
    prepTimeLeft: 18, driver: { name: "Thomas L.", status: "arrived", eta: null }, loyalty: "new", scheduled: "16:30",
    acceptedAt: Date.now() - 180000,
    statusHistory: [
      { status: "pending", at: "15:38", label: "Commande reçue" },
      { status: "preparing", at: "15:45", label: "Acceptée · 25 min" },
    ],
    items: [
      { name: "Burger Classic", category: "Burgers", qty: 3, unitPrice: 950, options: [] },
      { name: "Frites maison", category: "Accompagnements", qty: 3, unitPrice: 450, options: [] },
      { name: "Onion Rings", category: "Accompagnements", qty: 2, unitPrice: 550, options: [] },
    ],
    address: "15 rue de l'Alma, Anse Vata", note: "Grosse commande, merci !", status: "preparing", createdAt: "15:45",
  },
  {
    id: "CMD-4814", customer: "Antoine Mercier", phone: "76.55.00", type: "delivery", time: "15:50", total: 3600,
    driver: { name: "Léo P.", status: "arrived", eta: null },
    statusHistory: [
      { status: "pending", at: "15:20", label: "Commande reçue" },
      { status: "preparing", at: "15:22", label: "Acceptée · 20 min" },
      { status: "ready", at: "15:40", label: "Prête" },
    ],
    items: [
      { name: "Pizza Margherita", category: "Pizzas", qty: 2, unitPrice: 1500, options: [] },
      { name: "Tiramisu", category: "Desserts", qty: 1, unitPrice: 750, options: [] },
    ],
    note: "", status: "ready", createdAt: "15:22",
  },
  {
    id: "CMD-4813", customer: "Élodie Perrin", phone: "84.11.77", type: "pickup", time: "15:55", total: 1900,
    loyalty: "diamond",
    statusHistory: [
      { status: "pending", at: "15:25", label: "Commande reçue" },
      { status: "preparing", at: "15:27", label: "Acceptée · 15 min" },
      { status: "ready", at: "15:42", label: "Prête" },
    ],
    items: [
      { name: "Wrap Saumon", category: "Wraps", qty: 1, unitPrice: 1350, options: [] },
      { name: "Onion Rings", category: "Accompagnements", qty: 1, unitPrice: 550, options: [] },
    ],
    note: "", status: "ready", createdAt: "15:27",
  },
];

const MOCK_PRODUCTS = [
  { id: 1, name: "Burger Classic", category: "Burgers", price: 950, active: true },
  { id: 2, name: "Burger Bacon", category: "Burgers", price: 1200, active: true },
  { id: 3, name: "Burger Veggie", category: "Burgers", price: 1050, active: false },
  { id: 4, name: "Wrap Poulet", category: "Wraps", price: 1100, active: true },
  { id: 5, name: "Wrap Saumon", category: "Wraps", price: 1350, active: true },
  { id: 6, name: "Pizza Margherita", category: "Pizzas", price: 1500, active: true },
  { id: 7, name: "Pizza 4 Fromages", category: "Pizzas", price: 1700, active: true },
  { id: 8, name: "Pizza Calzone", category: "Pizzas", price: 1600, active: false },
  { id: 9, name: "Salade César", category: "Salades", price: 750, active: true },
  { id: 10, name: "Frites maison", category: "Accompagnements", price: 450, active: true },
  { id: 11, name: "Onion Rings", category: "Accompagnements", price: 550, active: true },
  { id: 12, name: "Tiramisu", category: "Desserts", price: 750, active: true },
  { id: 13, name: "Fondant Chocolat", category: "Desserts", price: 800, active: true },
  { id: 14, name: "Coca-Cola 33cl", category: "Boissons", price: 350, active: true },
  { id: 15, name: "Ice Tea 33cl", category: "Boissons", price: 450, active: true },
  { id: 16, name: "Eau plate 50cl", category: "Boissons", price: 200, active: false },
];

const MOCK_HISTORY = [
  { id: "CMD-4810", customer: "Antoine Mercier", phone: "76.55.00", type: "delivery", total: 3600, status: "done", date: "04/04", createdAt: "10:45", rating: 5,
    orderedAt: "10:45", acceptedAt: "10:47", readyAt: "11:00", deliveredAt: "11:12",
    items: [{ name: "Burger Classic", category: "Burgers", qty: 2, unitPrice: 950, options: [] }, { name: "Frites maison", category: "Accompagnements", qty: 2, unitPrice: 450, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "10:45", label: "Commande reçue" }, { status: "preparing", at: "10:47", label: "Acceptée · 15 min" }, { status: "done", at: "11:12", label: "Livrée" }] },
  { id: "CMD-4811", customer: "Nathalie Girard", phone: "80.11.44", type: "delivery", total: 1750, loyalty: "diamond", status: "done", date: "04/04", createdAt: "11:22", rating: 4,
    orderedAt: "11:22", acceptedAt: "11:24", readyAt: "11:33", deliveredAt: "11:40",
    items: [{ name: "Wrap Poulet", category: "Wraps", qty: 1, unitPrice: 1100, options: [{ name: "Supplément avocat", qty: 1, unitPrice: 200 }] }, { name: "Salade César", category: "Salades", qty: 1, unitPrice: 750, options: [] }],
    note: "Sans oignons svp", statusHistory: [{ status: "pending", at: "11:22", label: "Commande reçue" }, { status: "preparing", at: "11:24", label: "Acceptée · 10 min" }, { status: "done", at: "11:40", label: "Livrée" }] },
  { id: "CMD-4812", customer: "Olivier Petit", phone: "83.22.11", loyalty: "new", type: "pickup", total: 4100, status: "refused", date: "04/04", createdAt: "11:50",
    items: [{ name: "Pizza Margherita", category: "Pizzas", qty: 2, unitPrice: 1500, options: [] }, { name: "Onion Rings", category: "Accompagnements", qty: 2, unitPrice: 550, options: [] }],
    note: "Grosse faim !", statusHistory: [{ status: "pending", at: "11:50", label: "Commande reçue" }, { status: "refused", at: "11:52", label: "Refusée" }] },
  { id: "CMD-4813", customer: "Camille Rousseau", phone: "71.99.33", type: "delivery", total: 2800, status: "done", date: "04/04", createdAt: "12:15", rating: 3, scheduled: "12:45",
    orderedAt: "12:15", acceptedAt: "12:17", readyAt: "12:35", deliveredAt: "12:50",
    items: [{ name: "Burger Bacon", category: "Burgers", qty: 1, unitPrice: 1200, options: [{ name: "Double steak", qty: 1, unitPrice: 400 }] }, { name: "Frites maison", category: "Accompagnements", qty: 1, unitPrice: 450, options: [] }, { name: "Coca-Cola 33cl", category: "Boissons", qty: 1, unitPrice: 350, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "12:15", label: "Commande reçue" }, { status: "preparing", at: "12:17", label: "Acceptée · 20 min" }, { status: "done", at: "12:50", label: "Livrée" }] },
  { id: "CMD-4814", customer: "Lucas Blanc", phone: "79.33.56", type: "pickup", total: 950, loyalty: "diamond", status: "done", date: "04/04", createdAt: "12:44", rating: 5,
    orderedAt: "12:44", acceptedAt: "12:45", readyAt: "12:50", deliveredAt: "12:50",
    items: [{ name: "Pizza Margherita", category: "Pizzas", qty: 1, unitPrice: 1500, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "12:44", label: "Commande reçue" }, { status: "preparing", at: "12:45", label: "Acceptée · 5 min" }, { status: "done", at: "12:50", label: "Récupérée" }] },
  { id: "CMD-4809", customer: "Sophie Martin", phone: "78.90.12", type: "delivery", total: 5200, status: "done", date: "04/04", createdAt: "13:10", scheduled: "13:45",
    orderedAt: "13:10", acceptedAt: "13:12", readyAt: "13:38", deliveredAt: "13:52",
    items: [{ name: "Burger Classic", category: "Burgers", qty: 3, unitPrice: 950, options: [] }, { name: "Frites maison", category: "Accompagnements", qty: 3, unitPrice: 450, options: [] }],
    note: "Sonner 2 fois", statusHistory: [{ status: "pending", at: "13:10", label: "Commande reçue" }, { status: "preparing", at: "13:12", label: "Acceptée · 25 min" }, { status: "done", at: "13:52", label: "Livrée" }] },
  { id: "CMD-4808", customer: "Jean-Pierre Duval", phone: "82.44.11", type: "pickup", total: 1450, status: "done", date: "04/04", createdAt: "13:55", rating: 4,
    orderedAt: "13:55", acceptedAt: "13:56", readyAt: "14:05", deliveredAt: "14:05",
    items: [{ name: "Pizza Margherita", category: "Pizzas", qty: 1, unitPrice: 1500, options: [] }],
    note: "Bien cuite svp", statusHistory: [{ status: "pending", at: "13:55", label: "Commande reçue" }, { status: "preparing", at: "13:56", label: "Acceptée · 10 min" }, { status: "done", at: "14:05", label: "Récupérée" }] },
  { id: "CMD-4807", customer: "Marie Lefèvre", phone: "73.22.90", type: "delivery", total: 3100, status: "done", date: "04/04", createdAt: "14:32",
    orderedAt: "14:32", acceptedAt: "14:34", readyAt: "14:48", deliveredAt: "15:02",
    items: [{ name: "Wrap Poulet", category: "Wraps", qty: 2, unitPrice: 1100, options: [] }, { name: "Salade César", category: "Salades", qty: 1, unitPrice: 750, options: [] }, { name: "Coca-Cola 33cl", category: "Boissons", qty: 1, unitPrice: 350, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "14:32", label: "Commande reçue" }, { status: "preparing", at: "14:34", label: "Acceptée · 15 min" }, { status: "done", at: "15:02", label: "Livrée" }] },
  { id: "CMD-4806", customer: "Gary Bretegnier", phone: "76.12.34", type: "pickup", total: 2250, loyalty: "diamond", status: "done", date: "03/04", createdAt: "18:05", rating: 5,
    orderedAt: "18:05", acceptedAt: "18:06", readyAt: "18:15", deliveredAt: "18:15",
    items: [{ name: "Burger Classic", category: "Burgers", qty: 1, unitPrice: 950, options: [] }, { name: "Frites maison", category: "Accompagnements", qty: 1, unitPrice: 450, options: [] }, { name: "Ice Tea 33cl", category: "Boissons", qty: 1, unitPrice: 450, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "18:05", label: "Commande reçue" }, { status: "preparing", at: "18:06", label: "Acceptée · 10 min" }, { status: "done", at: "18:15", label: "Récupérée" }] },
  { id: "CMD-4805", customer: "Thibaud Crougneau", phone: "77.45.89", type: "delivery", total: 4800, status: "done", date: "03/04", createdAt: "17:22", rating: 2,
    orderedAt: "17:22", acceptedAt: "17:25", readyAt: "17:44", deliveredAt: "17:58",
    items: [{ name: "Pizza 4 Fromages", category: "Pizzas", qty: 2, unitPrice: 1700, options: [] }, { name: "Tiramisu", category: "Desserts", qty: 2, unitPrice: 750, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "17:22", label: "Commande reçue" }, { status: "preparing", at: "17:25", label: "Acceptée · 20 min" }, { status: "done", at: "17:58", label: "Livrée" }] },
  { id: "CMD-4804", customer: "Auxence Thomas", phone: "75.88.21", type: "pickup", total: 1100, loyalty: "diamond", status: "refused", date: "03/04", createdAt: "16:40",
    items: [{ name: "Wrap Poulet", category: "Wraps", qty: 1, unitPrice: 1100, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "16:40", label: "Commande reçue" }, { status: "refused", at: "16:42", label: "Refusée" }] },
  { id: "CMD-4803", customer: "Cyriaque Thomas", phone: "74.55.67", type: "delivery", total: 3350, status: "done", date: "03/04", createdAt: "15:15", scheduled: "15:45",
    orderedAt: "15:15", acceptedAt: "15:17", readyAt: "15:31", deliveredAt: "15:43",
    items: [{ name: "Burger Bacon", category: "Burgers", qty: 1, unitPrice: 1200, options: [] }, { name: "Wrap Saumon", category: "Wraps", qty: 1, unitPrice: 1350, options: [] }, { name: "Fondant Chocolat", category: "Desserts", qty: 1, unitPrice: 800, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "15:15", label: "Commande reçue" }, { status: "preparing", at: "15:17", label: "Acceptée · 15 min" }, { status: "done", at: "15:43", label: "Livrée" }] },
  { id: "CMD-4802", customer: "Élodie Perrin", phone: "84.11.77", type: "pickup", total: 1900, status: "done", date: "03/04", createdAt: "13:30",
    orderedAt: "13:30", acceptedAt: "13:31", readyAt: "13:40", deliveredAt: "13:40",
    items: [{ name: "Wrap Saumon", category: "Wraps", qty: 1, unitPrice: 1350, options: [] }, { name: "Onion Rings", category: "Accompagnements", qty: 1, unitPrice: 550, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "13:30", label: "Commande reçue" }, { status: "preparing", at: "13:31", label: "Acceptée · 10 min" }, { status: "done", at: "13:40", label: "Récupérée" }] },
  { id: "CMD-4801", customer: "Mathieu Caron", phone: "85.66.22", type: "delivery", total: 6100, status: "done", date: "03/04", createdAt: "12:10", rating: 4, scheduled: "12:45",
    orderedAt: "12:10", acceptedAt: "12:13", readyAt: "12:42", deliveredAt: "12:55",
    items: [{ name: "Burger Classic", category: "Burgers", qty: 3, unitPrice: 950, options: [] }, { name: "Frites maison", category: "Accompagnements", qty: 3, unitPrice: 450, options: [] }, { name: "Onion Rings", category: "Accompagnements", qty: 2, unitPrice: 550, options: [] }],
    note: "Grosse commande, merci !", statusHistory: [{ status: "pending", at: "12:10", label: "Commande reçue" }, { status: "preparing", at: "12:13", label: "Acceptée · 30 min" }, { status: "done", at: "12:55", label: "Livrée" }] },
  { id: "CMD-4800", customer: "Claire Fontaine", phone: "86.33.44", loyalty: "new", type: "pickup", total: 2400, status: "done", date: "01/04", createdAt: "19:00", rating: 5,
    orderedAt: "19:00", acceptedAt: "19:02", readyAt: "19:16", deliveredAt: "19:16",
    items: [{ name: "Pizza 4 Fromages", category: "Pizzas", qty: 1, unitPrice: 1700, options: [] }, { name: "Fondant Chocolat", category: "Desserts", qty: 1, unitPrice: 800, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "19:00", label: "Commande reçue" }, { status: "preparing", at: "19:02", label: "Acceptée · 15 min" }, { status: "done", at: "19:16", label: "Récupérée" }] },
  { id: "CMD-4799", customer: "Julien Morel", phone: "87.55.88", loyalty: "new", type: "delivery", total: 1650, status: "done", date: "01/04", createdAt: "18:12",
    orderedAt: "18:12", acceptedAt: "18:14", readyAt: "18:23", deliveredAt: "18:35",
    items: [{ name: "Wrap Poulet", category: "Wraps", qty: 1, unitPrice: 1100, options: [] }, { name: "Onion Rings", category: "Accompagnements", qty: 1, unitPrice: 550, options: [] }],
    note: "", statusHistory: [{ status: "pending", at: "18:12", label: "Commande reçue" }, { status: "preparing", at: "18:14", label: "Acceptée · 10 min" }, { status: "done", at: "18:35", label: "Livrée" }] },
];

// ─── STYLES ────────────────────────────────────────────────
const LIGHT = {
  primary: "#15A7A7",
  primaryLight: "#E8F7F7",
  red: "#F95D62",
  redLight: "#FEF0F0",
  yellow: "#FFD51E",
  yellowLight: "#FFFBEB",
  white: "#FFFFFF",
  bg: "#F6F8FA",
  title: "#444D59",
  text: "#4F6787",
  textLight: "#94A3B8",
  border: "#E8ECF1",
  green: "#22C55E",
  greenLight: "#F0FDF4",
  cardShadow: "0 1px 4px rgba(0,0,0,.04)",
  isDark: false,
};

const DARK = {
  primary: "#1DBFBF",
  primaryLight: "#172E2E",
  red: "#F87171",
  redLight: "#2D1F1F",
  yellow: "#FACC15",
  yellowLight: "#2D2A14",
  white: "#1A2030",
  bg: "#111720",
  title: "#E2E8F0",
  text: "#94A3B8",
  textLight: "#64748B",
  border: "#2A3344",
  green: "#34D399",
  greenLight: "#162520",
  cardShadow: "0 1px 4px rgba(0,0,0,.2)",
  isDark: true,
};

let C = LIGHT;

// ─── COMPONENTS ────────────────────────────────────────────

// Mock schedule
const SCHEDULE = { openHour: 7, closeHour: 21 };

function useSchedule() {
  const now = new Date();
  const h = now.getHours() + now.getMinutes() / 60;
  const isOpen = h >= SCHEDULE.openHour && h < SCHEDULE.closeHour;
  const remainMin = isOpen ? Math.max(0, Math.round((SCHEDULE.closeHour - h) * 60)) : 0;
  const totalWindow = SCHEDULE.closeHour - SCHEDULE.openHour;
  const elapsed = Math.max(0, Math.min(h - SCHEDULE.openHour, totalWindow));
  const progress = isOpen ? Math.min(elapsed / totalWindow, 1) : 1;
  return { isOpen, remainMin, progress };
}

function Clock() {
  const [time, setTime] = useState(new Date());
  useEffect(() => {
    const t = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(t);
  }, []);

  const { isOpen, remainMin, progress } = useSchedule();
  const remainH = Math.floor(remainMin / 60);
  const remainM = remainMin % 60;
  const remainText = remainH > 0 ? `${remainH}h${String(remainM).padStart(2, "0")}` : `${remainM} min`;

  // SVG ring
  const r = 12, circ = 2 * Math.PI * r;

  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
      {/* Current time */}
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={C.textLight} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
        </svg>
        <span style={{ fontFamily: "'Inter', sans-serif", fontSize: 22, fontWeight: 700, color: C.title, letterSpacing: 1.5 }}>
          {time.toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" })}
        </span>
      </div>

      {isOpen ? (
        /* Closing countdown ring */
        <div style={{ display: "flex", alignItems: "center", gap: 8, cursor: "default" }}>
          <svg width="30" height="30" viewBox="0 0 30 30" style={{ transform: "rotate(-90deg)" }}>
            <circle cx="15" cy="15" r={r} fill="none" stroke={C.border} strokeWidth="3" />
            <circle cx="15" cy="15" r={r} fill="none"
              stroke={C.textLight}
              strokeWidth="3" strokeLinecap="round"
              strokeDasharray={circ} strokeDashoffset={circ * progress}
              style={{ transition: "stroke-dashoffset 1s linear" }}
            />
          </svg>
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.2 }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: C.title }}>
              {remainText}
            </span>
            <span style={{ fontSize: 10, color: C.textLight }}>
              Fermeture - {SCHEDULE.closeHour}:00
            </span>
          </div>
        </div>
      ) : (
        /* Closed — next opening */
        <div style={{ display: "flex", alignItems: "center", gap: 6, cursor: "default" }}>
          <span style={{ fontSize: 12, fontWeight: 600, color: C.textLight }}>
            Réouverture - {String(SCHEDULE.openHour).padStart(2, "0")}:00
          </span>
        </div>
      )}
    </div>
  );
}

function Toggle({ on, onChange, label, colorOn = C.green, colorOff = C.red }) {
  return (
    <div
      onClick={onChange}
      style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", userSelect: "none" }}
    >
      <div
        style={{
          width: 48, height: 26, borderRadius: 13,
          background: on ? colorOn : colorOff,
          position: "relative", transition: "background .25s ease",
          boxShadow: `inset 0 1px 3px rgba(0,0,0,.15)`,
        }}
      >
        <div
          style={{
            width: 22, height: 22, borderRadius: 11,
            background: C.white, position: "absolute",
            top: 2, left: on ? 24 : 2,
            transition: "left .25s ease",
            boxShadow: "0 1px 4px rgba(0,0,0,.18)",
          }}
        />
      </div>
      <span style={{ fontSize: 12, fontWeight: 500, color: on ? colorOn : C.red, whiteSpace: "nowrap" }}>
        {label}
      </span>
    </div>
  );
}

function Badge({ type }) {
  if (type === "delivery") return null;
  return (
    <span
      style={{
        display: "inline-flex", alignItems: "center", gap: 5,
        fontSize: 11, fontWeight: 600, padding: "4px 10px",
        borderRadius: 20, background: C.yellowLight, color: "#D97706",
      }}
    >
      <span style={{ fontSize: 13 }}>🛍️</span> À emporter
    </span>
  );
}

function StatusBadge({ status }) {
  const map = {
    pending: { label: "Nouvelle", bg: C.yellow, color: "#444D59" },
    preparing: { label: "En préparation", bg: C.primary, color: C.white },
    ready: { label: "Prête", bg: C.green, color: C.white },
  };
  const s = map[status];
  return (
    <span
      style={{
        display: "inline-flex", alignItems: "center", gap: 4,
        fontSize: 11, fontWeight: 700, padding: "4px 12px",
        borderRadius: 20, background: s.bg, color: s.color,
        textTransform: "uppercase", letterSpacing: 0.5,
      }}
    >
      {status === "pending" && <span style={{ display: "inline-block", width: 6, height: 6, borderRadius: 3, background: "#444D59", animation: "pulse 1.5s infinite" }} />}
      {s.label}
    </span>
  );
}

function formatXPF(v) {
  return v.toLocaleString("fr-FR") + " Cfp";
}

function LoyaltyBadge({ loyalty }) {
  const [hover, setHover] = useState(false);
  if (!loyalty) return null;
  const isDiamond = loyalty === "diamond";
  const label = isDiamond ? "💎" : "🆕";
  const tip = isDiamond ? "Client fidèle" : "Nouveau client";
  return (
    <span
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "relative",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        fontSize: hover ? 22 : 18, lineHeight: 1,
        cursor: "default",
        transition: "font-size .12s ease",
      }}
    >
      {label}
      {hover && (
        <div style={{
          position: "absolute", top: "100%", left: "50%", transform: "translateX(-50%)",
          marginTop: 4,
          background: C.isDark ? C.border : C.title,
          color: "#FFF",
          padding: "4px 10px", borderRadius: 6,
          fontSize: 10, fontWeight: 600, whiteSpace: "nowrap",
          boxShadow: "0 2px 8px rgba(0,0,0,.25)",
          pointerEvents: "none", zIndex: 10,
        }}>
          {tip}
        </div>
      )}
    </span>
  );
}

function ScheduledBadge({ time }) {
  if (!time) return null;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      fontSize: 10, fontWeight: 700, padding: "3px 8px",
      borderRadius: 8, background: C.bg, border: `1px solid ${C.border}`,
      color: C.text,
    }}>
      🕐 Planifiée {time}
    </span>
  );
}

function timeDiffMin(a, b) {
  const [ah, am] = a.split(":").map(Number);
  const [bh, bm] = b.split(":").map(Number);
  return (bh * 60 + bm) - (ah * 60 + am);
}

function DriverStatus({ driver }) {
  if (!driver) return null;
  const statusMap = {
    en_route: { label: `${driver.name} · en route`, color: C.primary, bg: C.primaryLight },
    late: { label: `${driver.name} · en retard de ${driver.delay} min`, color: C.red, bg: C.redLight },
    arrived: { label: `${driver.name} · sur place`, color: C.green, bg: C.greenLight },
  };
  const s = statusMap[driver.status] || statusMap.en_route;
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 8,
      background: s.bg, borderRadius: 10, padding: "8px 14px",
      border: driver.status === "late" ? `1px solid ${C.red}40` : "none",
    }}>
      <span style={{ fontSize: 14 }}>🛵</span>
      <span style={{ fontSize: 12, fontWeight: 600, color: s.color }}>{s.label}</span>
    </div>
  );
}

function RefuseModal({ order, products, onClose, onRefuse, onToggleProduct }) {
  const [reason, setReason] = useState(null);
  const [customReason, setCustomReason] = useState("");
  const [showRupture, setShowRupture] = useState(false);
  const [ruptureItems, setRuptureItems] = useState({});
  const [autoDisable, setAutoDisable] = useState(true);

  const reasons = [
    { id: "overload", label: "Boutique surchargée" },
    { id: "rupture", label: "Article en rupture" },
    { id: "technical", label: "Problème technique" },
    { id: "other", label: "Autre" },
  ];

  // Get products matching order items
  const orderProducts = products.filter(p =>
    order.items.some(item => item.name === p.name)
  );

  const toggleRupture = (id) => {
    setRuptureItems(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const handleConfirmRupture = () => {
    if (autoDisable) {
      Object.keys(ruptureItems).forEach(id => {
        if (ruptureItems[id]) onToggleProduct(Number(id));
      });
    }
    onRefuse(order.id);
  };

  if (showRupture) {
    return (
      <div style={{
        position: "fixed", inset: 0, background: "rgba(0,0,0,.5)",
        display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100,
      }} onClick={onClose}>
        <div onClick={e => e.stopPropagation()} style={{
          background: C.white, borderRadius: 20, padding: "28px", width: 480, maxHeight: "80vh",
          overflowY: "auto", boxShadow: "0 20px 60px rgba(0,0,0,.2)",
        }}>
          <div style={{ fontSize: 18, fontWeight: 800, color: C.title, marginBottom: 6 }}>Articles en rupture</div>
          <div style={{ fontSize: 12, color: C.textLight, marginBottom: 20 }}>Sélectionnez les articles indisponibles</div>

          {orderProducts.map(p => (
            <div key={p.id} onClick={() => toggleRupture(p.id)} style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              padding: "12px 16px", borderRadius: 12, cursor: "pointer",
              border: ruptureItems[p.id] ? `2px solid ${C.red}` : `1px solid ${C.border}`,
              background: ruptureItems[p.id] ? C.redLight : C.white,
              marginBottom: 8, transition: "all .15s",
            }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, color: C.title }}>{p.name}</div>
                <div style={{ fontSize: 11, color: C.textLight }}>{p.category} · {formatXPF(p.price)}</div>
              </div>
              <div style={{
                width: 22, height: 22, borderRadius: 6,
                border: ruptureItems[p.id] ? "none" : `2px solid ${C.border}`,
                background: ruptureItems[p.id] ? C.red : "transparent",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                {ruptureItems[p.id] && (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#FFF" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                )}
              </div>
            </div>
          ))}

          {/* Auto-disable toggle */}
          <div onClick={() => setAutoDisable(!autoDisable)} style={{
            display: "flex", alignItems: "center", gap: 10, padding: "14px 0",
            cursor: "pointer", userSelect: "none", marginTop: 8,
            borderTop: `1px solid ${C.border}`,
          }}>
            <div style={{
              width: 20, height: 20, borderRadius: 5, flexShrink: 0,
              border: autoDisable ? "none" : `2px solid ${C.border}`,
              background: autoDisable ? C.primary : "transparent",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              {autoDisable && (
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#FFF" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
              )}
            </div>
            <span style={{ fontSize: 13, fontWeight: 500, color: C.text }}>
              Désactiver automatiquement ces articles du catalogue
            </span>
          </div>

          <div style={{ display: "flex", gap: 12, marginTop: 16 }}>
            <button onClick={onClose} style={{
              flex: 1, padding: "14px", borderRadius: 12, border: `1px solid ${C.border}`,
              background: C.white, color: C.text, fontSize: 14, fontWeight: 600,
              cursor: "pointer", fontFamily: "'Inter', sans-serif",
            }}>Annuler</button>
            <button onClick={handleConfirmRupture} style={{
              flex: 1, padding: "14px", borderRadius: 12, border: "none",
              background: C.red, color: "#FFF", fontSize: 14, fontWeight: 700,
              cursor: "pointer", fontFamily: "'Inter', sans-serif",
              opacity: Object.values(ruptureItems).some(v => v) ? 1 : 0.4,
              pointerEvents: Object.values(ruptureItems).some(v => v) ? "auto" : "none",
            }}>Refuser la commande</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{
      position: "fixed", inset: 0, background: "rgba(0,0,0,.5)",
      display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: C.white, borderRadius: 20, padding: "28px", width: 400,
        boxShadow: "0 20px 60px rgba(0,0,0,.2)",
      }}>
        <div style={{ fontSize: 18, fontWeight: 800, color: C.title, marginBottom: 6 }}>Refuser la commande</div>
        <div style={{ fontSize: 12, color: C.textLight, marginBottom: 20 }}>{order.id} · {order.customer}</div>

        {reasons.map(r => (
          <div key={r.id} onClick={() => setReason(r.id)} style={{
            padding: "14px 16px", borderRadius: 12, cursor: "pointer",
            border: reason === r.id ? `2px solid ${C.red}` : `1px solid ${C.border}`,
            background: reason === r.id ? C.redLight : C.white,
            marginBottom: 8, fontSize: 14, fontWeight: 500, color: C.title,
            transition: "all .15s",
          }}>
            {r.label}
          </div>
        ))}

        {reason === "other" && (
          <input
            type="text" placeholder="Motif…" value={customReason}
            onChange={e => setCustomReason(e.target.value)}
            style={{
              width: "100%", padding: "12px 16px", borderRadius: 12,
              border: `1px solid ${C.border}`, fontSize: 14, color: C.title,
              fontFamily: "'Inter', sans-serif", marginBottom: 8, background: C.bg,
              outline: "none",
            }}
          />
        )}

        <div style={{ display: "flex", gap: 12, marginTop: 16 }}>
          <button onClick={onClose} style={{
            flex: 1, padding: "14px", borderRadius: 12, border: `1px solid ${C.border}`,
            background: C.white, color: C.text, fontSize: 14, fontWeight: 600,
            cursor: "pointer", fontFamily: "'Inter', sans-serif",
          }}>Annuler</button>
          <button onClick={() => {
            if (reason === "rupture") { setShowRupture(true); return; }
            onRefuse(order.id);
          }} style={{
            flex: 1, padding: "14px", borderRadius: 12, border: "none",
            background: C.red, color: "#FFF", fontSize: 14, fontWeight: 700,
            cursor: "pointer", fontFamily: "'Inter', sans-serif",
            opacity: reason ? 1 : 0.4,
            pointerEvents: reason ? "auto" : "none",
          }}>
            {reason === "rupture" ? "Suivant →" : "Confirmer le refus"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── SIDEBAR ───────────────────────────────────────────────

const NAV_ITEMS = [
  { id: "orders", label: "Commandes", icon: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/><path d="M9 14l2 2 4-4"/></svg>
  )},
  { id: "history", label: "Historique", icon: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
  )},
  { id: "products", label: "Produits", icon: (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 01-8 0"/></svg>
  )},
];

function Sidebar({ active, onNav, badges = {} }) {
  return (
    <nav className="sidebar">
      {/* Logo - hidden on mobile */}
      <div className="sidebar-logo"
        style={{
          width: 42, height: 42, borderRadius: 12,
          background: `linear-gradient(135deg, ${C.primary}, #0E8585)`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: C.white, fontWeight: 800, fontSize: 16,
          fontFamily: "'Inter', sans-serif",
          boxShadow: "0 2px 8px rgba(21,167,167,.3)",
        }}
      >
        MH
      </div>

      {NAV_ITEMS.map((item) => {
        const isActive = active === item.id;
        const badge = badges[item.id];
        return (
          <div
            key={item.id}
            onClick={() => onNav(item.id)}
            className="sidebar-item"
            style={{
              borderRadius: 14,
              display: "flex", flexDirection: "column",
              alignItems: "center", justifyContent: "center",
              gap: 3, cursor: "pointer",
              background: isActive ? C.primaryLight : "transparent",
              color: isActive ? C.primary : C.textLight,
              transition: "all .2s ease",
              position: "relative",
            }}
          >
            {isActive && (
              <div className="sidebar-indicator"
                style={{
                  position: "absolute",
                  width: 3, height: 24, borderRadius: 2, background: C.primary,
                }}
              />
            )}
            {badge > 0 && (
              <div style={{
                position: "absolute", top: 2, right: 2,
                minWidth: 18, height: 18, borderRadius: 9,
                background: C.red, color: C.white,
                fontSize: 10, fontWeight: 700,
                display: "flex", alignItems: "center", justifyContent: "center",
                padding: "0 4px",
                border: `2px solid ${C.white}`,
                lineHeight: 1,
              }}>
                {badge}
              </div>
            )}
            {item.icon}
            <span style={{ fontSize: 9, fontWeight: 600, letterSpacing: 0.3 }}>{item.label}</span>
          </div>
        );
      })}
    </nav>
  );
}

// ─── HEADER ────────────────────────────────────────────────

function Header({ storeOpen, setStoreOpen, closedToday, setClosedToday, themeMode, setThemeMode }) {
  const { isOpen: scheduleOpen } = useSchedule();
  const isAccepting = storeOpen && !closedToday && scheduleOpen;

  let statusText, statusColor;
  if (!scheduleOpen) {
    statusText = "Fermé";
    statusColor = C.red;
  } else if (closedToday) {
    statusText = "Fermé pour la journée";
    statusColor = C.red;
  } else if (!storeOpen) {
    statusText = "Boutique désactivée";
    statusColor = C.red;
  } else {
    statusText = "Accepte les commandes";
    statusColor = C.green;
  }

  const themeIcons = { auto: "◐", light: "☀️", dark: "🌙" };
  const themeLabels = { auto: "Auto", light: "Clair", dark: "Sombre" };
  const nextTheme = { auto: "light", light: "dark", dark: "auto" };
  return (
    <div className="header"
      style={{
        background: C.white,
        borderBottom: `1px solid ${C.border}`,
        display: "flex", alignItems: "center",
        justifyContent: "space-between",
      }}
    >
      {/* Left : Store name + status */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, flexShrink: 0 }}>
        <div
          style={{
            width: 10, height: 10, borderRadius: 5, flexShrink: 0,
            background: isAccepting ? C.green : C.red,
            boxShadow: isAccepting ? "0 0 8px rgba(34,197,94,.5)" : "0 0 8px rgba(249,93,98,.5)",
            transition: "all .3s",
          }}
        />
        <div>
          <div className="header-title" style={{ fontWeight: 700, color: C.title, fontFamily: "'Inter', sans-serif" }}>
            Need Eat
          </div>
          <div className="header-status" style={{ color: statusColor, fontWeight: 500 }}>
            {statusText}
          </div>
        </div>
      </div>

      {/* Center : Clock */}
      <Clock />

      {/* Right : Toggles + Theme */}
      <div className="header-controls" style={{ display: "flex", alignItems: "center", gap: 20 }}>
        <Toggle
          on={storeOpen}
          onChange={() => setStoreOpen(!storeOpen)}
          label={storeOpen ? "Boutique active" : "Boutique inactive"}
          colorOn={C.green}
          colorOff={C.red}
        />
        <div className="header-sep" style={{ width: 1, height: 28, background: C.border }} />
        <Toggle
          on={!closedToday}
          onChange={() => setClosedToday(!closedToday)}
          label={closedToday ? "Fermé aujourd'hui" : "Ouvert"}
          colorOn={C.green}
          colorOff={C.red}
        />
        <div className="header-sep" style={{ width: 1, height: 28, background: C.border }} />
        {/* Theme toggle */}
        <div
          onClick={() => setThemeMode(nextTheme[themeMode])}
          style={{
            display: "flex", alignItems: "center", gap: 6,
            cursor: "pointer", userSelect: "none",
            padding: "5px 12px", borderRadius: 10,
            background: C.bg, border: `1px solid ${C.border}`,
            transition: "all .2s",
          }}
        >
          <span style={{ fontSize: 14 }}>{themeIcons[themeMode]}</span>
          <span style={{ fontSize: 11, fontWeight: 600, color: C.textLight }}>{themeLabels[themeMode]}</span>
        </div>
      </div>
    </div>
  );
}

// ─── VIEW : ORDERS LIST ────────────────────────────────────

function PrepTimerInline({ minutes }) {
  const isLate = minutes <= 0;
  const color = isLate ? C.red : C.green;
  const bgColor = isLate ? C.redLight : C.greenLight;
  const display = isLate ? `+${Math.abs(minutes)}` : minutes;
  return (
    <div className={isLate ? "timer-blink" : ""} style={{
      display: "inline-flex", alignItems: "center", gap: 5,
      background: bgColor, borderRadius: 10, padding: "4px 10px",
    }}>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/>
      </svg>
      <span style={{ fontSize: 18, fontWeight: 900, color, fontFamily: "'Inter', sans-serif", lineHeight: 1 }}>
        {display}
      </span>
      <span style={{ fontSize: 11, fontWeight: 600, color, opacity: 0.8 }}>min</span>
    </div>
  );
}

function WaitTimer({ since }) {
  const [elapsed, setElapsed] = useState(Math.floor((Date.now() - since) / 1000));
  useEffect(() => {
    const t = setInterval(() => setElapsed(Math.floor((Date.now() - since) / 1000)), 1000);
    return () => clearInterval(t);
  }, [since]);
  const isLate = elapsed > 30;
  const mins = Math.floor(elapsed / 60);
  const secs = elapsed % 60;
  const display = mins > 0 ? `${mins}m${String(secs).padStart(2, "0")}s` : `${secs}s`;
  return (
    <span style={{
      fontSize: 13, fontWeight: 700,
      color: isLate ? C.red : C.textLight,
    }}>
      {display}
    </span>
  );
}

function OrderCard({ order, onClick, onReady, isSelected }) {
  const isPending = order.status === "pending";
  const isPreparing = order.status === "preparing";
  const isReady = order.status === "ready";
  const showReadyBtn = isPreparing && order.acceptedAt && (Date.now() - order.acceptedAt > 120000);

  const borderColor = isPending ? C.yellow : isPreparing ? C.primary : isReady ? C.green : C.border;
  const borderWidth = isPending || isPreparing || isReady ? 2 : 1;
  const shadowDefault = isSelected
    ? `0 0 0 3px ${C.primary}40, 0 4px 16px rgba(0,0,0,.1)`
    : isPending ? "0 2px 12px rgba(255,213,30,.15)" : isPreparing ? "0 2px 12px rgba(21,167,167,.12)" : isReady ? "0 2px 12px rgba(34,197,94,.12)" : "0 1px 4px rgba(0,0,0,.04)";
  const topBarColor = isPending ? C.yellow : isPreparing ? C.primary : isReady ? C.green : null;

  return (
    <div style={{
      position: "relative", display: "flex", flexDirection: "column", height: "100%",
      transform: isSelected ? "scale(1.02)" : "scale(1)",
      transition: "transform .2s ease",
      zIndex: isSelected ? 1 : 0,
    }}>
      <div
        onClick={onClick}
        className={isPending ? "card-pending" : ""}
        style={{
          background: isSelected ? C.primaryLight : C.white,
          borderRadius: showReadyBtn ? "16px 16px 0 0" : 16,
          padding: "18px 22px",
          cursor: "pointer",
          border: `${borderWidth}px solid ${borderColor}`,
          transition: "all .2s ease",
          position: "relative",
          overflow: "hidden",
          flex: 1,
          boxShadow: shadowDefault,
        }}
        onMouseEnter={(e) => { if (!isSelected) { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 4px 16px rgba(0,0,0,.08)"; }}}
        onMouseLeave={(e) => { if (!isSelected) { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = shadowDefault; }}}
      >
        {topBarColor && (
          <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 3, background: topBarColor }} />
        )}

        {/* Row 1: ID + Status + Loyalty + Wait time */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 15, fontWeight: 700, color: C.title }}>{order.id}</span>
            <StatusBadge status={order.status} />
            <LoyaltyBadge loyalty={order.loyalty} />
            <ScheduledBadge time={order.scheduled} />
          </div>
          {isPending && order.pendingSince && (
            <WaitTimer since={order.pendingSince} />
          )}
        </div>

        {/* Row 2: Customer + Timer + Type */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: (isPreparing || isReady) ? 6 : 10 }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: C.text }}>{order.customer}</span>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            {isPreparing && order.prepTimeLeft != null && (
              <PrepTimerInline minutes={order.prepTimeLeft} />
            )}
            <Badge type={order.type} />
          </div>
        </div>

        {/* Driver / status line (preparing + ready) */}
        {(isPreparing || isReady) && (
          <div style={{ display: "flex", alignItems: "center", gap: 5, marginBottom: 8, minHeight: 18 }}>
            {order.driver ? (
              <>
                <span style={{ fontSize: 12 }}>🛵</span>
                <span style={{
                  fontSize: 11, fontWeight: 600,
                  color: order.driver.status === "late" ? C.red : order.driver.status === "arrived" ? C.green : C.primary,
                }}>
                  {order.driver.name} · {order.driver.status === "en_route" ? "en route" : order.driver.status === "late" ? `en retard de ${order.driver.delay} min` : "sur place"}
                </span>
              </>
            ) : (
              isReady && order.type === "pickup" ? (
                <span style={{ fontSize: 11, fontWeight: 600, color: C.green }}>🛍️ En attente du client</span>
              ) : (
                <span style={{ fontSize: 11, color: C.textLight }}>🛵 En attente de livreur</span>
              )
            )}
          </div>
        )}

        {/* Row 3: Items + Total */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ fontSize: 12, fontWeight: order.items.length > 1 ? 700 : 400, color: order.items.length > 1 ? "#D97706" : C.textLight }}>
            {order.items.length} article{order.items.length > 1 ? "s" : ""}
          </span>
          <span style={{ fontSize: 18, fontWeight: 800, color: C.primary }}>
            {formatXPF(order.total)}
          </span>
        </div>
      </div>
      {/* Quick "Prête" button for preparing orders — only after 2min */}
      {showReadyBtn && (
        <button onClick={(e) => { e.stopPropagation(); onReady(order.id); }} style={{
          width: "100%", padding: "10px", border: "none",
          borderRadius: "0 0 16px 16px",
          background: C.green, color: C.white,
          fontSize: 13, fontWeight: 700, cursor: "pointer",
          fontFamily: "'Inter', sans-serif",
          boxShadow: "0 2px 8px rgba(34,197,94,.25)",
          transition: "all .15s",
        }}>
          Prête ✓
        </button>
      )}
    </div>
  );
}

function OrdersList({ orders, onSelect, onReady, viewMode, setViewMode, selectedId }) {
  const pending = orders.filter((o) => o.status === "pending");
  const inProgress = orders.filter((o) => o.status === "preparing");
  const ready = orders.filter((o) => o.status === "ready");

  const Section = ({ title, count, color, items }) => (
    <div style={{ marginBottom: 28 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: C.title, textTransform: "uppercase", letterSpacing: 1 }}>
          {title}
        </span>
        <span
          style={{
            fontSize: 12, fontWeight: 700, color: C.white,
            background: color, borderRadius: 10,
            padding: "2px 10px", minWidth: 22, textAlign: "center",
          }}
        >
          {count}
        </span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(380px, 1fr))", gap: 12 }}>
        {items.map((o) => (
          <OrderCard key={o.id} order={o} onClick={() => onSelect(o)} onReady={onReady} isSelected={selectedId === o.id} />
        ))}
        {items.length === 0 && (
          <div style={{ padding: 20, textAlign: "center", color: C.textLight, fontSize: 13, gridColumn: "1 / -1" }}>
            Aucune commande
          </div>
        )}
      </div>
    </div>
  );

  return (
    <div style={{ padding: "24px 28px", overflowY: "auto", maxHeight: "calc(100vh - 64px)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
        <div style={{ fontSize: 22, fontWeight: 800, color: C.title }}>Commandes</div>
        {/* View mode toggle — hidden on mobile via className */}
        {setViewMode && (
          <div className="view-mode-toggle" style={{
            display: "flex", gap: 4, background: C.bg, borderRadius: 10,
            padding: 3, border: `1px solid ${C.border}`,
          }}>
            <div
              onClick={() => setViewMode("page")}
              title="Vue page"
              style={{
                width: 32, height: 28, borderRadius: 7, cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "center",
                background: viewMode === "page" ? C.primary : "transparent",
                color: viewMode === "page" ? C.white : C.textLight,
                transition: "all .15s",
              }}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
            </div>
            <div
              onClick={() => setViewMode("split")}
              title="Vue panneau"
              style={{
                width: 32, height: 28, borderRadius: 7, cursor: "pointer",
                display: "flex", alignItems: "center", justifyContent: "center",
                background: viewMode === "split" ? C.primary : "transparent",
                color: viewMode === "split" ? C.white : C.textLight,
                transition: "all .15s",
              }}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="3" x2="12" y2="21"/></svg>
            </div>
          </div>
        )}
      </div>
      <Section title="Nouvelles" count={pending.length} color={C.yellow} items={pending} />
      <Section title="En préparation" count={inProgress.length} color={C.primary} items={inProgress} />
      <Section title="En attente de récupération" count={ready.length} color={C.green} items={ready} />
    </div>
  );
}

// ─── STATUS TIMELINE ───────────────────────────────────────

function StatusTimeline({ history }) {
  if (!history || history.length === 0) return null;
  const statusColors = {
    pending: C.yellow,
    preparing: C.primary,
    done: C.green,
    refused: C.red,
  };
  return (
    <div style={{ background: C.white, borderRadius: 20, padding: "20px 28px", border: `1px solid ${C.border}` }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: C.title, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 16 }}>
        Suivi de la commande
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
        {history.map((step, i) => {
          const color = statusColors[step.status] || C.textLight;
          const isLast = i === history.length - 1;
          return (
            <div key={i} style={{ display: "flex", gap: 14, minHeight: isLast ? "auto" : 44 }}>
              {/* Dot + vertical line */}
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", width: 20, flexShrink: 0 }}>
                <div style={{
                  width: 12, height: 12, borderRadius: 6, flexShrink: 0,
                  background: color,
                  border: isLast ? `3px solid ${color}30` : "none",
                  boxSizing: "content-box",
                }} />
                {!isLast && (
                  <div style={{ width: 2, flex: 1, background: C.border, marginTop: 2, marginBottom: 2 }} />
                )}
              </div>
              {/* Label + time */}
              <div style={{ paddingBottom: isLast ? 0 : 12 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: C.title, lineHeight: 1.1 }}>
                  {step.label}
                </div>
                <div style={{ fontSize: 11, color: C.textLight, marginTop: 2 }}>
                  {step.at}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── CONTACT ICONS ─────────────────────────────────────────

function ContactIcons({ phone }) {
  return (
    <div style={{ display: "flex", gap: 8 }}>
      <div
        className="icon-pulse"
        title={`Appeler ${phone}`}
        style={{
          width: 36, height: 36, borderRadius: 10,
          background: C.green, color: C.white,
          display: "flex", alignItems: "center", justifyContent: "center",
          cursor: "pointer", transition: "all .15s",
        }}
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/>
        </svg>
      </div>
      <div
        className="icon-pulse"
        title="Chat"
        style={{
          width: 36, height: 36, borderRadius: 10,
          background: C.primary, color: C.white,
          display: "flex", alignItems: "center", justifyContent: "center",
          cursor: "pointer", transition: "all .15s",
        }}
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/>
        </svg>
      </div>
    </div>
  );
}

// ─── VIEW : ORDER DETAIL ───────────────────────────────────

function OrderDetail({ order, onBack, onUpdateStatus, products, onToggleProduct }) {
  const [prepTime, setPrepTime] = useState(null);
  const [showRefuseModal, setShowRefuseModal] = useState(false);
  const [customMode, setCustomMode] = useState(false);
  const [customValue, setCustomValue] = useState("");
  const nextStatus = { pending: "preparing", preparing: "ready", ready: "done" };
  const nextLabel = { pending: "Accepter & Préparer", preparing: "Commande prête ✓", ready: "Commande récupérée ✓" };
  const next = nextStatus[order.status];

  // Group items by category
  const grouped = order.items.reduce((acc, item) => {
    const cat = item.category || "Autres";
    if (!acc[cat]) acc[cat] = [];
    acc[cat].push(item);
    return acc;
  }, {});

  const itemTotal = (item) => {
    const optionsTotal = (item.options || []).reduce((s, o) => s + o.unitPrice * o.qty, 0);
    return item.unitPrice * item.qty + optionsTotal;
  };

  // ── Left column: info + actions ──
  const LeftCol = () => (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {/* Header card */}
      <div style={{ background: C.white, borderRadius: 20, padding: "24px 28px", border: `1px solid ${C.border}` }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
              <span style={{ fontSize: 22, fontWeight: 800, color: C.title }}>{order.id}</span>
              <StatusBadge status={order.status} />
              <LoyaltyBadge loyalty={order.loyalty} />
              <ScheduledBadge time={order.scheduled} />
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, color: C.text }}>{order.customer}</div>
            {order.phone && (
              <div style={{ fontSize: 12, color: C.textLight, marginTop: 2 }}>
                📞 {order.phone}
              </div>
            )}
          </div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              {order.phone && <ContactIcons phone={order.phone} />}
              <Badge type={order.type} />
            </div>
            <div style={{ fontSize: 12, color: C.textLight }}>Reçue à {order.createdAt}</div>
          </div>
        </div>

        {order.type === "delivery" && order.address && (
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: C.bg, borderRadius: 10, padding: "10px 14px", marginBottom: 12 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={C.primary} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
            <span style={{ fontSize: 13, color: C.text }}>{order.address}</span>
          </div>
        )}

        {order.note && (
          <div style={{ display: "flex", alignItems: "flex-start", gap: 8, background: C.yellowLight, borderRadius: 10, padding: "10px 14px", border: `1px solid ${C.yellow}40` }}>
            <span style={{ fontSize: 14 }}>💬</span>
            <span style={{ fontSize: 13, color: C.text, fontStyle: "italic" }}>{order.note}</span>
          </div>
        )}
      </div>

      {/* Prep time card */}
      {order.prepTimeLeft != null && (
        <div style={{ background: C.white, borderRadius: 20, padding: "16px 28px", border: `1px solid ${C.border}` }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: order.prepTimeLeft <= 0 ? C.red : C.title, textTransform: "uppercase", letterSpacing: 0.5 }}>
                {order.prepTimeLeft <= 0 ? "En retard de :" : "Commande récupérée dans :"}
              </span>
              <PrepTimerInline minutes={order.prepTimeLeft} />
            </div>
            <span style={{ fontSize: 13, fontWeight: 600, color: C.textLight }}>
              Pour {order.time}
            </span>
          </div>
        </div>
      )}

      {/* Driver status */}
      {order.driver && <DriverStatus driver={order.driver} />}

      {/* Actions for pending */}
      {order.status === "pending" && (
        <>
          {!order.scheduled && (
          <div style={{ background: C.white, borderRadius: 16, padding: "16px 22px", border: `1px solid ${C.border}` }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: C.title, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 12 }}>
              Ajouter du temps
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              {[5, 10, 15].map((t) => (
                <button key={t} className="btn-pop" onClick={() => { setPrepTime(prepTime === t ? null : t); setCustomMode(false); setCustomValue(""); }} style={{
                  flex: 1, padding: "12px 0", borderRadius: 12,
                  border: prepTime === t && !customMode ? `2px solid ${C.primary}` : `1px solid ${C.border}`,
                  background: prepTime === t && !customMode ? C.primaryLight : C.white,
                  color: prepTime === t && !customMode ? C.primary : C.text,
                  fontSize: 16, fontWeight: 800, cursor: "pointer",
                  fontFamily: "'Inter', sans-serif", transition: "all .15s ease",
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 4,
                }}>
                  +{t}<span style={{ fontSize: 12, fontWeight: 600, opacity: 0.7 }}>min</span>
                </button>
              ))}
              {/* Custom time */}
              {customMode ? (
                <div style={{
                  flex: 1, display: "flex", alignItems: "center", gap: 4,
                  borderRadius: 12, border: `2px solid ${C.primary}`,
                  background: C.primaryLight, padding: "0 10px",
                }}>
                  <span style={{ fontSize: 14, fontWeight: 800, color: C.primary }}>+</span>
                  <input
                    autoFocus
                    type="number" min="1" max="120"
                    value={customValue}
                    onChange={(e) => {
                      const v = e.target.value;
                      setCustomValue(v);
                      const n = parseInt(v);
                      setPrepTime(n > 0 ? n : null);
                    }}
                    onBlur={() => { if (!customValue) { setCustomMode(false); setPrepTime(null); }}}
                    style={{
                      border: "none", outline: "none", background: "transparent",
                      width: 36, fontSize: 16, fontWeight: 800, color: C.primary,
                      fontFamily: "'Inter', sans-serif", textAlign: "center",
                    }}
                  />
                  <span style={{ fontSize: 12, fontWeight: 600, color: C.primary, opacity: 0.7 }}>min</span>
                </div>
              ) : (
                <button className="btn-pop" onClick={() => { setCustomMode(true); setPrepTime(null); }} style={{
                  flex: 1, padding: "12px 0", borderRadius: 12,
                  border: `1px dashed ${C.border}`,
                  background: C.white, color: C.textLight,
                  fontSize: 13, fontWeight: 600, cursor: "pointer",
                  fontFamily: "'Inter', sans-serif", transition: "all .15s ease",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  Autre
                </button>
              )}
            </div>
          </div>
          )}
          <div style={{ display: "flex", gap: 12 }}>
            <button onClick={() => setShowRefuseModal(true)} style={{
              flex: 1, padding: "16px", borderRadius: 14,
              border: `2px solid ${C.red}`, background: C.white,
              color: C.red, fontSize: 15, fontWeight: 700,
              cursor: "pointer", fontFamily: "'Inter', sans-serif", transition: "all .2s",
            }}>Refuser</button>
            <button className="btn-wave" onClick={() => onUpdateStatus(order.id, next, prepTime)} style={{
              flex: 2, padding: "16px", borderRadius: 14, border: "none",
              background: C.primary, color: C.white, fontSize: 15, fontWeight: 700,
              cursor: "pointer", fontFamily: "'Inter', sans-serif",
              boxShadow: "0 4px 14px rgba(21,167,167,.35)", transition: "all .2s",
            }}>
              {prepTime ? `Accepter · +${prepTime} min` : "Accepter & Préparer"}
            </button>
          </div>
        </>
      )}

      {/* Action for preparing */}
      {order.status === "preparing" && next && (
        <>
          {!order.driver && (
            <div style={{ background: C.white, borderRadius: 16, padding: "16px 22px", border: `1px solid ${C.border}` }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: C.title, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 12 }}>
                Ajouter du temps
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                {[5, 10, 15].map((t) => (
                  <button key={t} className="btn-pop" onClick={() => onUpdateStatus(order.id, "preparing", t)} style={{
                    flex: 1, padding: "12px 0", borderRadius: 12,
                    border: `1px solid ${C.border}`, background: C.white,
                    color: C.text, fontSize: 16, fontWeight: 800, cursor: "pointer",
                    fontFamily: "'Inter', sans-serif", transition: "all .15s ease",
                    display: "flex", alignItems: "center", justifyContent: "center", gap: 4,
                  }}>
                    +{t}<span style={{ fontSize: 12, fontWeight: 600, opacity: 0.7 }}>min</span>
                  </button>
                ))}
              </div>
            </div>
          )}
          <button onClick={() => onUpdateStatus(order.id, next)} style={{
            width: "100%", padding: "16px", borderRadius: 14, border: "none",
            background: C.green, color: C.white, fontSize: 15, fontWeight: 700,
            cursor: "pointer", fontFamily: "'Inter', sans-serif",
            boxShadow: "0 4px 14px rgba(34,197,94,.35)", transition: "all .2s",
          }}>
            {nextLabel[order.status]}
          </button>
        </>
      )}

      {/* Action for ready */}
      {order.status === "ready" && (
        order.type === "pickup" ? (
          <button onClick={() => onUpdateStatus(order.id, next)} style={{
            width: "100%", padding: "16px", borderRadius: 14, border: "none",
            background: C.primary, color: C.white, fontSize: 15, fontWeight: 700,
            cursor: "pointer", fontFamily: "'Inter', sans-serif",
            boxShadow: "0 4px 14px rgba(21,167,167,.35)", transition: "all .2s",
          }}>
            Client a récupéré ✓
          </button>
        ) : (
          <div style={{
            padding: "12px 16px", borderRadius: 14,
            background: C.greenLight, border: `1px solid ${C.green}30`,
            fontSize: 13, fontWeight: 500, color: C.green, textAlign: "center",
          }}>
            🛵 La commande disparaîtra automatiquement à la récupération par le livreur
          </div>
        )
      )}

      {/* Timeline */}
      <StatusTimeline history={order.statusHistory} />
    </div>
  );

  // ── Right column: articles ──
  const RightCol = () => (
    <div style={{ background: C.white, borderRadius: 20, padding: "18px 22px", border: `1px solid ${C.border}` }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: C.title, marginBottom: 12, textTransform: "uppercase", letterSpacing: 0.5 }}>
        Articles
      </div>

      {Object.entries(grouped).map(([category, items], ci) => (
        <div key={category} style={{ marginBottom: ci < Object.keys(grouped).length - 1 ? 12 : 0 }}>
          <div style={{
            fontSize: 10, fontWeight: 700, color: C.primary, textTransform: "uppercase",
            letterSpacing: 0.8, marginBottom: 4, paddingBottom: 4,
            borderBottom: `1px solid ${C.primaryLight}`,
          }}>
            {category}
          </div>

          {items.map((item, i) => {
            const hasOptions = item.options && item.options.length > 0;
            const optionsPerUnit = (item.options || []).reduce((s, o) => s + o.unitPrice * (o.qty / item.qty), 0);
            const unitTotal = item.unitPrice + optionsPerUnit;

            // If qty > 1 AND has options → expand into individual lines
            if (item.qty > 1 && hasOptions) {
              return Array.from({ length: item.qty }, (_, ui) => (
                <div key={`${i}-${ui}`} style={{ padding: "5px 0", borderBottom: (ui < item.qty - 1 || i < items.length - 1) ? `1px dashed ${C.border}` : "none" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{
                      width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                      background: C.primaryLight, color: C.primary,
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontSize: 11, fontWeight: 800,
                    }}>1</span>
                    <span style={{ fontSize: 13, fontWeight: 600, color: C.title }}>{item.name}</span>
                    <span style={{ fontSize: 11, color: C.textLight, marginLeft: "auto", flexShrink: 0 }}>
                      {formatXPF(item.unitPrice)}
                    </span>
                  </div>
                  <div style={{ marginLeft: 30, marginTop: 2 }}>
                    {item.options.map((opt, oi) => {
                      const perUnit = Math.round(opt.qty / item.qty);
                      return (
                        <div key={oi} style={{ display: "flex", alignItems: "center", gap: 4, padding: "1px 0" }}>
                          <span style={{ fontSize: 11, color: C.textLight }}>
                            {perUnit > 1 && <span style={{ fontWeight: 600, color: C.text, marginRight: 3 }}>×{perUnit}</span>}
                            {opt.name}
                          </span>
                          {opt.unitPrice > 0 && (
                            <span style={{ fontSize: 11, fontWeight: 600, color: C.text, marginLeft: "auto", flexShrink: 0 }}>
                              +{formatXPF(opt.unitPrice * perUnit)}
                            </span>
                          )}
                        </div>
                      );
                    })}
                  </div>
                  {optionsPerUnit > 0 && (
                    <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 2 }}>
                      <span style={{ fontSize: 12, fontWeight: 700, color: C.title }}>{formatXPF(unitTotal)}</span>
                    </div>
                  )}
                </div>
              ));
            }

            // Normal rendering (qty == 1, or qty > 1 without options)
            const optionsTotal = (item.options || []).reduce((s, o) => s + o.unitPrice * o.qty, 0);
            const lineTotal = item.unitPrice * item.qty + optionsTotal;
            const showLineTotal = item.qty > 1 || optionsTotal > 0;
            return (
              <div key={i} style={{ padding: "5px 0", borderBottom: i < items.length - 1 ? `1px dashed ${C.border}` : "none" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{
                    width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                    background: item.qty > 1 ? C.yellowLight : C.primaryLight,
                    color: item.qty > 1 ? "#D97706" : C.primary,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontSize: 11, fontWeight: 800,
                  }}>{item.qty}</span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: C.title }}>{item.name}</span>
                  <span style={{ fontSize: 11, color: C.textLight, marginLeft: "auto", flexShrink: 0 }}>
                    {formatXPF(item.unitPrice)}
                  </span>
                </div>

                {/* Options (only for qty == 1 items with options) */}
                {hasOptions && (
                  <div style={{ marginLeft: 30, marginTop: 2 }}>
                    {item.options.map((opt, oi) => (
                      <div key={oi} style={{ display: "flex", alignItems: "center", gap: 4, padding: "1px 0" }}>
                        <span style={{ fontSize: 11, color: C.textLight }}>
                          {opt.qty > 1 && <span style={{ fontWeight: 600, color: C.text, marginRight: 3 }}>×{opt.qty}</span>}
                          {opt.name}
                        </span>
                        {opt.unitPrice > 0 && (
                          <span style={{ fontSize: 11, fontWeight: 600, color: C.text, marginLeft: "auto", flexShrink: 0 }}>
                            +{formatXPF(opt.unitPrice * opt.qty)}
                          </span>
                        )}
                      </div>
                    ))}
                  </div>
                )}

                {/* Total line when paid options or qty > 1 */}
                {showLineTotal && (
                  <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 2 }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: C.title }}>{formatXPF(lineTotal)}</span>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      ))}

      {/* Grand total */}
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        marginTop: 12, paddingTop: 10, borderTop: `2px solid ${C.title}`,
      }}>
        <span style={{ fontSize: 15, fontWeight: 800, color: C.title }}>Total</span>
        <span style={{ fontSize: 20, fontWeight: 800, color: C.primary }}>{formatXPF(order.total)}</span>
      </div>
    </div>
  );

  return (
    <div style={{ padding: "24px 28px", overflowY: "auto", maxHeight: "calc(100vh - 64px)" }}>
      {/* Back button */}
      <div onClick={onBack} style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        cursor: "pointer", color: C.text, fontSize: 13, fontWeight: 500,
        marginBottom: 20, padding: "6px 0",
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></svg>
        Retour aux commandes
      </div>

      {/* 2-column layout on wide screens, 1 column on small */}
      <div className="detail-grid" style={{
        display: "grid",
        gap: 20,
        alignItems: "start",
      }}>
        <LeftCol />
        <RightCol />
      </div>
    </div>
  );
}

// ─── VIEW : PRODUCT DEACTIVATION ───────────────────────────

function ProductManager({ products, onToggle }) {
  const [search, setSearch] = useState("");
  const [filterCat, setFilterCat] = useState("Tous");

  const categories = ["Tous", ...Array.from(new Set(products.map((p) => p.category)))];
  const filtered = products.filter((p) => {
    const matchSearch = p.name.toLowerCase().includes(search.toLowerCase());
    const matchCat = filterCat === "Tous" || p.category === filterCat;
    return matchSearch && matchCat;
  });

  const activeCount = products.filter((p) => p.active).length;
  const inactiveCount = products.filter((p) => !p.active).length;

  return (
    <div style={{ padding: "24px 28px", overflowY: "auto", maxHeight: "calc(100vh - 64px)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
        <div style={{ fontSize: 22, fontWeight: 800, color: C.title }}>Produits</div>
        <div style={{ display: "flex", gap: 12 }}>
          <span
            style={{
              fontSize: 12, fontWeight: 600, padding: "6px 14px",
              borderRadius: 20, background: C.greenLight, color: C.green,
            }}
          >
            {activeCount} actifs
          </span>
          <span
            style={{
              fontSize: 12, fontWeight: 600, padding: "6px 14px",
              borderRadius: 20, background: C.redLight, color: C.red,
            }}
          >
            {inactiveCount} désactivés
          </span>
        </div>
      </div>

      {/* Search */}
      <div
        style={{
          display: "flex", alignItems: "center", gap: 10,
          background: C.white, borderRadius: 12, padding: "0 16px",
          border: `1px solid ${C.border}`, marginBottom: 16, height: 44,
        }}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={C.textLight} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
        <input
          type="text"
          placeholder="Rechercher un produit…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          style={{
            border: "none", outline: "none", flex: 1,
            fontSize: 14, color: C.title, fontFamily: "'Inter', sans-serif",
            background: "transparent",
          }}
        />
      </div>

      {/* Category pills */}
      <div style={{ display: "flex", gap: 8, marginBottom: 20, flexWrap: "wrap" }}>
        {categories.map((cat) => (
          <button
            key={cat}
            onClick={() => setFilterCat(cat)}
            style={{
              padding: "7px 16px", borderRadius: 20,
              border: filterCat === cat ? "none" : `1px solid ${C.border}`,
              background: filterCat === cat ? C.primary : C.white,
              color: filterCat === cat ? C.white : C.text,
              fontSize: 12, fontWeight: 600, cursor: "pointer",
              fontFamily: "'Inter', sans-serif",
              transition: "all .2s",
            }}
          >
            {cat}
          </button>
        ))}
      </div>

      {/* Product list */}
      <div
        style={{
          background: C.white, borderRadius: 20,
          border: `1px solid ${C.border}`, overflow: "hidden",
        }}
      >
        {filtered.map((product, i) => (
          <div
            key={product.id}
            style={{
              display: "flex", justifyContent: "space-between", alignItems: "center",
              padding: "14px 22px",
              borderBottom: i < filtered.length - 1 ? `1px solid ${C.border}` : "none",
              opacity: product.active ? 1 : 0.55,
              transition: "opacity .25s",
            }}
          >
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: C.title }}>{product.name}</div>
              <div style={{ fontSize: 11, color: C.textLight, marginTop: 2 }}>{product.category}</div>
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, color: C.text, marginRight: 20 }}>
              {formatXPF(product.price)}
            </div>
            <Toggle
              on={product.active}
              onChange={() => onToggle(product.id)}
              label={product.active ? "Actif" : "Inactif"}
              colorOn={C.green}
              colorOff={C.red}
            />
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{ padding: 30, textAlign: "center", color: C.textLight, fontSize: 13 }}>
            Aucun produit trouvé
          </div>
        )}
      </div>
    </div>
  );
}

// ─── VIEW : HISTORY ────────────────────────────────────────

function HistoryView() {
  const [filter, setFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [expanded, setExpanded] = useState(null);

  const filtered = MOCK_HISTORY.filter((o) => {
    const matchFilter = filter === "all" || o.status === filter;
    const matchSearch = o.customer.toLowerCase().includes(search.toLowerCase()) || o.id.toLowerCase().includes(search.toLowerCase());
    return matchFilter && matchSearch;
  });

  const grouped = filtered.reduce((acc, o) => {
    if (!acc[o.date]) acc[o.date] = [];
    acc[o.date].push(o);
    return acc;
  }, {});

  const totalDone = MOCK_HISTORY.filter((o) => o.status === "done").length;
  const totalRefused = MOCK_HISTORY.filter((o) => o.status === "refused").length;
  const totalRevenue = MOCK_HISTORY.filter((o) => o.status === "done").reduce((s, o) => s + o.total, 0);

  return (
    <div style={{ padding: "24px 28px", overflowY: "auto", maxHeight: "calc(100vh - 64px)" }}>
      <div style={{ fontSize: 22, fontWeight: 800, color: C.title, marginBottom: 20 }}>Historique</div>

      {/* Stats row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 20 }}>
        <div style={{ background: C.white, borderRadius: 14, padding: "14px 18px", border: `1px solid ${C.border}` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.textLight, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 4 }}>Terminées</div>
          <div style={{ fontSize: 24, fontWeight: 800, color: C.green }}>{totalDone}</div>
        </div>
        <div style={{ background: C.white, borderRadius: 14, padding: "14px 18px", border: `1px solid ${C.border}` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.textLight, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 4 }}>Refusées</div>
          <div style={{ fontSize: 24, fontWeight: 800, color: C.red }}>{totalRefused}</div>
        </div>
        <div style={{ background: C.white, borderRadius: 14, padding: "14px 18px", border: `1px solid ${C.border}` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.textLight, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 4 }}>Chiffre d'affaires</div>
          <div style={{ fontSize: 24, fontWeight: 800, color: C.primary }}>{formatXPF(totalRevenue)}</div>
        </div>
      </div>

      {/* Search + filter */}
      <div style={{ display: "flex", gap: 12, marginBottom: 20 }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 10, flex: 1,
          background: C.white, borderRadius: 12, padding: "0 16px",
          border: `1px solid ${C.border}`, height: 42,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={C.textLight} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/></svg>
          <input
            type="text" placeholder="Rechercher…" value={search}
            onChange={(e) => setSearch(e.target.value)}
            style={{ border: "none", outline: "none", flex: 1, fontSize: 13, color: C.title, fontFamily: "'Inter', sans-serif", background: "transparent" }}
          />
        </div>
        {["all", "done", "refused"].map((f) => {
          const labels = { all: "Toutes", done: "Terminées", refused: "Refusées" };
          return (
            <button key={f} onClick={() => setFilter(f)} style={{
              padding: "0 16px", height: 42, borderRadius: 12,
              border: filter === f ? "none" : `1px solid ${C.border}`,
              background: filter === f ? C.primary : C.white,
              color: filter === f ? C.white : C.text,
              fontSize: 12, fontWeight: 600, cursor: "pointer",
              fontFamily: "'Inter', sans-serif",
            }}>
              {labels[f]}
            </button>
          );
        })}
      </div>

      {/* Grouped list */}
      {Object.entries(grouped).map(([date, items]) => {
        // Parse dd/mm and build human label
        const [dd, mm] = date.split("/").map(Number);
        const now = new Date();
        const year = now.getFullYear();
        const entryDate = new Date(year, mm - 1, dd);
        const today = new Date(year, now.getMonth(), now.getDate());
        const diffDays = Math.round((today - entryDate) / 86400000);
        const monthNames = ["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"];
        const fullDate = `${String(dd).padStart(2,"0")} ${monthNames[mm - 1]}`;
        let label;
        if (diffDays === 0) label = "Aujourd'hui";
        else if (diffDays === 1) label = "Hier";
        else if (diffDays < 7) label = `Il y a ${diffDays} jours`;
        else label = "Cette semaine";
        if (diffDays >= 7 && diffDays < 14) label = "La semaine dernière";
        else if (diffDays >= 14) label = `Il y a ${Math.floor(diffDays / 7)} semaines`;

        return (
          <div key={date} style={{ marginBottom: 24 }}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 10 }}>
              <span style={{ fontSize: 13, fontWeight: 700, color: C.title }}>
                {label}
              </span>
              <span style={{ fontSize: 11, color: C.textLight }}>
                {fullDate}
              </span>
            </div>
          <div style={{
            background: C.white, borderRadius: 16,
            border: `1px solid ${C.border}`, overflow: "hidden",
          }}>
            {items.map((order, i) => {
              const isExpanded = expanded === order.id;
              const isDone = order.status === "done";
              const prepMin = isDone && order.acceptedAt && order.readyAt ? timeDiffMin(order.acceptedAt, order.readyAt) : null;
              const delivMin = isDone && order.readyAt && order.deliveredAt && order.type === "delivery" ? timeDiffMin(order.readyAt, order.deliveredAt) : null;
              const totalMin = isDone && order.orderedAt && order.deliveredAt ? timeDiffMin(order.orderedAt, order.deliveredAt) : null;
              const schedDiff = isDone && order.scheduled && order.deliveredAt ? timeDiffMin(order.scheduled, order.deliveredAt) : null;
              const announcedPrep = isDone ? (() => { const s = (order.statusHistory || []).find(h => h.status === "preparing"); if (!s) return null; const m = s.label.match(/(\d+)\s*min/); return m ? parseInt(m[1]) : null; })() : null;
              const prepLate = prepMin !== null && announcedPrep !== null && prepMin > announcedPrep;

              const grouped2 = (order.items || []).reduce((acc, item) => {
                const cat = item.category || "Autres";
                if (!acc[cat]) acc[cat] = [];
                acc[cat].push(item);
                return acc;
              }, {});

              const timingEl = isDone ? (
                <div className="hist-timing">
                  <span className="hist-t-arrow" style={{ fontSize: 10, color: C.textLight }}>{order.orderedAt} → {order.deliveredAt}</span>
                  <span className="hist-t-prep" style={{ fontSize: 10, fontWeight: 600, color: prepLate ? C.red : C.textLight }}>
                    Prép {prepMin}min{prepLate ? ` (${announcedPrep})` : ""}
                  </span>
                  {delivMin !== null ? (
                    <span className="hist-t-deliv" style={{ fontSize: 10, fontWeight: 600, color: delivMin > 10 ? C.red : C.textLight }}>
                      Livr {delivMin}min
                    </span>
                  ) : (
                    <span className="hist-t-deliv" />
                  )}
                  <span className="hist-t-total" style={{ fontSize: 10, fontWeight: 600, color: order.scheduled ? (schedDiff !== null && Math.abs(schedDiff) > 10 ? C.red : C.textLight) : C.textLight }}>
                    {order.scheduled
                      ? (schedDiff > 0 ? `+${schedDiff}min` : `${schedDiff}min`)
                      : `Total ${totalMin}min`}
                  </span>
                </div>
              ) : null;

              return (
                <div key={order.id} style={{ borderBottom: i < items.length - 1 ? `1px solid ${C.border}` : "none" }}>
                  <div
                    className="hist-row"
                    onClick={() => setExpanded(isExpanded ? null : order.id)}
                    style={{
                      padding: "10px 20px", cursor: "pointer",
                      background: isExpanded ? C.bg : "transparent",
                      transition: "background .15s",
                    }}
                  >
                    {/* Line 1: core info */}
                    <div className="hist-line1" style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <div style={{
                        width: 26, height: 26, borderRadius: 7, flexShrink: 0,
                        background: isDone ? C.greenLight : C.redLight,
                        display: "flex", alignItems: "center", justifyContent: "center",
                      }}>
                        {isDone ? (
                          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={C.green} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                        ) : (
                          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={C.red} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                        )}
                      </div>
                      <span className="hist-id" style={{ fontSize: 12, fontWeight: 700, color: C.title, flexShrink: 0 }}>{order.id}</span>
                      <span style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 12, fontWeight: 500, color: C.text, flex: 1, minWidth: 0, overflow: "hidden" }}>
                        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{order.customer}</span>
                        <LoyaltyBadge loyalty={order.loyalty} />
                      </span>
                      {/* Timing inline on large screens */}
                      <div className="hist-timing-lg">{timingEl}</div>
                      <div className="hist-badges" style={{ display: "flex", alignItems: "center", gap: 6, flexShrink: 0 }}>
                        <ScheduledBadge time={order.scheduled} />
                        <Badge type={order.type} />
                        {order.rating && (
                          <span style={{ fontSize: 11, color: "#F59E0B", letterSpacing: -1 }}>
                            {"★".repeat(order.rating)}{"☆".repeat(5 - order.rating)}
                          </span>
                        )}
                      </div>
                      <span className="hist-total" style={{ fontSize: 13, fontWeight: 700, color: isDone ? C.title : C.red, textAlign: "right", flexShrink: 0 }}>
                        {isDone ? formatXPF(order.total) : "—"}
                      </span>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={C.textLight} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transition: "transform .2s", transform: isExpanded ? "rotate(180deg)" : "rotate(0)", flexShrink: 0 }}>
                        <polyline points="6 9 12 15 18 9"/>
                      </svg>
                    </div>

                    {/* Timing on separate line for small/medium screens */}
                    {timingEl && <div className="hist-timing-sm" style={{ marginTop: 4, marginLeft: 36 }}>{timingEl}</div>}
                  </div>

                  {/* Expanded detail */}
                  {isExpanded && (
                    <div style={{ padding: "12px 20px 16px", background: C.bg }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 12 }}>
                        {order.phone && <span style={{ fontSize: 12, color: C.textLight }}>📞 {order.phone}</span>}
                        {order.phone && <ContactIcons phone={order.phone} />}
                      </div>

                      {order.note && (
                        <div style={{ display: "flex", alignItems: "flex-start", gap: 6, background: C.yellowLight, borderRadius: 8, padding: "8px 12px", marginBottom: 12, border: `1px solid ${C.yellow}30` }}>
                          <span style={{ fontSize: 12 }}>💬</span>
                          <span style={{ fontSize: 12, color: C.text, fontStyle: "italic" }}>{order.note}</span>
                        </div>
                      )}

                      {order.items && order.items.length > 0 && (
                        <div style={{ background: C.white, borderRadius: 12, padding: "12px 16px", border: `1px solid ${C.border}`, marginBottom: 12 }}>
                          {Object.entries(grouped2).map(([cat, catItems], ci) => (
                            <div key={cat} style={{ marginBottom: ci < Object.keys(grouped2).length - 1 ? 8 : 0 }}>
                              <div style={{ fontSize: 9, fontWeight: 700, color: C.primary, textTransform: "uppercase", letterSpacing: 0.8, marginBottom: 3 }}>{cat}</div>
                              {catItems.map((item, ii) => (
                                <div key={ii} style={{ display: "flex", alignItems: "center", gap: 6, padding: "2px 0" }}>
                                  <span style={{ fontSize: 11, fontWeight: 700, color: item.qty > 1 ? "#D97706" : C.primary, width: 16, textAlign: "center" }}>{item.qty}</span>
                                  <span style={{ fontSize: 11, color: C.title, flex: 1 }}>{item.name}</span>
                                  <span style={{ fontSize: 10, color: C.textLight }}>{formatXPF(item.unitPrice * item.qty)}</span>
                                </div>
                              ))}
                            </div>
                          ))}
                          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, paddingTop: 6, borderTop: `1px solid ${C.border}` }}>
                            <span style={{ fontSize: 11, fontWeight: 700, color: C.title }}>Total</span>
                            <span style={{ fontSize: 12, fontWeight: 800, color: C.primary }}>{formatXPF(order.total)}</span>
                          </div>
                        </div>
                      )}

                      <StatusTimeline history={order.statusHistory} />
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      );
      })}

      {Object.keys(grouped).length === 0 && (
        <div style={{ padding: 40, textAlign: "center", color: C.textLight, fontSize: 14 }}>
          Aucune commande trouvée
        </div>
      )}
    </div>
  );
}

// ─── APP ───────────────────────────────────────────────────

function App() {
  const [page, setPage] = useState("orders");
  const [selectedOrder, setSelectedOrder] = useState(null);
  const [orders, setOrders] = useState(MOCK_ORDERS);
  const [products, setProducts] = useState(MOCK_PRODUCTS);
  const [storeOpen, setStoreOpen] = useState(true);
  const [closedToday, setClosedToday] = useState(false);
  const [themeMode, setThemeMode] = useState("auto");
  const [systemDark, setSystemDark] = useState(false);
  const [viewMode, setViewMode] = useState("page"); // "page" or "split"

  // Detect system dark preference
  useEffect(() => {
    const mq = window.matchMedia("(prefers-color-scheme: dark)");
    setSystemDark(mq.matches);
    const handler = (e) => setSystemDark(e.matches);
    mq.addEventListener("change", handler);
    return () => mq.removeEventListener("change", handler);
  }, []);

  // Resolve theme
  const isDark = themeMode === "dark" || (themeMode === "auto" && systemDark);
  C = isDark ? DARK : LIGHT;

  const handleUpdateStatus = (orderId, newStatus, prepTime) => {
    if (newStatus === "done") {
      setOrders((prev) => prev.filter((o) => o.id !== orderId));
      setSelectedOrder(null);
      return;
    }
    setOrders((prev) =>
      prev.map((o) => {
        if (o.id !== orderId) return o;
        const updates = { status: newStatus };
        if (newStatus === "preparing" && o.status !== "preparing") {
          // Fresh acceptance
          updates.acceptedAt = Date.now();
          if (prepTime) updates.prepTimeLeft = prepTime;
        } else if (newStatus === "preparing" && o.status === "preparing" && prepTime) {
          // Adding time to existing prep
          updates.prepTimeLeft = (o.prepTimeLeft || 0) + prepTime;
        }
        return { ...o, ...updates };
      })
    );
    setSelectedOrder((prev) => {
      if (!prev || prev.id !== orderId) return prev;
      const updates = { status: newStatus };
      if (newStatus === "preparing" && prev.status !== "preparing") {
        updates.acceptedAt = Date.now();
        if (prepTime) updates.prepTimeLeft = prepTime;
      } else if (newStatus === "preparing" && prev.status === "preparing" && prepTime) {
        updates.prepTimeLeft = (prev.prepTimeLeft || 0) + prepTime;
      }
      return { ...prev, ...updates };
    });
  };

  const handleReady = (orderId) => {
    setOrders((prev) =>
      prev.map((o) => (o.id === orderId ? { ...o, status: "ready" } : o))
    );
    if (selectedOrder && selectedOrder.id === orderId) {
      setSelectedOrder((prev) => prev ? { ...prev, status: "ready" } : null);
    }
  };

  const handleToggleProduct = (productId) => {
    setProducts((prev) =>
      prev.map((p) => (p.id === productId ? { ...p, active: !p.active } : p))
    );
  };

  const pendingCount = orders.filter((o) => o.status === "pending").length;
  const inactiveCount = products.filter((p) => !p.active).length;

  return (
    <div className="app-layout"
      style={{
        fontFamily: "'Inter', sans-serif",
        height: "100vh", overflow: "hidden", background: C.bg,
      }}
    >
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
        * { margin: 0; padding: 0; box-sizing: border-box; transition: background-color .3s ease, border-color .3s ease, color .2s ease; }
        @keyframes pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.3; }
        }
        @keyframes blink-pending {
          0%, 100% { border-color: ${C.yellow}; box-shadow: 0 0 0 0 ${C.yellow}66; background: ${C.white}; }
          50% { border-color: ${C.yellow}; box-shadow: 0 0 20px 4px ${C.yellow}80; background: ${C.yellowLight}; }
        }
        @keyframes blink-timer {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.2; transform: scale(1.05); }
        }
        .card-pending { animation: blink-pending 1.8s ease-in-out infinite; }
        .timer-blink { animation: blink-timer 0.9s ease-in-out infinite; }
        @keyframes wave-btn {
          0% { background-position: -100% 0; }
          100% { background-position: 200% 0; }
        }
        .btn-wave {
          position: relative;
          overflow: hidden;
          background: ${C.primary} !important;
        }
        .btn-wave::before {
          content: '';
          position: absolute;
          top: 0; left: 0; right: 0; bottom: 0;
          background: linear-gradient(
            105deg,
            transparent 20%,
            rgba(255,255,255,0) 30%,
            rgba(255,255,255,.25) 44%,
            rgba(180,240,240,.4) 50%,
            rgba(255,255,255,.25) 56%,
            rgba(255,255,255,0) 70%,
            transparent 80%
          );
          background-size: 200% 100%;
          animation: wave-btn 2s ease-in-out infinite;
        }
        .btn-wave:hover::before { animation-duration: 1s; }
        .btn-wave:hover { filter: brightness(1.08); }
        @keyframes icon-pulse {
          0%, 100% { transform: scale(1); }
          50% { transform: scale(1.12); }
        }
        .icon-pulse { animation: icon-pulse 2s ease-in-out infinite; }
        .icon-pulse:hover { animation-duration: 0.6s; }
        .btn-pop { transition: transform .15s ease, background .15s ease, border-color .15s ease; }
        .btn-pop:hover { background: ${C.primaryLight} !important; border-color: ${C.primary} !important; color: ${C.primary} !important; }
        .btn-pop:active { transform: scale(0.9); }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: ${C.border}; border-radius: 3px; }

        /* ── LAYOUT ── */
        .app-layout { display: flex; flex-direction: row; }
        .sidebar {
          width: 72px; min-height: 100vh; background: ${C.white};
          border-right: 1px solid ${C.border};
          display: flex; flex-direction: column; align-items: center;
          padding-top: 20px; gap: 6px; flex-shrink: 0;
        }
        .sidebar-logo { margin-bottom: 28px; }
        .sidebar-item { width: 52px; height: 52px; }
        .sidebar-indicator { left: -10px; top: 50%; transform: translateY(-50%); }
        .header { height: 64px; padding: 0 28px; }
        .header-title { font-size: 16px; }
        .header-status { font-size: 11px; }
        .header-controls { display: flex; }
        .header-sep { display: block; }

        /* ── HISTORY TIMING alignment ── */
        .hist-timing { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
        .hist-t-arrow { width: 90px; flex-shrink: 0; }
        .hist-t-prep { width: 100px; flex-shrink: 0; }
        .hist-t-deliv { width: 80px; flex-shrink: 0; }
        .hist-t-total { width: 80px; flex-shrink: 0; }

        .detail-grid { grid-template-columns: 1fr; }
        .view-mode-toggle { display: none !important; }
        .hist-timing-lg { display: none; }
        .hist-timing-sm { display: block; }
        .hist-badges { display: flex; }

        /* ── MOBILE (≤ 640px) ── */
        @media (max-width: 640px) {
          .app-layout { flex-direction: column; }
          .sidebar {
            position: fixed; bottom: 0; left: 0; right: 0; z-index: 50;
            width: 100%; min-height: auto; height: 56px;
            flex-direction: row; justify-content: space-around;
            padding: 0; gap: 0;
            border-right: none; border-top: 1px solid ${C.border};
            box-shadow: 0 -2px 10px rgba(0,0,0,.06);
          }
          .sidebar-logo { display: none; }
          .sidebar-item { width: 48px; height: 48px; border-radius: 12px; }
          .sidebar-indicator { left: 50% !important; top: auto !important; bottom: 0; transform: translateX(-50%) !important; width: 20px !important; height: 3px !important; }
          .header { height: 50px; padding: 0 14px; }
          .header-title { font-size: 13px; }
          .header-status { font-size: 9px; }
          .header-controls { gap: 10px !important; }
          .header-sep { display: none; }
          .main-content { padding-bottom: 60px; }
          .hist-line1 { flex-wrap: wrap; gap: 6px !important; }
          .hist-badges { width: 100%; margin-top: 2px; order: 10; }
          .hist-total { margin-left: auto; }
          .hist-timing-sm { margin-left: 0 !important; }
          .hist-t-arrow, .hist-t-prep, .hist-t-deliv, .hist-t-total { width: auto; }
        }

        /* ── LARGE (≥ 1200px) ── */
        @media (min-width: 1200px) {
          .detail-grid { grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); }
          .view-mode-toggle { display: flex !important; }
          .hist-timing-lg { display: flex !important; flex: 1; justify-content: center; }
          .hist-timing-sm { display: none !important; }
        }
      `}</style>

      {/* Sidebar */}
      <Sidebar
        active={page}
        onNav={(p) => { setPage(p); setSelectedOrder(null); }}
        badges={{ orders: pendingCount, products: inactiveCount }}
      />

      {/* Main area */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        <Header
          storeOpen={storeOpen}
          setStoreOpen={setStoreOpen}
          closedToday={closedToday}
          setClosedToday={setClosedToday}
          themeMode={themeMode}
          setThemeMode={setThemeMode}
        />

        <div className="main-content" style={{ flex: 1, overflow: "hidden", display: "flex" }}>
          {page === "orders" && (
            viewMode === "split" ? (
              /* ── SPLIT MODE: list + detail side by side ── */
              <>
                <div style={{ width: selectedOrder ? "60%" : "100%", transition: "width .3s ease", overflow: "hidden", borderRight: selectedOrder ? `1px solid ${C.border}` : "none" }}>
                  <OrdersList orders={orders} onSelect={setSelectedOrder} onReady={handleReady} viewMode={viewMode} setViewMode={setViewMode} selectedId={selectedOrder?.id} />
                </div>
                {selectedOrder && (
                  <div style={{ width: "40%", overflow: "hidden" }}>
                    <OrderDetail
                      order={selectedOrder}
                      onBack={() => setSelectedOrder(null)}
                      onUpdateStatus={handleUpdateStatus}
                      products={products}
                      onToggleProduct={handleToggleProduct}
                    />
                  </div>
                )}
              </>
            ) : (
              /* ── PAGE MODE: one view at a time ── */
              <>
                {!selectedOrder && (
                  <div style={{ flex: 1, overflow: "hidden" }}>
                    <OrdersList orders={orders} onSelect={setSelectedOrder} onReady={handleReady} viewMode={viewMode} setViewMode={setViewMode} />
                  </div>
                )}
                {selectedOrder && (
                  <div style={{ flex: 1, overflow: "hidden" }}>
                    <OrderDetail
                      order={selectedOrder}
                      onBack={() => setSelectedOrder(null)}
                      onUpdateStatus={handleUpdateStatus}
                      products={products}
                      onToggleProduct={handleToggleProduct}
                    />
                  </div>
                )}
              </>
            )
          )}
          {page === "products" && (
            <div style={{ flex: 1, overflow: "hidden" }}>
              <ProductManager products={products} onToggle={handleToggleProduct} />
            </div>
          )}
          {page === "history" && (
            <div style={{ flex: 1, overflow: "hidden" }}>
              <HistoryView />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
