const { useEffect, useMemo, useRef, useState } = React;

// Multi-store marketplace v1: customer hub, merchant applications, merchant admin, platform admin, shared delivery fleet.
// No external packages or CDN icon imports.

const PLATFORM_DEFAULTS = {
  brandName: "Road Runner Local Hub",
  brandLogo: "",
  companyName: "Road Runner Company",
  supportEmail: "support@roadrunner.local",
  supportPhone: "28220 00000",
  legalAddress: "Κίσσαμος, Χανιά",
  subtitle: "Marketplace παραγγελιών για τοπικά καταστήματα",
  platformPin: "9999",
  serviceFee: 0.3,
  deliveryFee: 1,
  freeDeliveryFrom: 8,
  minOrder: 3,
  deliveryEnabled: true,
  pickupEnabled: true,
  payCashEnabled: true,
  payCardDeliveryEnabled: true,
  payStoreCardEnabled: true,
  driverBaseEtaMinutes: 25,
  driverBusyExtraMinutes: 8,
  driverPickupPrepMinutes: 10,
  liveDriverTrackingEnabled: true,
  driverLocationMaxAgeMinutes: 10,
  driverCommissionPercent: 40,
  driverPlatformFeePercent: 60,
  driverMinWithdraw: 300,
  driverRewardEnabled: true,
  driverRewardMinRating: 4.8,
  driverRewardBonusPerOrder: 0.2,
  loyaltyEnabled: true,
  loyaltyEarnPoints: 1,
  loyaltyEarnEuro: 1,
  loyaltyRedeemEnabled: true,
  loyaltyRedeemPoints: 100,
  loyaltyRedeemEuro: 1,
  loyaltyMinRedeemPoints: 100,
  loyaltyMaxDiscountPercent: 100,
  loyaltyApplyOnFees: true,
  loyaltyTierSilver: 250,
  loyaltyTierGold: 750,
  loyaltyTierBlack: 1500,
  loyaltyStreakBonusPoints: 15,
  platformAnnouncement: "Ένα hub για καφέ, snacks, προσφορές και delivery από πολλά καταστήματα.",
  contactText: `Επικοινωνία πλατφόρμας

Για υποστήριξη πελατών, καταστημάτων και διανομέων μπορείς να επικοινωνήσεις με την πλατφόρμα μέσω email ή τηλεφώνου.

Η πλατφόρμα διαχειρίζεται τεχνικά την παραγγελιοληψία, την εμφάνιση καταστημάτων, την καταχώρηση παραγγελιών, την επικοινωνία με τον πελάτη και τη ροή παράδοσης. Για θέματα ποιότητας προϊόντων, διαθεσιμότητας, συσκευασίας και φορολογικών παραστατικών, υπεύθυνο είναι το αντίστοιχο κατάστημα, εκτός αν υπάρχει διαφορετική γραπτή συμφωνία με την πλατφόρμα.`,
  termsText: `Όροι χρήσης πλατφόρμας

1. Ρόλος πλατφόρμας
Η πλατφόρμα λειτουργεί ως τεχνολογικό σύστημα παραγγελιοληψίας, διαχείρισης παραγγελιών, προβολής συνεργαζόμενων καταστημάτων και, όπου είναι ενεργό, συντονισμού διανομής. Δεν υποκαθιστά το κατάστημα ως προς την ποιότητα, την προετοιμασία, τη διαθεσιμότητα, τη νομιμότητα προϊόντων, την έκδοση αποδείξεων/τιμολογίων και τη συμμόρφωση με υγειονομικούς ή φορολογικούς κανόνες.

2. Παραγγελίες
Ο πελάτης οφείλει να καταχωρεί σωστό όνομα, τηλέφωνο, διεύθυνση, όροφο/κουδούνι, οδηγίες παράδοσης και τρόπο πληρωμής. Λανθασμένα στοιχεία μπορεί να οδηγήσουν σε καθυστέρηση, ακύρωση ή αποτυχία παράδοσης.

3. Χρεώσεις πλατφόρμας
Σε κάθε παραγγελία μπορεί να υπάρχουν service fee, delivery fee ή άλλες εμφανείς χρεώσεις πλατφόρμας. Οι χρεώσεις εμφανίζονται πριν την ολοκλήρωση της παραγγελίας. Η πλατφόρμα διατηρεί το δικαίωμα να μεταβάλλει fees, ελάχιστη παραγγελία, free delivery όρια, loyalty κανόνες, delivery κανόνες και ποσοστά διανομής οποιαδήποτε στιγμή, με εμφάνιση των νέων τιμών στο checkout ή/και στους όρους.

4. Καταστήματα
Κάθε κατάστημα είναι υπεύθυνο για τα προϊόντα, τις τιμές προϊόντων, τη διαθεσιμότητα, την προετοιμασία, τη συσκευασία, την ακρίβεια των πληροφοριών και την έκδοση νόμιμων παραστατικών όπου απαιτείται.

5. Διανομείς
Οι διανομείς οφείλουν να ακολουθούν τους κανόνες παραλαβής/παράδοσης, να προστατεύουν τα προσωπικά δεδομένα πελατών, να μη χρησιμοποιούν στοιχεία πελατών εκτός της συγκεκριμένης παράδοσης και να χειρίζονται μετρητά με ακρίβεια.

6. Αποκλεισμοί και διαγραφή
Η πλατφόρμα μπορεί να αναστείλει, αποκλείσει ή διαγράψει λογαριασμό πελάτη, διανομέα ή καταστήματος σε περίπτωση παραβίασης κανόνων, κακής χρήσης, ψευδών στοιχείων, απάτης, επαναλαμβανόμενων προβλημάτων ή επιχειρησιακής ανάγκης. Τα καταστήματα μπορούν να αποκλείουν πελάτες μόνο από το δικό τους κατάστημα.

7. Αξιολογήσεις
Ο πελάτης μπορεί να αξιολογεί τον διανομέα μετά από ολοκληρωμένη παράδοση. Οι αξιολογήσεις χρησιμοποιούνται για ποιότητα υπηρεσίας, επιβράβευση, έλεγχο απόδοσης και πιθανή αναστολή συνεργασίας σε περιπτώσεις σοβαρών ή επαναλαμβανόμενων παραπόνων.

8. Αλλαγές όρων
Η συνέχιση χρήσης της πλατφόρμας μετά από αλλαγές στους όρους θεωρείται αποδοχή των ενημερωμένων όρων, εφόσον οι αλλαγές εμφανίζονται διαθέσιμες στην πλατφόρμα.`,
  privacyText: `Πολιτική απορρήτου

1. Δεδομένα που συλλέγονται
Η πλατφόρμα μπορεί να αποθηκεύει όνομα, τηλέφωνο, email, διεύθυνση, όροφο/κουδούνι, σημειώσεις παράδοσης, ιστορικό παραγγελιών, στοιχεία καταστήματος, στοιχεία διανομέα, στοιχεία οχήματος, αξιολογήσεις, logs κατάστασης παραγγελιών, τεχνικά δεδομένα λειτουργίας και, όταν ο διανομέας έχει ενεργό GPS tracking, προσωρινή τοποθεσία διανομέα για την παρακολούθηση της ενεργής παράδοσης.

2. Σκοπός επεξεργασίας
Τα δεδομένα χρησιμοποιούνται για δημιουργία λογαριασμού, εκτέλεση παραγγελίας, επικοινωνία πελάτη-καταστήματος-διανομέα, υποστήριξη, πρόληψη κατάχρησης, λογιστικό/επιχειρησιακό έλεγχο, loyalty, αξιολογήσεις και βελτίωση υπηρεσίας.

3. Κοινοποίηση δεδομένων
Τα απαραίτητα στοιχεία πελάτη εμφανίζονται στο κατάστημα και στον διανομέα μόνο για την εκτέλεση της συγκεκριμένης παραγγελίας. Ο διανομέας βλέπει όνομα, τηλέφωνο, διεύθυνση, όροφο/κουδούνι, οδηγίες, τρόπο πληρωμής και περιεχόμενο παραγγελίας. Δεν επιτρέπεται χρήση αυτών των στοιχείων για άλλον σκοπό.

4. Δικαιώματα χρήστη
Ο χρήστης μπορεί να ζητήσει ενημέρωση, διόρθωση, περιορισμό, αντίρρηση ή διαγραφή προσωπικών δεδομένων, όπου αυτό επιτρέπεται από την ισχύουσα νομοθεσία και τις υποχρεώσεις τήρησης επιχειρησιακών/φορολογικών αρχείων.

5. Ασφάλεια
Η πλατφόρμα πρέπει να εφαρμόζει τεχνικά και οργανωτικά μέτρα όπως περιορισμένη πρόσβαση, ρόλους χρηστών, καταγραφή ενεργειών, ασφαλή αποθήκευση, προστασία από μη εξουσιοδοτημένη πρόσβαση και ελαχιστοποίηση δεδομένων.

6. Χρόνος τήρησης
Τα δεδομένα τηρούνται για όσο χρειάζεται για την παροχή της υπηρεσίας, την υποστήριξη, τον έλεγχο συναλλαγών και τις νόμιμες υποχρεώσεις. Δεδομένα που δεν χρειάζονται πλέον πρέπει να διαγράφονται ή να ανωνυμοποιούνται.`,
  refundText: `Ακυρώσεις, παράπονα και επιστροφές

Οι παραγγελίες φαγητού/ροφημάτων είναι άμεσης εκτέλεσης και συχνά αφορούν προϊόντα που ετοιμάζονται κατά παραγγελία. Ακύρωση μπορεί να γίνει μόνο πριν την αποδοχή ή πριν την έναρξη προετοιμασίας από το κατάστημα, ανάλογα με την πολιτική της πλατφόρμας και του καταστήματος.

Αν υπάρχει λάθος προϊόν, ελλιπής παραγγελία, μεγάλη καθυστέρηση, πρόβλημα ποιότητας ή λάθος χρέωση, ο πελάτης πρέπει να επικοινωνεί άμεσα με την υποστήριξη. Η πλατφόρμα εξετάζει το αίτημα σε συνεργασία με το κατάστημα και, όπου υπάρχει διανομή, με τον διανομέα.

Η πλατφόρμα μπορεί να αποφασίσει επαναποστολή, μερική επιστροφή, πλήρη επιστροφή, κουπόνι/πίστωση ή απόρριψη αιτήματος, ανάλογα με τα στοιχεία της περίπτωσης.`,
  merchantTermsText: `Όροι συνεργαζόμενων καταστημάτων

Το κατάστημα αποδέχεται ότι η πλατφόρμα μπορεί να εμφανίζει service fee, delivery fee ή άλλη χρέωση προς τον πελάτη. Αυτές οι χρεώσεις αφορούν τη χρήση της πλατφόρμας, την τεχνική λειτουργία, την παραγγελιοληψία και/ή τη διανομή, και μπορούν να αλλάξουν οποιαδήποτε στιγμή από τον Platform Admin.

Το κατάστημα παραμένει υπεύθυνο για προϊόντα, τιμές προϊόντων, ποιότητα, συσκευασία, χρόνους προετοιμασίας, φορολογικά παραστατικά, άδειες λειτουργίας, υγειονομική συμμόρφωση και σωστή ενημέρωση του μενού.

Το κατάστημα μπορεί να αποκλείει πελάτη μόνο από το δικό του κατάστημα. Η πλατφόρμα διατηρεί το δικαίωμα καθολικού αποκλεισμού χρήστη ή καταστήματος.`,
  driverRulesText: `Κανόνες διανομέων

1. Ο διανομέας βλέπει τα στοιχεία πελάτη μόνο για τη συγκεκριμένη παράδοση.
2. Δεν επιτρέπεται αποθήκευση, κοινοποίηση ή προσωπική χρήση τηλεφώνου/διεύθυνσης πελάτη.
3. Πριν φύγει από το κατάστημα ελέγχει αριθμό παραγγελίας, σακούλες, ροφήματα, συνοδευτικά και ειδικές οδηγίες.
4. Σε πληρωμή με μετρητά εισπράττει το ποσό που εμφανίζει η παραγγελία και επιστρέφει σωστά ρέστα.
5. Σε πληρωμή με κάρτα στον διανομέα ακολουθείται η εγκεκριμένη διαδικασία POS/τερματικού.
6. Δεν παραδίδει παραγγελία σε λάθος άτομο ή λάθος διεύθυνση χωρίς τηλεφωνική επιβεβαίωση.
7. Ολοκληρώνει την παραγγελία μόνο μετά την πραγματική παράδοση στον πελάτη.
8. Χαμηλές αξιολογήσεις, ακυρώσεις, παράπονα ή κακή χρήση μπορούν να οδηγήσουν σε αναστολή ή αποκλεισμό.
9. Υψηλές αξιολογήσεις μπορούν να δίνουν bonus όταν είναι ενεργό το σύστημα επιβράβευσης.
10. Όταν ο διανομέας ενεργοποιεί GPS tracking, η ζωντανή τοποθεσία εμφανίζεται μόνο για επιχειρησιακό έλεγχο ενεργής διανομής σε πελάτη, κατάστημα και διαχείριση πλατφόρμας.`,
  cashHandlingText: `Λειτουργία μετρητών

Σε παραγγελίες με μετρητά ο διανομέας πρέπει να βλέπει καθαρά το συνολικό ποσό, αν ο πελάτης ζητά ρέστα από συγκεκριμένο χαρτονόμισμα, και τις οδηγίες παράδοσης. Ο διανομέας παραδίδει την παραγγελία, εισπράττει το σωστό ποσό και επιστρέφει ρέστα όπου χρειάζεται. Διαφωνίες πληρωμής πρέπει να δηλώνονται στην πλατφόρμα.`,
  deliveryFlowText: `Ροή παραλαβής και παράδοσης

Νέα παραγγελία → αποδοχή από κατάστημα → ετοιμασία → ανάθεση διανομέα → παραλαβή από κατάστημα → διαδρομή προς πελάτη → παράδοση → rating πελάτη.

Ο διανομέας πριν πατήσει "Παρέλαβα" πρέπει να έχει λάβει όλα τα προϊόντα. Πριν πατήσει "Ολοκλήρωση" πρέπει να έχει παραδώσει πραγματικά στον πελάτη ή σε εξουσιοδοτημένο πρόσωπο.`,
};

const DEFAULT_CATEGORIES = ["Προσφορές", "Καφέδες", "Ροφήματα", "Σφολιάτες", "Σάντουιτς", "Γλυκά", "Snacks"];

const statusSteps = [
  { key: "new", label: "Νέα", text: "Η παραγγελία καταχωρήθηκε", icon: "🧾" },
  { key: "accepted", label: "Αποδοχή", text: "Το κατάστημα την αποδέχτηκε", icon: "✅" },
  { key: "preparing", label: "Ετοιμασία", text: "Το κατάστημα ετοιμάζει την παραγγελία", icon: "🍳" },
  { key: "driver_assigned", label: "Ανάθεση", text: "Ανατέθηκε σε διανομέα", icon: "🛵" },
  { key: "picked_up", label: "Παραλαβή", text: "Ο διανομέας παρέλαβε από το κατάστημα", icon: "📦" },
  { key: "delivery", label: "Διανομή", text: "Ο διανομέας είναι καθ’ οδόν", icon: "🛵" },
  { key: "completed", label: "Ολοκληρώθηκε", text: "Παραδόθηκε στον πελάτη", icon: "🎉" },
];

const statusLabels = {
  new: "Νέα παραγγελία",
  accepted: "Αποδοχή από κατάστημα",
  preparing: "Σε ετοιμασία",
  driver_assigned: "Ανατέθηκε σε διανομέα",
  picked_up: "Παραλήφθηκε από κατάστημα",
  delivery: "Σε διανομή",
  completed: "Ολοκληρώθηκε",
  cancelled: "Ακυρώθηκε",
};

const UI_TEXT = {
  el: {
    merchant: "Merchant",
    driver: "Driver",
    platformAdmin: "Platform Admin",
    login: "Login",
    activeStores: "ενεργά καταστήματα",
    products: "προϊόντα",
    stores: "Καταστήματα",
    allHub: "Όλο το hub",
    marketplaceBadge: "Παραγγελίες · Προσφορές · Τοπικά καταστήματα · Delivery",
    heroTitle: "Παράγγειλε εύκολα από τοπικά καταστήματα ή βάλε το κατάστημά σου στο δίκτυο.",
    productsCap: "Προϊόντα",
    driverFee: "Driver fee",
    joinPlatform: "Για επαγγελματίες",
    haveStore: "Έχεις κατάστημα;",
    merchantPitch: "Κάνε αίτηση συνεργασίας και διαχειρίσου προϊόντα, προσφορές και παραγγελίες από το δικό σου portal.",
    storeApply: "Αίτηση συνεργασίας",
    searchPlaceholder: "Αναζήτηση καταστήματος ή προϊόντος...",
    tracking: "Tracking",
    seeProgress: "Δες πρόοδο",
    topOffers: "Οι 3 καλύτερες προσφορές",
    noOffers: "Προσφορές σύντομα",
    optionsAdd: "Επιλογές / Προσθήκη",
    favorite: "Αγαπημένο",
    favorited: "Στα αγαπημένα",
    emptyFilter: "Δεν υπάρχουν προϊόντα για αυτό το φίλτρο.",
    cart: "Καλάθι",
    emptyCart: "Άδειο καλάθι",
    emptyCartText: "Πρόσθεσε προϊόντα από ένα κατάστημα.",
    itemsTotal: "Προϊόντα",
    pickup: "Παραλαβή",
    fromStore: "Από κατάστημα",
    free: "Δωρεάν",
    serviceFee: "Service fee",
    loyaltyFeeDiscount: "Loyalty έκπτωση στα fees",
    total: "Σύνολο",
    continue: "Συνέχεια",
    minOrder: "Ελάχιστη παραγγελία",
  },
  en: {
    merchant: "Merchant",
    driver: "Driver",
    platformAdmin: "Platform Admin",
    login: "Login",
    activeStores: "active stores",
    products: "products",
    stores: "Stores",
    allHub: "Full hub",
    marketplaceBadge: "Orders · Offers · Local stores · Delivery",
    heroTitle: "Order easily from local stores or bring your store into the network.",
    productsCap: "Products",
    driverFee: "Driver fee",
    joinPlatform: "For businesses",
    haveStore: "Own a store?",
    merchantPitch: "Apply as a partner and manage products, offers and orders from your own portal.",
    storeApply: "Partner application",
    searchPlaceholder: "Search store or product...",
    tracking: "Tracking",
    seeProgress: "Track order",
    topOffers: "Top 3 offers",
    noOffers: "Offers coming soon",
    optionsAdd: "Options / Add",
    favorite: "Favorite",
    favorited: "Favorited",
    emptyFilter: "No products for this filter.",
    cart: "Cart",
    emptyCart: "Empty cart",
    emptyCartText: "Add products from one store.",
    itemsTotal: "Products",
    pickup: "Pickup",
    fromStore: "From store",
    free: "Free",
    serviceFee: "Service fee",
    loyaltyFeeDiscount: "Loyalty discount on fees",
    total: "Total",
    continue: "Continue",
    minOrder: "Minimum order",
  }
};

const AUTO_TRANSLATIONS = {
  "Marketplace παραγγελιών για τοπικά καταστήματα": "Ordering marketplace for local stores",
  "Ένα hub για καφέ, snacks, προσφορές και delivery από πολλά καταστήματα.": "One hub for coffee, snacks, offers and delivery from multiple stores.",
  "Προσφορές": "Offers",
  "Καφέδες": "Coffees",
  "Ροφήματα": "Drinks",
  "Σφολιάτες": "Pastries",
  "Σάντουιτς": "Sandwiches",
  "Γλυκά": "Desserts",
  "Όλα": "All",
  "Κίσσαμος": "Kissamos",
  "Κέντρο Κισσάμου": "Kissamos Center",
  "Παραλιακή Κισσάμου": "Kissamos Seafront",
  "Καφέδες, ροφήματα, σφολιάτες και combos.": "Coffee, drinks, pastries and combos.",
  "Σάντουιτς, χυμοί, γλυκά και γρήγορο brunch.": "Sandwiches, juices, desserts and quick brunch.",
  "Freddo Espresso": "Freddo Espresso",
  "Freddo Cappuccino": "Freddo Cappuccino",
  "Energy Combo": "Energy Combo",
  "Club Sandwich": "Club Sandwich",
  "Φυσικός Χυμός": "Fresh Juice",
  "Brunch Deal": "Brunch Deal",
  "Διπλός espresso με πάγο και έντονο σώμα.": "Double espresso over ice with a strong body.",
  "Κρύος cappuccino με πλούσια κρέμα.": "Cold cappuccino with rich foam.",
  "Καφές + σφολιάτα σε ειδική τιμή.": "Coffee + pastry at a special price.",
  "Κοτόπουλο, μπέικον, τυρί, ντομάτα και πατάτες.": "Chicken, bacon, cheese, tomato and fries.",
  "Φρεσκοστυμμένος χυμός πορτοκάλι.": "Freshly squeezed orange juice.",
  "Club sandwich + φυσικός χυμός.": "Club sandwich + fresh juice.",
  "Σκέτος": "No sugar",
  "Μέτριος": "Medium sugar",
  "Γλυκός": "Sweet",
  "Χωρίς γάλα": "No milk",
  "Λίγο γάλα": "A little milk",
  "Με γάλα": "With milk",
  "Κανονικό": "Regular",
  "Χωρίς έξτρα": "No extras",
  "Ζεστή σφολιάτα": "Warm pastry",
  "Με πατάτες": "With fries",
  "Χωρίς πατάτες": "No fries",
  "Με πάγο": "With ice",
  "Χωρίς πάγο": "No ice",
  "Χωρίς ζάχαρη": "No sugar"
};

const EN_PHRASES = {
  "Επικοινωνία": "Contact",
  "Όροι χρήσης": "Terms of Use",
  "Πολιτική απορρήτου": "Privacy Policy",
  "Ακυρώσεις / Επιστροφές": "Cancellations / Refunds",
  "Όροι καταστημάτων": "Store Terms",
  "Κανόνες διανομέων": "Driver Rules",
  "Στοιχεία πλατφόρμας": "Platform details",
  "Τηλέφωνο": "Phone",
  "Έδρα": "Registered area",
  "Πληροφορίες": "Information",
  "Πελάτης": "Customer",
  "Κατάστημα": "Store",
  "Καταστήματα": "Stores",
  "Προϊόντα": "Products",
  "Παραγγελίες": "Orders",
  "Παραγγελία": "Order",
  "Όλες οι παραγγελίες": "All orders",
  "Παραγγελίες καταστήματος": "Store orders",
  "Δεν υπάρχουν παραγγελίες": "No orders found",
  "Δεν υπάρχουν αιτήσεις": "No applications found",
  "Δεν υπάρχουν διανομείς": "No drivers found",
  "Δεν υπάρχουν διαθέσιμες παραγγελίες": "No available orders",
  "Δεν έχεις ενεργή διανομή": "You have no active delivery",
  "Δεν έχεις ενεργή παραγγελία": "You have no active order",
  "Δεν υπάρχουν προϊόντα για αυτό το φίλτρο.": "No products match this filter.",
  "Άδειο καλάθι": "Empty cart",
  "Πρόσθεσε προϊόντα από ένα κατάστημα.": "Add products from one store.",
  "Σύνολο": "Total",
  "Σχόλιο προϊόντος": "Product note",
  "Σχόλια παραγγελίας": "Order notes",
  "Ειδικές οδηγίες": "Special instructions",
  "Προσθήκη": "Add",
  "Αφαίρεση": "Remove",
  "Αποθήκευση": "Save",
  "Αποθήκευση προφίλ": "Save profile",
  "Αποθήκευση store setup": "Save store setup",
  "Αποθήκευση κατηγοριών": "Save categories",
  "Δημιουργία λογαριασμού": "Create account",
  "Είσοδος": "Login",
  "Είσοδος πελάτη": "Customer login",
  "Εγγραφή πελάτη": "Customer registration",
  "Εγγραφή διανομέα": "Driver registration",
  "Είσοδος διανομέα": "Driver login",
  "Αποστολή αίτησης": "Submit application",
  "Αίτηση συμμετοχής καταστήματος": "Store application",
  "Νέα αίτηση καταστήματος": "New store application",
  "Έχω ήδη έγκριση / Login": "Already approved / Login",
  "Έχω λογαριασμό": "I already have an account",
  "Νέα εγγραφή": "New registration",
  "Ονοματεπώνυμο": "Full name",
  "Ιδιοκτήτης": "Owner",
  "Τηλέφωνο ιδιοκτήτη / login": "Owner phone / login",
  "Κωδικός": "Password",
  "Κωδικός merchant": "Merchant password",
  "Αριθμός ταυτότητας": "ID number",
  "Ταυτότητα / άδεια": "ID / license",
  "ΑΦΜ": "Tax number",
  "Όνομα καταστήματος": "Store name",
  "Τηλέφωνο καταστήματος": "Store phone",
  "Διεύθυνση καταστήματος": "Store address",
  "Περιοχή": "Area",
  "Τύπος καταστήματος": "Store type",
  "IBAN καταστήματος": "Store IBAN",
  "Σημειώσεις": "Notes",
  "Διεύθυνση": "Address",
  "Διεύθυνση παράδοσης": "Delivery address",
  "Διεύθυνση προαιρετικά": "Optional address",
  "Όροφος": "Floor",
  "Όροφος / κουδούνι": "Floor / doorbell",
  "Ώρα παράδοσης / παραλαβής": "Delivery / pickup time",
  "Άμεσα ή 18:30": "ASAP or 18:30",
  "Τρόπος εξυπηρέτησης": "Service type",
  "Πληρωμή": "Payment",
  "Μετρητά": "Cash",
  "Μετρητά στην παράδοση": "Cash on delivery",
  "Κάρτα στον διανομέα": "Card to driver",
  "Κάρτα στο κατάστημα": "Card at store",
  "Delivery στην πόρτα": "Delivery to door",
  "Παραλαβή από κατάστημα": "Pickup from store",
  "Παραλαβή": "Pickup",
  "Από κατάστημα": "From store",
  "Δωρεάν": "Free",
  "Ολοκλήρωση παραγγελίας": "Checkout",
  "Αποστολή παραγγελίας": "Place order",
  "Ελάχιστη παραγγελία": "Minimum order",
  "Διαθέσιμοι πόντοι": "Available points",
  "πόντοι": "points",
  "πόντος": "point",
  "έκπτωση μόνο στα fees": "discount only on fees",
  "Loyalty επιβράβευση": "Loyalty rewards",
  "Με αυτή την παραγγελία κερδίζεις περίπου": "With this order you earn about",
  "πόντους από την αξία προϊόντων": "points from product value",
  "Η εξαργύρωση αφαιρείται μόνο από service/delivery fees.": "Redemption is applied only to service/delivery fees.",
  "Πόντοι για εξαργύρωση": "Points to redeem",
  "Χρειάζονται τουλάχιστον": "At least",
  "Η έκπτωση εφαρμόζεται μόνο μέχρι το ύψος των platform fees, όχι στα προϊόντα.": "The discount applies only up to platform fees, not products.",
  "Γεια σου": "Hello",
  "πελάτη": "customer",
  "Προφίλ, ιστορικό, loyalty πόντοι, ενεργές παραγγελίες και αγαπημένα προϊόντα.": "Profile, history, loyalty points, active orders and favorite products.",
  "Σύνοψη": "Overview",
  "Προφίλ": "Profile",
  "Αγαπημένα": "Favorites",
  "Ενεργές": "Active",
  "Loyalty πόντοι": "Loyalty points",
  "Σύνολο αγορών": "Total spent",
  "Γρήγορη σύνοψη": "Quick overview",
  "Loyalty διαθέσιμοι πόντοι": "Available loyalty points",
  "Καταστήματα που έχεις χρησιμοποιήσει": "Stores used",
  "Ολοκληρωμένες παραγγελίες": "Completed orders",
  "Ενεργές παραγγελίες": "Active orders",
  "Ιστορικό παραγγελιών": "Order history",
  "Κίνηση loyalty": "Loyalty activity",
  "Συνολικά κερδισμένοι πόντοι": "Total points earned",
  "Συνολικά εξαργυρωμένοι πόντοι": "Total points redeemed",
  "Συνολική έκπτωση από loyalty στα fees": "Total loyalty discount on fees",
  "Ελάχιστοι πόντοι εξαργύρωσης": "Minimum redeem points",
  "Πού εφαρμόζεται": "Applies to",
  "Μόνο σε service fee + delivery fee": "Only to service fee + delivery fee",
  "Προφίλ πελάτη": "Customer profile",
  "Αγαπημένα προϊόντα": "Favorite products",
  "Δεν έχεις αγαπημένα ακόμα": "You have no favorites yet",
  "Επανάληψη": "Reorder",
  "Αξιολόγηση διανομέα": "Driver rating",
  "Έδωσες": "You rated",
  "Αν είναι πάνω από το όριο επιβράβευσης, ο διανομέας παίρνει bonus.": "If it meets the reward threshold, the driver receives a bonus.",
  "αναμονή": "pending",
  "Νέα παραγγελία": "New order",
  "Αποδοχή από κατάστημα": "Accepted by store",
  "Σε ετοιμασία": "Preparing",
  "Ανατέθηκε σε διανομέα": "Assigned to driver",
  "Παραλήφθηκε από κατάστημα": "Picked up from store",
  "Σε διανομή": "Out for delivery",
  "Ολοκληρώθηκε": "Completed",
  "Ακυρώθηκε": "Cancelled",
  "Νέα": "New",
  "Αποδοχή": "Accepted",
  "Ετοιμασία": "Preparing",
  "Ανάθεση": "Assigned",
  "Διανομή": "Delivery",
  "Η παραγγελία καταχωρήθηκε": "The order was placed",
  "Το κατάστημα την αποδέχτηκε": "The store accepted it",
  "Το κατάστημα ετοιμάζει την παραγγελία": "The store is preparing the order",
  "Ο διανομέας παρέλαβε από το κατάστημα": "The driver picked it up from the store",
  "Ο διανομέας είναι καθ’ οδόν": "The driver is on the way",
  "Παραδόθηκε στον πελάτη": "Delivered to the customer",
  "Στοιχεία παραγγελίας": "Order details",
  "Οδηγίες": "Instructions",
  "Προορισμός": "Destination",
  "Προγραμματισμός": "Scheduled time",
  "Επικοινωνία με τηλέφωνο": "Phone contact",
  "Επικοινωνία με μήνυμα": "Message contact",
  "Μετρητά: εισπράττεις": "Cash: collect",
  "από τον πελάτη": "from the customer",
  "Ρέστα από": "Change from",
  "Έλεγξε αν χρειάζονται ρέστα.": "Check if change is needed.",
  "Ακολούθησε τη διαδικασία POS/καταστήματος.": "Follow the POS/store procedure.",
  "Αποδοχή διανομής": "Accept delivery",
  "Παρέλαβα από κατάστημα": "Picked up from store",
  "Ξεκίνησα προς πελάτη": "Started toward customer",
  "Ολοκλήρωση παράδοσης": "Complete delivery",
  "Όχημα": "Vehicle",
  "Μηχανάκι": "Motorbike",
  "Αυτοκίνητο": "Car",
  "Ποδήλατο": "Bicycle",
  "Πινακίδα": "Plate number",
  "Περιμένεις έγκριση Platform Admin": "Waiting for Platform Admin approval",
  "Είσαι offline": "You are offline",
  "Γίνε online για να βλέπεις διαθέσιμες παραγγελίες από όλα τα καταστήματα.": "Go online to see available orders from all stores.",
  "Τρέχουσα διανομή": "Current delivery",
  "Διαθέσιμες παραγγελίες όλων των καταστημάτων": "Available orders from all stores",
  "Ο οδηγός παίρνει": "The driver receives",
  "από κάθε delivery fee": "from each delivery fee",
  "ανά ολοκληρωμένη αξιολογημένη διανομή": "per completed rated delivery",
  "Κεντρική διαχείριση διανομέων": "Central driver management",
  "Δεν υπάρχουν requests.": "No requests found.",
  "Νέο προϊόν": "New product",
  "Επεξεργασία προϊόντος": "Edit product",
  "Ο Merchant ελέγχει προϊόντα, κατηγορίες, τιμές και προσφορές.": "The merchant manages products, categories, prices and offers.",
  "Όνομα προϊόντος": "Product name",
  "Φωτογραφία προϊόντος": "Product photo",
  "Κατηγορία": "Category",
  "Νέα κατηγορία": "New category",
  "Τιμή": "Price",
  "Παλιά τιμή": "Old price",
  "Χρόνος": "Time",
  "Περιγραφή": "Description",
  "Γλυκύτητα": "Sweetness",
  "Επιλογές": "Options",
  "Επιλογή": "Option",
  "Ενεργό": "Active",
  "Προσφορά": "Offer",
  "Προϊόντα καταστήματος": "Store products",
  "Κεντρικός έλεγχος πλατφόρμας.": "Central platform control.",
  "Κεντρικός έλεγχος για χρήστες, καταστήματα, delivery, fees, branding, νομικές σελίδες και αποκλεισμούς.": "Central control for users, stores, delivery, fees, branding, legal pages and bans.",
  "Χρήστες": "Users",
  "Αιτήσεις": "Applications",
  "Σελίδες": "Pages",
  "Οικονομικά πλατφόρμας": "Platform financials",
  "Έλεγχος δεδομένων": "Data control",
  "Ενεργοί χρήστες": "Active users",
  "Banned/suspended χρήστες": "Banned/suspended users",
  "Ακυρωμένες παραγγελίες": "Cancelled orders",
  "Καταστήματα πλατφόρμας": "Platform stores",
  "Κεντρικά fees πλατφόρμας": "Central platform fees",
  "Branding & βασικές πληροφορίες πλατφόρμας": "Branding & basic platform information",
  "Footer / Νομικές σελίδες": "Footer / Legal pages",
  "Χρήστες / πελάτες πλατφόρμας": "Platform users / customers",
  "Δεν υπάρχουν εγγεγραμμένοι χρήστες": "No registered users",
  "Εγκεκριμένο": "Approved",
  "Σε αναστολή": "Suspended",
  "Μόνιμο ban": "Permanent ban",
  "Απορρίφθηκε": "Rejected",
  "Σε αναμονή": "Pending",
  "Εγκεκριμένος": "Approved",
  "Σε αναμονή έγκρισης": "Pending approval",
  "Ενεργός": "Active",
  "Αποκλεισμός από Merchant": "Blocked by Merchant",
  "Αποκλεισμός από κατάστημα": "Blocked by store",
  "Πελάτες καταστήματος & αποκλεισμοί": "Store customers & bans",
  "Δεν υπάρχουν πελάτες ακόμα": "No customers yet",
  "χωρίς email": "no email",
  "Banned από αυτό το κατάστημα": "Banned from this store",
  "Unban από κατάστημα": "Unban from store",
  "Ban από κατάστημα": "Ban from store",
  "Ενεργοί αποκλεισμοί": "Active bans",
  "Store οικονομικά": "Store financials",
  "Τζίρος προϊόντων καταστήματος": "Store product revenue",
  "Μέσο order προϊόντων": "Average product order",
  "Οι χρεώσεις service/delivery fees της πλατφόρμας εμφανίζονται στον πελάτη και μπορούν να αλλάξουν από την πλατφόρμα οποιαδήποτε στιγμή. Το κατάστημα βλέπει εδώ μόνο τα δικά του έσοδα προϊόντων.": "Platform service/delivery fees are shown to the customer and may change by the platform at any time. The store sees only its own product revenue here.",
  "Το Merchant Admin είναι ξεχωριστό από το Platform Admin. Ο καταστηματάρχης διαχειρίζεται προϊόντα, κατηγορίες και orders μόνο του δικού του καταστήματος.": "Merchant Admin is separate from Platform Admin. The merchant manages products, categories and orders only for their own store.",
  "Με την αίτηση αποδέχεσαι ότι η πλατφόρμα μπορεί να εφαρμόζει service/delivery fees προς τον πελάτη και να τα αλλάζει οποιαδήποτε στιγμή. Το κατάστημα βλέπει τα δικά του έσοδα προϊόντων, ενώ η πλατφόρμα διατηρεί τον κεντρικό έλεγχο κανόνων, fees και πρόσβασης.": "By applying, you accept that the platform may apply service/delivery fees to the customer and change them at any time. The store sees its own product revenue, while the platform keeps central control of rules, fees and access.",
  "Οι διανομείς βλέπουν orders από όλα τα εγκεκριμένα καταστήματα και πρέπει να ακολουθούν κανόνες προσωπικών δεδομένων, παραλαβής, παράδοσης και διαχείρισης μετρητών.": "Drivers see orders from all approved stores and must follow personal-data, pickup, delivery and cash-handling rules.",
  "Με την αίτηση αποδέχεσαι ότι τα στοιχεία πελατών χρησιμοποιούνται μόνο για την αντίστοιχη παράδοση, ότι η ολοκλήρωση πατιέται μόνο μετά την πραγματική παράδοση και ότι χαμηλές αξιολογήσεις ή παράπονα μπορούν να οδηγήσουν σε αναστολή.": "By applying, you accept that customer details are used only for the relevant delivery, completion is pressed only after real delivery, and low ratings or complaints may lead to suspension.",
  "Όροι χρήσης πλατφόρμας": "Platform Terms of Use",
  "Επικοινωνία πλατφόρμας": "Platform contact",
  "Όροι συνεργαζόμενων καταστημάτων": "Partner Store Terms",
  "Κανόνες διανομέων": "Driver rules",
  "Λειτουργία μετρητών": "Cash handling",
  "Ροή παραλαβής και παράδοσης": "Pickup and delivery flow",
  "Ακυρώσεις, παράπονα και επιστροφές": "Cancellations, complaints and refunds",
  "Δεδομένα που συλλέγονται": "Data collected",
  "Σκοπός επεξεργασίας": "Purpose of processing",
  "Κοινοποίηση δεδομένων": "Data sharing",
  "Δικαιώματα χρήστη": "User rights",
  "Ασφάλεια": "Security",
  "Χρόνος τήρησης": "Retention period",
  "Ρόλος πλατφόρμας": "Platform role",
  "Χρεώσεις πλατφόρμας": "Platform fees",
  "Διανομείς": "Drivers",
  "Αποκλεισμοί και διαγραφή": "Bans and deletion",
  "Αξιολογήσεις": "Ratings",
  "Αλλαγές όρων": "Changes to terms"
};

function translateTextToEnglish(text) {
  const original = String(text ?? "");
  if (!original.trim()) return original;
  const leadingLength = original.length - original.trimStart().length;
  const trailingLength = original.length - original.trimEnd().length;
  const leading = original.slice(0, leadingLength);
  const trailing = trailingLength ? original.slice(original.length - trailingLength) : "";
  let body = original.trim();
  if (AUTO_TRANSLATIONS[body]) return `${leading}${AUTO_TRANSLATIONS[body]}${trailing}`;
  if (EN_PHRASES[body]) return `${leading}${EN_PHRASES[body]}${trailing}`;
  const sorted = Object.entries({ ...AUTO_TRANSLATIONS, ...EN_PHRASES }).sort((a, b) => b[0].length - a[0].length);
  sorted.forEach(([el, en]) => {
    if (body.includes(el)) body = body.split(el).join(en);
  });
  return `${leading}${body}${trailing}`;
}

function t(lang, key) {
  return UI_TEXT[lang]?.[key] || UI_TEXT.el[key] || key;
}

function tx(value, lang = "el") {
  if (lang !== "en") return value;
  if (value && typeof value === "object" && !Array.isArray(value)) return value.en || translateTextToEnglish(value.el || "");
  return translateTextToEnglish(value);
}

function translateDomTree(root) {
  if (typeof window === "undefined" || !root) return;
  const blocked = new Set(["SCRIPT", "STYLE", "TEXTAREA"]);
  const filter = window.NodeFilter;
  if (!filter) return;
  const walker = document.createTreeWalker(root, filter.SHOW_TEXT, {
    acceptNode(node) {
      const parent = node.parentElement;
      if (!parent || blocked.has(parent.tagName) || parent.closest("textarea")) return filter.FILTER_REJECT;
      if (!node.nodeValue || !node.nodeValue.trim()) return filter.FILTER_REJECT;
      return filter.FILTER_ACCEPT;
    }
  });
  const nodes = [];
  while (walker.nextNode()) nodes.push(walker.currentNode);
  nodes.forEach((node) => {
    const translated = translateTextToEnglish(node.nodeValue);
    if (translated !== node.nodeValue) node.nodeValue = translated;
  });
  root.querySelectorAll?.("[placeholder], [title], [aria-label]").forEach((el) => {
    ["placeholder", "title", "aria-label"].forEach((attr) => {
      const value = el.getAttribute(attr);
      if (value) el.setAttribute(attr, translateTextToEnglish(value));
    });
  });
}

const formatEuro = (value, lang = "el") => new Intl.NumberFormat(lang === "en" ? "en-US" : "el-GR", { style: "currency", currency: "EUR" }).format(Number(value || 0));
const safeId = (prefix = "id") => `${prefix}-${Math.floor(100000 + Math.random() * 900000)}`;
const roundMoney = (value) => Math.round(Number(value || 0) * 100) / 100;

function readStorage(key, fallback) {
  if (typeof window === "undefined") return fallback;
  try {
    const serverState = window.__RR_SERVER_STATE__ || {};
    if (typeof RR_SYNC_KEYS !== "undefined" && RR_SYNC_KEYS.includes(key) && Object.prototype.hasOwnProperty.call(serverState, key)) {
      try { localStorage.setItem(key, JSON.stringify(serverState[key])); } catch {}
      return serverState[key] ?? fallback;
    }
    const parsed = JSON.parse(localStorage.getItem(key) || "null");
    return parsed ?? fallback;
  } catch {
    return fallback;
  }
}

function isInlineImageData(value) {
  return typeof value === "string" && value.startsWith("data:image/");
}

function storageSafeImage(value) {
  return isInlineImageData(value) ? "" : (value || "");
}

function compactOrderItemForStorage(item) {
  return { ...item, image: storageSafeImage(item.image) };
}

function compactOrderForStorage(order) {
  return {
    ...order,
    storeSnapshot: order.storeSnapshot ? { ...order.storeSnapshot, logo: storageSafeImage(order.storeSnapshot.logo) } : order.storeSnapshot,
    items: Array.isArray(order.items) ? order.items.map(compactOrderItemForStorage) : [],
    statusHistory: Array.isArray(order.statusHistory) ? order.statusHistory.slice(-20) : [],
    driverEvents: Array.isArray(order.driverEvents) ? order.driverEvents.slice(-20) : [],
  };
}

function compactStorageValue(key, value) {
  if (key === "rr_orders_v1") return Array.isArray(value) ? value.slice(0, 150).map(compactOrderForStorage) : [];
  return value;
}

function saveStorage(key, value) {
  if (typeof window === "undefined") return;
  const compactValue = compactStorageValue(key, value);
  try {
    localStorage.setItem(key, JSON.stringify(compactValue));
  } catch (error) {
    console.warn(`Storage save skipped for ${key}`, error);
    try {
      localStorage.removeItem(key);
      const emergencyValue = key === "rr_orders_v1" && Array.isArray(value) ? value.slice(0, 50).map(compactOrderForStorage) : compactValue;
      localStorage.setItem(key, JSON.stringify(emergencyValue));
    } catch (secondError) {
      console.warn(`Storage emergency save failed for ${key}`, secondError);
    }
  }
  queueServerStateSave(key, compactValue);
}


const RR_SYNC_KEYS = [
  "rr_platform_v1",
  "rr_stores_v1",
  "rr_store_apps_v1",
  "rr_users_v1",
  "rr_drivers_v1",
  "rr_driver_withdrawals_v1",
  "rr_orders_v1",
];

function rrApiHeaders() {
  return {
    "Content-Type": "application/json",
    "X-RR-Sync-Token": String(window.__RR_SYNC_TOKEN__ || ""),
  };
}

function queueServerStateSave(key, value) {
  if (typeof window === "undefined" || !window.__RR_API_ENABLED__) return;
  if (!RR_SYNC_KEYS.includes(key)) return;
  window.__RR_SAVE_TIMERS__ = window.__RR_SAVE_TIMERS__ || {};
  if (window.__RR_SAVE_TIMERS__[key]) window.clearTimeout(window.__RR_SAVE_TIMERS__[key]);
  window.__RR_SAVE_TIMERS__[key] = window.setTimeout(() => {
    fetch("./api/state.php", {
      method: "POST",
      credentials: "same-origin",
      headers: rrApiHeaders(),
      body: JSON.stringify({ key, value }),
    }).catch((error) => console.warn("Road Runner MySQL sync failed", key, error));
  }, 350);
}

function sameJson(a, b) {
  try { return JSON.stringify(a) === JSON.stringify(b); } catch { return false; }
}

function splitList(value) {
  if (Array.isArray(value)) return value.filter(Boolean);
  return String(value || "").split(",").map((item) => item.trim()).filter(Boolean);
}

function paymentLabel(value) {
  if (value === "card_on_delivery") return "Κάρτα στον διανομέα";
  if (value === "store_card") return "Κάρτα στο κατάστημα";
  return "Μετρητά στην παράδοση";
}

function serviceLabel(value) {
  return value === "pickup" ? "Παραλαβή από κατάστημα" : "Delivery";
}

function vehicleLabel(value) {
  if (value === "car") return "Αυτοκίνητο";
  if (value === "bicycle") return "Ποδήλατο";
  if (value === "scooter") return "Scooter";
  return "Μηχανάκι";
}

function normalizeLocation(location) {
  if (!location) return null;
  const lat = Number(location.lat ?? location.latitude);
  const lng = Number(location.lng ?? location.longitude);
  if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
  return {
    lat: Math.round(lat * 1000000) / 1000000,
    lng: Math.round(lng * 1000000) / 1000000,
    accuracy: location.accuracy == null ? null : Math.round(Number(location.accuracy)),
    heading: location.heading == null ? null : Math.round(Number(location.heading)),
    speed: location.speed == null ? null : Math.round(Number(location.speed) * 10) / 10,
    at: location.at || new Date().toISOString(),
  };
}

function locationAgeText(location) {
  if (!location?.at) return "χωρίς ενημέρωση";
  const seconds = Math.max(0, Math.round((Date.now() - new Date(location.at).getTime()) / 1000));
  if (seconds < 60) return `${seconds}s πριν`;
  const minutes = Math.round(seconds / 60);
  if (minutes < 60) return `${minutes} λεπτά πριν`;
  return `${Math.round(minutes / 60)} ώρες πριν`;
}

function mapsUrl(location) {
  const loc = normalizeLocation(location);
  return loc ? `https://www.google.com/maps?q=${loc.lat},${loc.lng}` : "#";
}

function storeStatusLabel(status) {
  if (status === "approved") return "Εγκεκριμένο";
  if (status === "suspended") return "Σε αναστολή";
  if (status === "banned") return "Μόνιμο ban";
  if (status === "rejected") return "Απορρίφθηκε";
  return "Σε αναμονή";
}

function driverStatusLabel(status) {
  if (status === "approved") return "Εγκεκριμένος";
  if (status === "suspended") return "Σε αναστολή";
  if (status === "rejected") return "Απορρίφθηκε";
  return "Σε αναμονή έγκρισης";
}

function userStatusLabel(status) {
  if (status === "banned") return "Μόνιμο ban";
  if (status === "suspended") return "Σε αναστολή";
  return "Ενεργός";
}

function isUserGloballyBanned(user) {
  return user?.status === "banned" || user?.status === "suspended";
}

function isCustomerBannedFromStore(user, store) {
  if (!user || !store) return false;
  return (store.customerBans || []).some((ban) => (ban.userId && ban.userId === user.id) || (ban.phone && ban.phone === user.phone));
}

function calculateExtraPriceFromChoices(choices) {
  const text = [choices?.sweetness, choices?.milk, ...(choices?.extras || [])].join(" ");
  const extraPricePattern = /[+]([0-9]+(?:[.][0-9]+)?)€/g;
  const matches = Array.from(text.matchAll(extraPricePattern));
  return roundMoney(matches.reduce((sum, match) => sum + Number(match[1] || 0), 0));
}

function readImageFile(file, onLoad) {
  if (!file) return;
  if (!file.type?.startsWith("image/")) return;
  const reader = new FileReader();
  reader.onload = () => {
    const raw = String(reader.result || "");
    const img = new Image();
    img.onload = () => {
      try {
        const maxSide = 720;
        const scale = Math.min(1, maxSide / Math.max(img.width || 1, img.height || 1));
        const canvas = document.createElement("canvas");
        canvas.width = Math.max(1, Math.round((img.width || 1) * scale));
        canvas.height = Math.max(1, Math.round((img.height || 1) * scale));
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        const optimized = canvas.toDataURL("image/webp", 0.72);
        onLoad(optimized.length < raw.length ? optimized : raw);
      } catch {
        onLoad(raw);
      }
    };
    img.onerror = () => onLoad(raw);
    img.src = raw;
  };
  reader.readAsDataURL(file);
}

function ImageUpload({ label, value, onChange, fallback = "🏪", hint = "PNG / JPG / WebP" }) {
  return <div className="rounded-2xl bg-white p-4 ring-1 ring-slate-200"><span className="mb-3 block text-sm font-black text-slate-700">{label}</span><div className="flex items-center gap-4"><div className="grid h-20 w-20 shrink-0 place-items-center overflow-hidden rounded-2xl bg-slate-100 ring-1 ring-slate-200">{value ? <img src={value} alt={label} className="h-full w-full object-contain" /> : <span className="text-3xl">{fallback}</span>}</div><div className="min-w-0 flex-1"><input type="file" accept="image/*" onChange={(e) => readImageFile(e.target.files?.[0], onChange)} className="block w-full text-sm font-bold text-slate-600 file:mr-3 file:rounded-xl file:border-0 file:bg-slate-950 file:px-4 file:py-2 file:text-sm file:font-black file:text-white" /><p className="mt-2 text-xs font-bold text-slate-500">{hint}</p>{value && <button type="button" onClick={() => onChange("")} className="mt-2 rounded-xl bg-rose-50 px-3 py-2 text-xs font-black text-rose-700">Αφαίρεση εικόνας</button>}</div></div></div>;
}

function MediaBox({ src, fallback = "🏪", className = "", imgClassName = "h-full w-full object-cover" }) {
  return src ? <img src={src} alt="" className={imgClassName} /> : <span className={className}>{fallback}</span>;
}

function normalizeProduct(product, storeId) {
  return {
    id: product.id || safeId("prod"),
    storeId,
    title: String(product.title || "Νέο προϊόν").trim(),
    category: String(product.category || "Καφέδες").trim(),
    price: Number(product.price || 0),
    oldPrice: product.oldPrice === "" || product.oldPrice == null ? null : Number(product.oldPrice),
    rating: Number(product.rating || 4.8),
    time: product.time || "10-15'",
    image: product.image || product.imageUrl || "",
    emoji: product.emoji || "☕",
    badge: product.badge || "",
    active: product.active !== false,
    promo: Boolean(product.promo || product.offerType === "bogo" || product.offerType === "bundle"),
    offerType: product.offerType || "standard",
    bundleProductId: product.bundleProductId || "",
    bundleLabel: product.bundleLabel || "",
    description: product.description || "",
    options: {
      sweetness: product.options?.sweetness?.length ? product.options.sweetness : ["Κανονικό"],
      milk: product.options?.milk?.length ? product.options.milk : ["Κανονικό"],
      extras: product.options?.extras?.length ? product.options.extras : ["Χωρίς έξτρα"],
    },
  };
}

function createDefaultProducts(storeId) {
  const base = [
    { title: "Freddo Espresso", category: "Καφέδες", price: 2.2, oldPrice: 2.6, rating: 4.9, emoji: "☕", badge: "Best seller", description: "Διπλός espresso με πάγο και έντονο σώμα.", options: { sweetness: ["Σκέτος", "Μέτριος", "Γλυκός"], milk: ["Χωρίς γάλα", "Λίγο γάλα", "Φυτικό γάλα +0.40€"], extras: ["Extra δόση +0.60€", "Σιρόπι βανίλια +0.30€"] } },
    { title: "Freddo Cappuccino", category: "Καφέδες", price: 2.4, rating: 4.8, emoji: "🥤", badge: "Δημοφιλές", description: "Κρύος cappuccino με πλούσια κρέμα.", options: { sweetness: ["Σκέτος", "Μέτριος", "Γλυκός"], milk: ["Κανονικό αφρόγαλα", "Φυτικό γάλα +0.40€"], extras: ["Extra δόση +0.60€", "Σιρόπι καραμέλα +0.30€"] } },
    { title: "Energy Combo", category: "Προσφορές", price: 4.2, oldPrice: 5.4, rating: 4.9, emoji: "⚡", badge: "-22%", promo: true, description: "Καφές + σφολιάτα σε ειδική τιμή.", options: { sweetness: ["Σκέτος", "Μέτριος", "Γλυκός"], milk: ["Χωρίς γάλα", "Με γάλα"], extras: ["Extra δόση +0.60€", "Ζεστή σφολιάτα"] } },
  ];
  return base.map((product) => normalizeProduct(product, storeId));
}

function createDemoStores() {
  return [
    {
      id: "store-1",
      status: "approved",
      active: true,
      createdAt: new Date().toISOString(),
      approvedAt: new Date().toISOString(),
      owner: { name: "Μιχάλης Ξ.", phone: "6900000001", email: "owner1@example.com", password: "1234", idNumber: "ΑΒ123456", taxNumber: "123456789" },
      profile: { name: "Kissamos Coffee", subtitle: "Specialty coffee & snacks", logo: "", logoEmoji: "☕", phone: "28220 00000", address: "Κέντρο Κισσάμου", area: "Κίσσαμος", openHours: "08:00 - 23:30", deliveryTime: "25-35'", description: "Καφέδες, ροφήματα, σφολιάτες και combos." },
      categories: DEFAULT_CATEGORIES,
      products: createDefaultProducts("store-1"),
    },
    {
      id: "store-2",
      status: "approved",
      active: true,
      createdAt: new Date().toISOString(),
      approvedAt: new Date().toISOString(),
      owner: { name: "Ελένη Κ.", phone: "6900000002", email: "owner2@example.com", password: "1234", idNumber: "ΑΒ654321", taxNumber: "987654321" },
      profile: { name: "Fresh Bite", subtitle: "Sandwiches, brunch & juices", logo: "", logoEmoji: "🥪", phone: "28220 11111", address: "Παραλιακή Κισσάμου", area: "Κίσσαμος", openHours: "09:00 - 22:00", deliveryTime: "30-40'", description: "Σάντουιτς, χυμοί, γλυκά και γρήγορο brunch." },
      categories: ["Προσφορές", "Σάντουιτς", "Ροφήματα", "Γλυκά", "Snacks"],
      products: [
        normalizeProduct({ title: "Club Sandwich", category: "Σάντουιτς", price: 5.8, rating: 4.8, emoji: "🥪", badge: "Meal", description: "Κοτόπουλο, μπέικον, τυρί, ντομάτα και πατάτες.", options: { sweetness: ["Κανονικό"], milk: ["Με πατάτες", "Χωρίς πατάτες"], extras: ["Extra sauce +0.40€", "Extra cheddar +0.50€"] } }, "store-2"),
        normalizeProduct({ title: "Φυσικός Χυμός", category: "Ροφήματα", price: 3, rating: 4.9, emoji: "🍊", badge: "Fresh", description: "Φρεσκοστυμμένος χυμός πορτοκάλι.", options: { sweetness: ["Χωρίς ζάχαρη"], milk: ["Με πάγο", "Χωρίς πάγο"], extras: ["Με τζίντζερ +0.30€"] } }, "store-2"),
        normalizeProduct({ title: "Brunch Deal", category: "Προσφορές", price: 6.5, oldPrice: 8, promo: true, rating: 4.7, emoji: "🍽️", badge: "Combo", description: "Club sandwich + φυσικός χυμός.", options: { sweetness: ["Κανονικό"], milk: ["Με πατάτες"], extras: ["Extra sauce +0.40€"] } }, "store-2"),
      ],
    },
  ];
}

function emptyCustomerForm() {
  return { name: "", phone: "", address: "", floor: "", notes: "", changeFor: "", deliveryType: "delivery", paymentMethod: "cash", scheduledTime: "", contactPreference: "phone", loyaltyPointsToRedeem: "" };
}

function emptyAuthForm() {
  return { name: "", phone: "", email: "", password: "", address: "", floor: "" };
}

function emptyDriverForm() {
  return { name: "", phone: "", email: "", password: "", vehicleType: "motorbike", vehiclePlate: "", idNumber: "", taxNumber: "", iban: "", area: "", emergencyPhone: "", notes: "" };
}

function emptyMerchantApplication() {
  return { ownerName: "", ownerPhone: "", ownerEmail: "", ownerPassword: "", ownerIdNumber: "", ownerTaxNumber: "", storeName: "", storePhone: "", storeAddress: "", storeArea: "", storeType: "Καφέ / Take away", iban: "", notes: "" };
}

function newProductDraft(category = "Καφέδες") {
  return { id: null, title: "", category, price: "", oldPrice: "", rating: "4.8", time: "10-15'", image: "", emoji: "☕", badge: "", active: true, promo: false, offerType: "standard", bundleProductId: "", bundleLabel: "", description: "", options: { sweetness: "Κανονικό", milk: "Κανονικό", extras: "Χωρίς έξτρα" } };
}

function productToDraft(product) {
  return { ...product, offerType: product.offerType || "standard", bundleProductId: product.bundleProductId || "", bundleLabel: product.bundleLabel || "", price: String(product.price ?? ""), oldPrice: product.oldPrice == null ? "" : String(product.oldPrice), rating: String(product.rating ?? 4.8), options: { sweetness: (product.options?.sweetness || []).join(", "), milk: (product.options?.milk || []).join(", "), extras: (product.options?.extras || []).join(", ") } };
}

function normalizeUser(user) {
  return {
    id: user.id || safeId("user"),
    name: String(user.name || "").trim(),
    phone: String(user.phone || "").trim(),
    email: String(user.email || "").trim(),
    password: String(user.password || "").trim(),
    address: String(user.address || "").trim(),
    floor: String(user.floor || "").trim(),
    loyaltyPoints: Number(user.loyaltyPoints || 0),
    favorites: Array.isArray(user.favorites) ? user.favorites : [],
    status: user.status || "active",
    banReason: user.banReason || "",
    bannedAt: user.bannedAt || "",
    createdAt: user.createdAt || new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
}

function normalizeDriver(driver) {
  return { id: driver.id || safeId("driver"), name: String(driver.name || "").trim(), phone: String(driver.phone || "").trim(), email: String(driver.email || "").trim(), password: String(driver.password || "").trim(), vehicleType: driver.vehicleType || "motorbike", vehiclePlate: String(driver.vehiclePlate || "").trim(), idNumber: String(driver.idNumber || "").trim(), taxNumber: String(driver.taxNumber || "").trim(), iban: String(driver.iban || "").trim(), area: String(driver.area || "").trim(), emergencyPhone: String(driver.emergencyPhone || "").trim(), notes: String(driver.notes || "").trim(), status: driver.status || "pending", online: Boolean(driver.online), liveTrackingEnabled: Boolean(driver.liveTrackingEnabled), lastLocation: normalizeLocation(driver.lastLocation), trackingError: driver.trackingError || "", trackingUpdatedAt: driver.trackingUpdatedAt || driver.lastLocation?.at || "", activeOrderId: driver.activeOrderId || "", completedDeliveries: Number(driver.completedDeliveries || 0), rating: Number(driver.rating || 5), createdAt: driver.createdAt || new Date().toISOString(), approvedAt: driver.approvedAt || "" };
}

function getAvailablePaymentOptions(deliveryType, platform) {
  const options = [];
  if (deliveryType === "delivery") {
    if (platform.payCashEnabled !== false) options.push("cash");
    if (platform.payCardDeliveryEnabled !== false) options.push("card_on_delivery");
  }
  if (deliveryType === "pickup" && platform.payStoreCardEnabled !== false) options.push("store_card");
  return options;
}

function canDriverClaimOrder(order) {
  return order?.deliveryType !== "pickup" && !order.driverId && !["completed", "cancelled"].includes(order.status);
}

function calculateDeliveryEta(drivers, platform) {
  const online = drivers.filter((driver) => driver.status === "approved" && driver.online);
  const busy = online.filter((driver) => driver.activeOrderId).length;
  const prep = Number(platform.driverPickupPrepMinutes || 10);
  const eta = Math.max(prep + 5, Number(platform.driverBaseEtaMinutes || 25) + busy * Number(platform.driverBusyExtraMinutes || 8));
  const now = Date.now();
  return { pickupAt: new Date(now + prep * 60000).toISOString(), deliveryAt: new Date(now + eta * 60000).toISOString(), etaMinutes: eta, onlineDrivers: online.length, busyDrivers: busy };
}

function deliveryFeeForOrder(order) {
  if (!order || order.deliveryType === "pickup") return 0;
  return Number(order.totals?.deliveryFee || 0);
}

function driverEarningForOrder(order, platform) {
  if (!order || order.status !== "completed" || !order.driverId || order.deliveryType === "pickup") return 0;
  if (order.deliveryAssignment?.driverPayout != null) return Number(order.deliveryAssignment.driverPayout || 0);
  return roundMoney(deliveryFeeForOrder(order) * (Number(platform.driverCommissionPercent || 40) / 100));
}

function driverRatingBonusForOrder(order, platform) {
  if (!order || order.status !== "completed" || !order.driverId || platform.driverRewardEnabled === false) return 0;
  const rating = Number(order.driverRating?.rating || 0);
  const minRating = Number(platform.driverRewardMinRating || 4.8);
  if (rating < minRating) return 0;
  return roundMoney(Number(platform.driverRewardBonusPerOrder || 0));
}

function driverTotalEarningForOrder(order, platform) {
  return roundMoney(driverEarningForOrder(order, platform) + driverRatingBonusForOrder(order, platform));
}

function loyaltyDiscountForOrder(order) {
  return Number(order?.totals?.loyaltyDiscount || order?.loyaltyDiscount || 0);
}

function platformFeesForOrder(order) {
  return Number(order?.totals?.serviceFee || 0) + deliveryFeeForOrder(order);
}

function platformFeesAfterLoyaltyForOrder(order) {
  return roundMoney(Math.max(0, platformFeesForOrder(order) - loyaltyDiscountForOrder(order)));
}

function platformNetForOrder(order, platform) {
  return roundMoney(platformFeesAfterLoyaltyForOrder(order) - driverTotalEarningForOrder(order, platform));
}

function driverWalletStats(driverId, orders, withdrawals, platform) {
  const completed = orders.filter((order) => order.driverId === driverId && order.status === "completed");
  const baseEarned = completed.reduce((sum, order) => sum + driverEarningForOrder(order, platform), 0);
  const ratingBonus = completed.reduce((sum, order) => sum + driverRatingBonusForOrder(order, platform), 0);
  const earned = baseEarned + ratingBonus;
  const ratedOrders = completed.filter((order) => order.driverRating?.rating);
  const averageRating = ratedOrders.length ? ratedOrders.reduce((sum, order) => sum + Number(order.driverRating.rating || 0), 0) / ratedOrders.length : 0;
  const requests = withdrawals.filter((request) => request.driverId === driverId);
  const pending = requests.filter((request) => request.status === "pending").reduce((sum, request) => sum + Number(request.amount || 0), 0);
  const paid = requests.filter((request) => request.status === "approved").reduce((sum, request) => sum + Number(request.amount || 0), 0);
  return { earned: roundMoney(earned), baseEarned: roundMoney(baseEarned), ratingBonus: roundMoney(ratingBonus), pending: roundMoney(pending), paid: roundMoney(paid), available: roundMoney(Math.max(0, earned - pending - paid)), completedOrders: completed.length, ratedOrders: ratedOrders.length, averageRating: roundMoney(averageRating), requests };
}

function calculateEarnedLoyaltyPoints(amount, platform) {
  if (platform.loyaltyEnabled === false) return 0;
  const earnPoints = Number(platform.loyaltyEarnPoints || 0);
  const earnEuro = Number(platform.loyaltyEarnEuro || 1);
  if (earnPoints <= 0 || earnEuro <= 0) return 0;
  return Math.max(0, Math.floor((Number(amount || 0) / earnEuro) * earnPoints));
}

function calculateLoyaltyUsage(requestedPoints, availablePoints, eligibleAmount, platform) {
  if (platform.loyaltyEnabled === false || platform.loyaltyRedeemEnabled === false) return { points: 0, discount: 0, reason: "disabled" };
  const requested = Math.floor(Number(requestedPoints || 0));
  const available = Math.floor(Number(availablePoints || 0));
  const redeemPoints = Number(platform.loyaltyRedeemPoints || 0);
  const redeemEuro = Number(platform.loyaltyRedeemEuro || 0);
  const minPoints = Math.floor(Number(platform.loyaltyMinRedeemPoints || 0));
  const maxPercent = Math.min(100, Math.max(0, Number(platform.loyaltyMaxDiscountPercent ?? 100)));
  const baseAmount = Math.max(0, Number(eligibleAmount || 0));
  if (requested <= 0 || available <= 0 || redeemPoints <= 0 || redeemEuro <= 0 || baseAmount <= 0) return { points: 0, discount: 0, reason: "empty" };
  const usableRequested = Math.min(requested, available);
  if (usableRequested < minPoints) return { points: 0, discount: 0, reason: "min" };
  const valuePerPoint = redeemEuro / redeemPoints;
  const discount = roundMoney(Math.min(usableRequested * valuePerPoint, baseAmount * (maxPercent / 100), baseAmount));
  const points = Math.min(usableRequested, Math.ceil(discount / valuePerPoint));
  return { points, discount, reason: discount > 0 ? "applied" : "empty" };
}

function loyaltyTier(points, platform) {
  const value = Number(points || 0);
  if (value >= Number(platform.loyaltyTierBlack || 1500)) return { key: "black", name: "Black", icon: "💎", next: null, multiplier: 1.3 };
  if (value >= Number(platform.loyaltyTierGold || 750)) return { key: "gold", name: "Gold", icon: "🏆", next: Number(platform.loyaltyTierBlack || 1500), multiplier: 1.2 };
  if (value >= Number(platform.loyaltyTierSilver || 250)) return { key: "silver", name: "Silver", icon: "🥈", next: Number(platform.loyaltyTierGold || 750), multiplier: 1.1 };
  return { key: "starter", name: "Starter", icon: "⭐", next: Number(platform.loyaltyTierSilver || 250), multiplier: 1 };
}

function loyaltyProgress(points, platform) {
  const tier = loyaltyTier(points, platform);
  if (!tier.next) return 100;
  const previous = tier.key === "gold" ? Number(platform.loyaltyTierGold || 750) : tier.key === "silver" ? Number(platform.loyaltyTierSilver || 250) : 0;
  const span = Math.max(1, tier.next - previous);
  return Math.min(100, Math.max(0, ((Number(points || 0) - previous) / span) * 100));
}

function calculateStreak(orders) {
  const days = Array.from(new Set((orders || []).filter((order) => order.status !== "cancelled").map((order) => new Date(order.createdAt).toISOString().slice(0, 10)))).sort().reverse();
  if (!days.length) return 0;
  let streak = 0;
  let cursor = new Date();
  for (let index = 0; index < 14; index += 1) {
    const key = cursor.toISOString().slice(0, 10);
    if (days.includes(key)) streak += 1;
    else if (index > 0) break;
    cursor.setDate(cursor.getDate() - 1);
  }
  return streak;
}

function offerLabel(product, products = []) {
  if (product?.offerType === "bogo") return "1+1 δώρο";
  if (product?.offerType === "bundle") {
    const item = products.find((row) => row.id === product.bundleProductId);
    return product.bundleLabel || `Combo με ${item?.title || "άλλο προϊόν"}`;
  }
  return product?.badge || "";
}

function playNewOrderSound(seconds = 5, volume = 0.9) {
  if (typeof window === "undefined") return;
  const AudioContextClass = window.AudioContext || window.webkitAudioContext;
  if (!AudioContextClass) return;
  const safeVolume = Math.min(1, Math.max(0.05, Number(volume || 0.9)));
  try {
    const ctx = new AudioContextClass();
    const master = ctx.createGain();
    const compressor = ctx.createDynamicsCompressor();
    master.gain.value = safeVolume;
    compressor.threshold.value = -18;
    compressor.knee.value = 24;
    compressor.ratio.value = 10;
    compressor.attack.value = 0.003;
    compressor.release.value = 0.22;
    master.connect(compressor);
    compressor.connect(ctx.destination);

    const start = ctx.currentTime;
    const end = start + seconds;
    for (let t = start; t < end; t += 0.52) {
      const high = ctx.createOscillator();
      const low = ctx.createOscillator();
      const gain = ctx.createGain();
      high.type = "square";
      low.type = "sawtooth";
      high.frequency.setValueAtTime(980, t);
      high.frequency.exponentialRampToValueAtTime(1720, t + 0.16);
      low.frequency.setValueAtTime(440, t);
      low.frequency.exponentialRampToValueAtTime(660, t + 0.16);
      gain.gain.setValueAtTime(0.0001, t);
      gain.gain.exponentialRampToValueAtTime(0.95, t + 0.025);
      gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.32);
      high.connect(gain);
      low.connect(gain);
      gain.connect(master);
      high.start(t);
      low.start(t);
      high.stop(t + 0.34);
      low.stop(t + 0.34);
    }

    const finishTone = ctx.createOscillator();
    const finishGain = ctx.createGain();
    finishTone.type = "triangle";
    finishTone.frequency.setValueAtTime(1480, end + 0.05);
    finishGain.gain.setValueAtTime(0.0001, end + 0.05);
    finishGain.gain.exponentialRampToValueAtTime(0.75, end + 0.08);
    finishGain.gain.exponentialRampToValueAtTime(0.0001, end + 0.75);
    finishTone.connect(finishGain);
    finishGain.connect(master);
    finishTone.start(end + 0.05);
    finishTone.stop(end + 0.8);

    window.setTimeout(() => ctx.close?.(), Math.round((seconds + 1.2) * 1000));
  } catch (error) {
    console.warn("New order sound was blocked by the browser", error);
  }
}

function loyaltyRuleText(platform) {
  if (platform.loyaltyEnabled === false) return "Το loyalty είναι απενεργοποιημένο.";
  return `${Number(platform.loyaltyEarnPoints || 0)} πόντος ανά ${formatEuro(platform.loyaltyEarnEuro || 1)} · ${Number(platform.loyaltyRedeemPoints || 0)} πόντοι = ${formatEuro(platform.loyaltyRedeemEuro || 0)} έκπτωση μόνο στα fees`; 
}

function getStoreStats(storeId, orders, platform) {
  const rows = orders.filter((order) => order.storeId === storeId && order.status !== "cancelled");
  const productRevenue = rows.reduce((sum, order) => sum + Number(order.totals?.subtotal || 0), 0);
  const serviceFees = rows.reduce((sum, order) => sum + Number(order.totals?.serviceFee || 0), 0);
  const deliveryFees = rows.reduce((sum, order) => sum + deliveryFeeForOrder(order), 0);
  const driverEarnings = rows.reduce((sum, order) => sum + driverEarningForOrder(order, platform), 0);
  const loyaltyDiscounts = rows.reduce((sum, order) => sum + loyaltyDiscountForOrder(order), 0);
  return { orders: rows.length, active: rows.filter((order) => !["completed", "cancelled"].includes(order.status)).length, completed: rows.filter((order) => order.status === "completed").length, productRevenue, serviceFees, deliveryFees, loyaltyDiscounts, driverEarnings, platformNet: serviceFees + deliveryFees - loyaltyDiscounts - driverEarnings, avgOrder: rows.length ? rows.reduce((sum, order) => sum + Number(order.totals?.total || 0), 0) / rows.length : 0 };
}

function runDevTests() {
  const extra = calculateExtraPriceFromChoices({ milk: "Φυτικό +0.40€", extras: ["Extra +0.60€"] });
  console.assert(extra === 1, `extra price expected 1, got ${extra}`);
  const order = { status: "completed", deliveryType: "delivery", driverId: "d1", totals: { deliveryFee: 1, serviceFee: 0.3 }, deliveryAssignment: {} };
  console.assert(driverEarningForOrder(order, PLATFORM_DEFAULTS) === 0.4, "driver earning must be 40% of delivery fee");
  console.assert(platformNetForOrder(order, PLATFORM_DEFAULTS) === 0.9, "platform net must be service + 60% delivery");
  const loyaltyFeeOrder = { ...order, totals: { deliveryFee: 1, serviceFee: 0.3, loyaltyDiscount: 0.3 } };
  console.assert(platformNetForOrder(loyaltyFeeOrder, PLATFORM_DEFAULTS) === 0.6, "loyalty discount must reduce only platform fees, not store subtotal");
  const storeStats = getStoreStats("s1", [{ ...order, storeId: "s1", totals: { ...order.totals, subtotal: 5, total: 6.3 } }], PLATFORM_DEFAULTS);
  console.assert(storeStats.productRevenue === 5, "store revenue must be product subtotal only");
  console.assert(canDriverClaimOrder({ deliveryType: "delivery", status: "new", driverId: "" }) === true, "new delivery order must be claimable");
  console.assert(canDriverClaimOrder({ deliveryType: "pickup", status: "new", driverId: "" }) === false, "pickup order must not be claimable by driver");
  console.assert(calculateEarnedLoyaltyPoints(10, PLATFORM_DEFAULTS) === 10, "loyalty earn must be 1 point per euro by default");
  const compactedOrder = compactOrderForStorage({ storeSnapshot: { logo: "data:image/png;base64,AAA" }, items: [{ image: "data:image/png;base64,BBB", title: "x" }], statusHistory: Array(30).fill({ status: "new" }), driverEvents: Array(30).fill({ type: "x" }) });
  console.assert(compactedOrder.storeSnapshot.logo === "" && compactedOrder.items[0].image === "" && compactedOrder.statusHistory.length === 20, "orders must be compacted before localStorage");
  const loyalty = calculateLoyaltyUsage(100, 150, 1.3, PLATFORM_DEFAULTS);
  console.assert(loyalty.points === 100 && loyalty.discount === 1, "100 loyalty points must redeem 1 euro from platform fees by default");
}

if (typeof console !== "undefined") runDevTests();

function App() {
  const [platform, setPlatform] = useState(() => ({ ...PLATFORM_DEFAULTS, ...readStorage("rr_platform_v1", PLATFORM_DEFAULTS) }));
  const [lang, setLang] = useState(() => readStorage("rr_lang_v1", "el"));
  const [stores, setStores] = useState(() => readStorage("rr_stores_v1", createDemoStores()));
  const [applications, setApplications] = useState(() => readStorage("rr_store_apps_v1", []));
  const [users, setUsers] = useState(() => readStorage("rr_users_v1", []));
  const [currentUserId, setCurrentUserId] = useState(() => readStorage("rr_current_user_v1", ""));
  const [drivers, setDrivers] = useState(() => readStorage("rr_drivers_v1", []).map(normalizeDriver));
  const [currentDriverId, setCurrentDriverId] = useState(() => readStorage("rr_current_driver_v1", ""));
  const [driverWithdrawals, setDriverWithdrawals] = useState(() => readStorage("rr_driver_withdrawals_v1", []));
  const [orders, setOrders] = useState(() => readStorage("rr_orders_v1", []));

  const [selectedStoreId, setSelectedStoreId] = useState("all");
  const [activeCategory, setActiveCategory] = useState("Προσφορές");
  const [query, setQuery] = useState("");
  const [cart, setCart] = useState([]);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [selectedChoices, setSelectedChoices] = useState({ sweetness: "", milk: "", extras: [], note: "" });
  const [checkoutOpen, setCheckoutOpen] = useState(false);
  const [trackingOrder, setTrackingOrder] = useState(null);
  const [trackId, setTrackId] = useState("");

  const [authOpen, setAuthOpen] = useState(false);
  const [authMode, setAuthMode] = useState("login");
  const [authForm, setAuthForm] = useState(() => emptyAuthForm());
  const [authError, setAuthError] = useState("");
  const [accountOpen, setAccountOpen] = useState(false);
  const [customerForm, setCustomerForm] = useState(() => emptyCustomerForm());

  const [driverOpen, setDriverOpen] = useState(false);
  const [driverMode, setDriverMode] = useState("login");
  const [driverForm, setDriverForm] = useState(() => emptyDriverForm());
  const [driverError, setDriverError] = useState("");

  const [merchantOpen, setMerchantOpen] = useState(false);
  const [merchantMode, setMerchantMode] = useState("login");
  const [merchantForm, setMerchantForm] = useState({ phone: "", password: "" });
  const [merchantApplication, setMerchantApplication] = useState(() => emptyMerchantApplication());
  const [merchantError, setMerchantError] = useState("");
  const [currentMerchantStoreId, setCurrentMerchantStoreId] = useState(() => readStorage("rr_current_merchant_store_v1", ""));

  const [platformOpen, setPlatformOpen] = useState(false);
  const [platformUnlocked, setPlatformUnlocked] = useState(false);
  const [platformPin, setPlatformPin] = useState("");
  const [legalPage, setLegalPage] = useState(null);
  const [accessMenuOpen, setAccessMenuOpen] = useState(false);

  useEffect(() => saveStorage("rr_platform_v1", platform), [platform]);
  useEffect(() => saveStorage("rr_lang_v1", lang), [lang]);
  useEffect(() => {
    if (typeof window === "undefined") return undefined;
    let timer = null;
    let observer = null;
    const run = () => {
      if (lang === "en") translateDomTree(document.body);
    };
    if (lang === "en") {
      timer = window.setTimeout(run, 0);
      observer = new MutationObserver(() => {
        if (timer) window.clearTimeout(timer);
        timer = window.setTimeout(run, 25);
      });
      observer.observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["placeholder", "title", "aria-label"] });
    }
    return () => {
      if (timer) window.clearTimeout(timer);
      if (observer) observer.disconnect();
    };
  }, [lang, platformOpen, authOpen, accountOpen, checkoutOpen, trackingOrder, driverOpen, merchantOpen, legalPage, selectedProduct, orders, stores, users, drivers]);
  useEffect(() => saveStorage("rr_stores_v1", stores), [stores]);
  useEffect(() => saveStorage("rr_store_apps_v1", applications), [applications]);
  useEffect(() => saveStorage("rr_users_v1", users), [users]);
  useEffect(() => saveStorage("rr_current_user_v1", currentUserId || ""), [currentUserId]);
  useEffect(() => saveStorage("rr_drivers_v1", drivers), [drivers]);
  useEffect(() => saveStorage("rr_current_driver_v1", currentDriverId || ""), [currentDriverId]);
  useEffect(() => saveStorage("rr_driver_withdrawals_v1", driverWithdrawals), [driverWithdrawals]);
  useEffect(() => saveStorage("rr_orders_v1", orders), [orders]);
  useEffect(() => saveStorage("rr_current_merchant_store_v1", currentMerchantStoreId || ""), [currentMerchantStoreId]);

  const approvedStores = useMemo(() => stores.filter((store) => store.status === "approved" && store.active !== false), [stores]);
  const selectedStore = useMemo(() => approvedStores.find((store) => store.id === selectedStoreId) || null, [approvedStores, selectedStoreId]);
  const allProducts = useMemo(() => approvedStores.flatMap((store) => store.products.filter((product) => product.active !== false).map((product) => ({ ...product, storeName: store.profile.name, storeLogo: store.profile.logo || "", storeLogoEmoji: store.profile.logoEmoji, storeArea: store.profile.area }))), [approvedStores]);
  const categories = useMemo(() => selectedStore ? selectedStore.categories : Array.from(new Set(["Όλα", "Προσφορές", ...approvedStores.flatMap((store) => store.categories)])), [selectedStore, approvedStores]);
  const currentUser = useMemo(() => users.find((user) => user.id === currentUserId) || null, [users, currentUserId]);
  const currentDriver = useMemo(() => drivers.find((driver) => driver.id === currentDriverId) || null, [drivers, currentDriverId]);
  const currentMerchantStore = useMemo(() => stores.find((store) => store.id === currentMerchantStoreId) || null, [stores, currentMerchantStoreId]);
  const latestStateRef = useRef({});

  useEffect(() => {
    latestStateRef.current = { platform, lang, stores, applications, users, currentUserId, drivers, currentDriverId, driverWithdrawals, orders, currentMerchantStoreId };
  }, [platform, lang, stores, applications, users, currentUserId, drivers, currentDriverId, driverWithdrawals, orders, currentMerchantStoreId]);

  useEffect(() => {
    if (typeof window === "undefined" || !window.__RR_API_ENABLED__) return undefined;
    let cancelled = false;
    let busy = false;
    async function pullServerState() {
      if (busy) return;
      busy = true;
      try {
        const response = await fetch("./api/state.php?pull=1", {
          cache: "no-store",
          credentials: "same-origin",
          headers: { "X-RR-Sync-Token": String(window.__RR_SYNC_TOKEN__ || "") },
        });
        const data = await response.json();
        if (cancelled || !data.ok || !data.state) return;
        const state = data.state;
        const latest = latestStateRef.current;
        if (Object.prototype.hasOwnProperty.call(state, "rr_platform_v1") && !sameJson(state.rr_platform_v1, latest.platform)) setPlatform({ ...PLATFORM_DEFAULTS, ...state.rr_platform_v1 });
        if (Object.prototype.hasOwnProperty.call(state, "rr_stores_v1") && !sameJson(state.rr_stores_v1, latest.stores)) setStores(Array.isArray(state.rr_stores_v1) ? state.rr_stores_v1 : createDemoStores());
        if (Object.prototype.hasOwnProperty.call(state, "rr_store_apps_v1") && !sameJson(state.rr_store_apps_v1, latest.applications)) setApplications(Array.isArray(state.rr_store_apps_v1) ? state.rr_store_apps_v1 : []);
        if (Object.prototype.hasOwnProperty.call(state, "rr_users_v1") && !sameJson(state.rr_users_v1, latest.users)) setUsers(Array.isArray(state.rr_users_v1) ? state.rr_users_v1 : []);
        if (Object.prototype.hasOwnProperty.call(state, "rr_drivers_v1") && !sameJson(state.rr_drivers_v1, latest.drivers)) setDrivers(Array.isArray(state.rr_drivers_v1) ? state.rr_drivers_v1.map(normalizeDriver) : []);
        if (Object.prototype.hasOwnProperty.call(state, "rr_driver_withdrawals_v1") && !sameJson(state.rr_driver_withdrawals_v1, latest.driverWithdrawals)) setDriverWithdrawals(Array.isArray(state.rr_driver_withdrawals_v1) ? state.rr_driver_withdrawals_v1 : []);
        if (Object.prototype.hasOwnProperty.call(state, "rr_orders_v1") && !sameJson(state.rr_orders_v1, latest.orders)) setOrders(Array.isArray(state.rr_orders_v1) ? state.rr_orders_v1 : []);
      } catch (error) {
        console.warn("Road Runner MySQL pull failed", error);
      } finally {
        busy = false;
      }
    }
    const id = window.setInterval(pullServerState, 4500);
    pullServerState();
    return () => { cancelled = true; window.clearInterval(id); };
  }, []);

  const filteredProducts = useMemo(() => {
    const source = selectedStore ? selectedStore.products.filter((p) => p.active !== false).map((p) => ({ ...p, storeName: selectedStore.profile.name, storeLogo: selectedStore.profile.logo || "", storeLogoEmoji: selectedStore.profile.logoEmoji, storeArea: selectedStore.profile.area })) : allProducts;
    const term = query.trim().toLowerCase();
    return source.filter((product) => {
      const categoryMatch = activeCategory === "Όλα" || product.category === activeCategory || (activeCategory === "Προσφορές" && (product.promo || product.oldPrice));
      const searchMatch = !term || product.title.toLowerCase().includes(term) || product.description.toLowerCase().includes(term) || product.storeName.toLowerCase().includes(term);
      return categoryMatch && searchMatch;
    });
  }, [selectedStore, allProducts, activeCategory, query]);

  const cartStore = useMemo(() => stores.find((store) => store.id === cart[0]?.storeId) || null, [stores, cart]);
  const subtotal = cart.reduce((sum, item) => sum + Number(item.lineTotal || 0), 0);
  const deliveryFee = customerForm.deliveryType === "delivery" && subtotal > 0 && subtotal < Number(platform.freeDeliveryFrom || 0) ? Number(platform.deliveryFee || 0) : 0;
  const serviceFee = subtotal > 0 ? Number(platform.serviceFee || 0) : 0;
  const platformFeeAmount = deliveryFee + serviceFee;
  const loyaltyEligibleAmount = platformFeeAmount;
  const loyaltyUsage = calculateLoyaltyUsage(customerForm.loyaltyPointsToRedeem, currentUser?.loyaltyPoints || 0, loyaltyEligibleAmount, platform);
  const loyaltyDiscount = Math.min(loyaltyUsage.discount, platformFeeAmount);
  const total = roundMoney(Math.max(0, subtotal + deliveryFee + serviceFee - loyaltyDiscount));
  const earnedPointsPreview = calculateEarnedLoyaltyPoints(subtotal, platform);
  const customerBlockedReason = currentUser?.status === "banned" ? `Ο λογαριασμός σου έχει αποκλειστεί: ${currentUser.banReason || "χωρίς αιτιολογία"}` : currentUser && cartStore && isCustomerBannedFromStore(currentUser, cartStore) ? `Το κατάστημα ${cartStore.profile.name} έχει αποκλείσει αυτόν τον πελάτη.` : "";
  const canOrder = cart.length > 0 && subtotal >= Number(platform.minOrder || 0) && !customerBlockedReason;
  const availablePaymentOptions = getAvailablePaymentOptions(customerForm.deliveryType, platform);

  const availableDriverOrders = useMemo(() => orders.filter((order) => canDriverClaimOrder(order)), [orders]);
  const currentDriverOrders = useMemo(() => currentDriver ? orders.filter((order) => order.driverId === currentDriver.id && !["completed", "cancelled"].includes(order.status)) : [], [orders, currentDriver]);
  const currentDriverWallet = useMemo(() => currentDriver ? driverWalletStats(currentDriver.id, orders, driverWithdrawals, platform) : null, [currentDriver, orders, driverWithdrawals, platform]);
  const customerOrders = useMemo(() => currentUser ? orders.filter((order) => order.userId === currentUser.id || order.customer?.phone === currentUser.phone) : [], [orders, currentUser]);

  const platformStats = useMemo(() => {
    const valid = orders.filter((order) => order.status !== "cancelled");
    const productRevenue = valid.reduce((sum, order) => sum + Number(order.totals?.subtotal || 0), 0);
    const serviceFees = valid.reduce((sum, order) => sum + Number(order.totals?.serviceFee || 0), 0);
    const deliveryFees = valid.reduce((sum, order) => sum + deliveryFeeForOrder(order), 0);
    const driverEarnings = valid.reduce((sum, order) => sum + driverTotalEarningForOrder(order, platform), 0);
    return {
      stores: stores.length,
      approvedStores: stores.filter((store) => store.status === "approved").length,
      pendingStores: applications.filter((app) => app.status === "pending").length,
      products: allProducts.length,
      orders: orders.length,
      activeOrders: orders.filter((order) => !["completed", "cancelled"].includes(order.status)).length,
      productRevenue,
      serviceFees,
      deliveryFees,
      driverEarnings,
      platformNet: serviceFees + deliveryFees - valid.reduce((sum, order) => sum + loyaltyDiscountForOrder(order), 0) - driverEarnings,
      loyaltyDiscounts: valid.reduce((sum, order) => sum + Number(order.totals?.loyaltyDiscount || order.loyaltyDiscount || 0), 0),
      loyaltyPointsIssued: valid.reduce((sum, order) => sum + Number(order.loyaltyEarned || 0), 0),
      loyaltyPointsRedeemed: valid.reduce((sum, order) => sum + Number(order.loyaltyRedeemed || 0), 0),
      driverPendingWithdrawals: driverWithdrawals.filter((request) => request.status === "pending").reduce((sum, request) => sum + Number(request.amount || 0), 0),
      onlineDrivers: drivers.filter((driver) => driver.status === "approved" && driver.online).length,
      approvedDrivers: drivers.filter((driver) => driver.status === "approved").length,
      users: users.length,
      activeUsers: users.filter((user) => user.status !== "banned" && user.status !== "suspended").length,
      bannedUsers: users.filter((user) => user.status === "banned" || user.status === "suspended").length,
      returningUsers: users.filter((user) => valid.filter((order) => order.userId === user.id).length > 1).length,
      completedOrders: orders.filter((order) => order.status === "completed").length,
      cancelledOrders: orders.filter((order) => order.status === "cancelled").length,
      suspendedStores: stores.filter((store) => store.status === "suspended" || store.status === "banned").length,
      hiddenStores: stores.filter((store) => store.active === false).length,
      avgBasket: valid.length ? valid.reduce((sum, order) => sum + Number(order.totals?.total || 0), 0) / valid.length : 0,
    };
  }, [orders, stores, applications, allProducts, driverWithdrawals, drivers, platform, users]);

  function openProduct(product) {
    const store = stores.find((row) => row.id === product.storeId);
    setSelectedProduct({ ...product, storeName: store?.profile.name || product.storeName, storeLogo: store?.profile.logo || product.storeLogo || "", storeLogoEmoji: store?.profile.logoEmoji || product.storeLogoEmoji || "🏪" });
    setSelectedChoices({ sweetness: product.options?.sweetness?.[0] || "", milk: product.options?.milk?.[0] || "", extras: [], note: "" });
  }

  function addToCart(product, choices) {
    const store = stores.find((row) => row.id === product.storeId);
    if (!store || store.status !== "approved" || product.active === false) return;
    const finalChoices = choices || { sweetness: product.options?.sweetness?.[0] || "", milk: product.options?.milk?.[0] || "", extras: [], note: "" };
    const extraPrice = calculateExtraPriceFromChoices(finalChoices);
    const unitPrice = roundMoney(Number(product.price) + extraPrice);
    const optionText = [finalChoices.sweetness, finalChoices.milk, ...(finalChoices.extras || [])].filter(Boolean).join(" · ");
    const note = String(finalChoices.note || "").trim();
    const key = `${product.storeId}-${product.id}-${optionText}-${note}`;
    setCart((current) => {
      const base = current.length && current[0].storeId !== product.storeId ? [] : current;
      const existing = base.find((item) => item.key === key);
      if (existing) return base.map((item) => item.key === key ? { ...item, qty: item.qty + 1, bonusQty: item.offerType === "bogo" ? item.qty + 1 : item.bonusQty || 0, lineTotal: roundMoney(unitPrice * (item.qty + 1)) } : item);
      return [...base, { key, storeId: product.storeId, storeName: store.profile.name, storeLogo: store.profile.logo || "", storeLogoEmoji: store.profile.logoEmoji, productId: product.id, title: product.title, image: product.image || "", emoji: product.emoji, optionText, productNote: note, unitPrice, qty: 1, bonusQty: product.offerType === "bogo" ? 1 : 0, offerType: product.offerType || "standard", bundleProductId: product.bundleProductId || "", bundleLabel: offerLabel(product, store.products), lineTotal: unitPrice }];
    });
  }

  function updateQty(key, change) {
    setCart((current) => current.map((item) => { const qty = Math.max(0, item.qty + change); return item.key === key ? { ...item, qty, bonusQty: item.offerType === "bogo" ? qty : item.bonusQty || 0, lineTotal: roundMoney(item.unitPrice * qty) } : item; }).filter((item) => item.qty > 0));
  }

  function updateItemNote(key, productNote) {
    setCart((current) => current.map((item) => item.key === key ? { ...item, productNote } : item));
  }

  function openCheckout() {
    if (!currentUser) {
      setAuthMode("register");
      setAuthOpen(true);
      return;
    }
    setCustomerForm((current) => ({ ...current, name: current.name || currentUser.name, phone: current.phone || currentUser.phone, address: current.address || currentUser.address, floor: current.floor || currentUser.floor, paymentMethod: getAvailablePaymentOptions(current.deliveryType, platform)[0] || "cash" }));
    setCheckoutOpen(true);
  }

  function placeOrder(e) {
    e.preventDefault();
    if (!currentUser) return openCheckout();
    if (isUserGloballyBanned(currentUser) || isCustomerBannedFromStore(currentUser, cartStore)) return;
    if (!cartStore || !canOrder || !availablePaymentOptions.includes(customerForm.paymentMethod)) return;
    if (!customerForm.name || !customerForm.phone || (customerForm.deliveryType === "delivery" && !customerForm.address)) return;
    const now = new Date().toISOString();
    const finalDeliveryFee = customerForm.deliveryType === "pickup" ? 0 : deliveryFee;
    const orderPlatformFeeAmount = finalDeliveryFee + serviceFee;
    const orderLoyaltyUsageRaw = calculateLoyaltyUsage(customerForm.loyaltyPointsToRedeem, currentUser.loyaltyPoints || 0, orderPlatformFeeAmount, platform);
    const orderLoyaltyDiscount = Math.min(orderLoyaltyUsageRaw.discount, orderPlatformFeeAmount);
    const orderLoyaltyUsage = { ...orderLoyaltyUsageRaw, discount: orderLoyaltyDiscount };
    const orderEarnedPoints = calculateEarnedLoyaltyPoints(subtotal, platform);
    const finalTotal = roundMoney(Math.max(0, subtotal + serviceFee + finalDeliveryFee - orderLoyaltyDiscount));
    const order = {
      id: safeId("ord"),
      storeId: cartStore.id,
      storeSnapshot: { id: cartStore.id, name: cartStore.profile.name, phone: cartStore.profile.phone, address: cartStore.profile.address, area: cartStore.profile.area, logo: storageSafeImage(cartStore.profile.logo), logoEmoji: cartStore.profile.logoEmoji },
      userId: currentUser.id,
      createdAt: now,
      status: "new",
      statusUpdatedAt: now,
      statusHistory: [{ status: "new", at: now }],
      deliveryType: customerForm.deliveryType,
      paymentMethod: customerForm.paymentMethod,
      contactPreference: customerForm.contactPreference,
      scheduledTime: customerForm.scheduledTime,
      customer: { ...customerForm },
      items: cart.map(compactOrderItemForStorage),
      driverId: "",
      driverSnapshot: null,
      driverEvents: [],
      deliveryAssignment: customerForm.deliveryType === "pickup" ? null : { status: "waiting_driver", assignedAt: "", pickedUpAt: "", completedAt: "", etaMinutes: Number(platform.driverBaseEtaMinutes || 25), driverCommissionPercent: Number(platform.driverCommissionPercent || 40), driverPlatformFeePercent: Number(platform.driverPlatformFeePercent || 60), driverPayout: 0 },
      loyaltyEarned: orderEarnedPoints + (calculateStreak(customerOrders) >= 2 ? Number(platform.loyaltyStreakBonusPoints || 0) : 0),
      loyaltyRedeemed: orderLoyaltyUsage.points,
      loyaltyDiscount: orderLoyaltyUsage.discount,
      totals: { subtotal, serviceFee, deliveryFee: finalDeliveryFee, loyaltyDiscount: orderLoyaltyUsage.discount, loyaltyPointsRedeemed: orderLoyaltyUsage.points, totalBeforeDiscount: subtotal + serviceFee + finalDeliveryFee, total: finalTotal, platformFeesBeforeDiscount: serviceFee + finalDeliveryFee, platformFeesAfterLoyalty: Math.max(0, serviceFee + finalDeliveryFee - orderLoyaltyUsage.discount), platformFees: Math.max(0, serviceFee + finalDeliveryFee - orderLoyaltyUsage.discount) },
    };
    setOrders((current) => [order, ...current]);
    setUsers((current) => current.map((user) => user.id === currentUser.id ? normalizeUser({ ...user, ...customerForm, loyaltyPoints: Math.max(0, Number(user.loyaltyPoints || 0) - Number(orderLoyaltyUsage.points || 0)) + order.loyaltyEarned }) : user));
    setCart([]);
    setCheckoutOpen(false);
    setTrackingOrder(order);
  }

  function updateOrderStatus(orderId, status) {
    const now = new Date().toISOString();
    let releasedDriverId = "";
    const next = orders.map((order) => {
      if (order.id !== orderId) return order;
      const closing = ["completed", "cancelled"].includes(status);
      if (closing && order.driverId) releasedDriverId = order.driverId;
      const driverPayout = status === "completed" && order.driverId
        ? roundMoney(deliveryFeeForOrder(order) * (Number(order.deliveryAssignment?.driverCommissionPercent || platform.driverCommissionPercent || 40) / 100))
        : Number(order.deliveryAssignment?.driverPayout || 0);
      return {
        ...order,
        status,
        deliveryAssignment: order.deliveryAssignment ? { ...order.deliveryAssignment, status, driverPayout, completedAt: status === "completed" ? now : order.deliveryAssignment.completedAt } : order.deliveryAssignment,
        statusUpdatedAt: now,
        statusHistory: [...(order.statusHistory || []), { status, at: now }],
      };
    });
    setOrders(next);
    if (releasedDriverId) {
      setDrivers((current) => current.map((driver) => driver.id === releasedDriverId ? normalizeDriver({ ...driver, activeOrderId: "", completedDeliveries: status === "completed" ? Number(driver.completedDeliveries || 0) + 1 : Number(driver.completedDeliveries || 0) }) : driver));
    }
    if (trackingOrder?.id === orderId) setTrackingOrder(next.find((order) => order.id === orderId));
  }

  function rateDriverOrder(orderId, rating, comment = "") {
    if (!currentUser) return;
    const value = Math.min(5, Math.max(1, Number(rating || 0)));
    const now = new Date().toISOString();
    let driverId = "";
    const nextOrders = orders.map((order) => {
      if (order.id !== orderId || order.userId !== currentUser.id || order.status !== "completed" || !order.driverId) return order;
      driverId = order.driverId;
      const ratedOrder = { ...order, driverRating: { rating: value, comment: String(comment || "").trim(), at: now, byUserId: currentUser.id } };
      return { ...ratedOrder, deliveryAssignment: ratedOrder.deliveryAssignment ? { ...ratedOrder.deliveryAssignment, ratingBonus: driverRatingBonusForOrder(ratedOrder, platform) } : ratedOrder.deliveryAssignment };
    });
    setOrders(nextOrders);
    if (driverId) {
      setDrivers((current) => current.map((driver) => {
        if (driver.id !== driverId) return driver;
        const rated = nextOrders.filter((order) => order.driverId === driverId && order.driverRating?.rating);
        const avg = rated.length ? rated.reduce((sum, order) => sum + Number(order.driverRating.rating || 0), 0) / rated.length : Number(driver.rating || 5);
        return normalizeDriver({ ...driver, rating: Math.round(avg * 10) / 10 });
      }));
    }
    if (trackingOrder?.id === orderId) setTrackingOrder(nextOrders.find((order) => order.id === orderId));
  }

  function openTrackingById() {
    const found = orders.find((order) => order.id === trackId.trim());
    if (found) setTrackingOrder(found);
  }

  function registerCustomer(e) {
    e.preventDefault();
    const prepared = normalizeUser(authForm);
    if (!prepared.name || !prepared.phone || !prepared.password) return setAuthError("Συμπλήρωσε όνομα, τηλέφωνο και κωδικό.");
    if (users.some((user) => user.phone === prepared.phone)) return setAuthError("Υπάρχει ήδη πελάτης με αυτό το τηλέφωνο.");
    const created = { ...prepared, id: safeId("user") };
    setUsers((current) => [created, ...current]);
    setCurrentUserId(created.id);
    setAuthForm(emptyAuthForm());
    setAuthError("");
    setAuthOpen(false);
    setCustomerForm((current) => ({ ...current, name: current.name || created.name, phone: current.phone || created.phone, address: current.address || created.address, floor: current.floor || created.floor, paymentMethod: getAvailablePaymentOptions(current.deliveryType, platform)[0] || "cash" }));
    if (cart.length) setCheckoutOpen(true);
  }

  function loginCustomer(e) {
    e.preventDefault();
    const found = users.find((user) => user.phone === authForm.phone.trim() && user.password === authForm.password.trim());
    if (!found) return setAuthError("Δεν βρέθηκε πελάτης με αυτά τα στοιχεία.");
    setCurrentUserId(found.id);
    setAuthForm(emptyAuthForm());
    setAuthError("");
    setAuthOpen(false);
    setCustomerForm((current) => ({ ...current, name: current.name || found.name, phone: current.phone || found.phone, address: current.address || found.address, floor: current.floor || found.floor, paymentMethod: getAvailablePaymentOptions(current.deliveryType, platform)[0] || "cash" }));
    if (cart.length) setCheckoutOpen(true);
  }

  function updateCustomerProfile(profile) {
    if (!currentUser) return;
    const updated = normalizeUser({ ...currentUser, ...profile, id: currentUser.id, password: profile.password || currentUser.password });
    setUsers((current) => current.map((user) => user.id === currentUser.id ? updated : user));
    setCustomerForm((current) => ({ ...current, name: updated.name, phone: updated.phone, address: updated.address, floor: updated.floor }));
  }

  function updateCustomerAdmin(userId, patch) {
    const now = new Date().toISOString();
    setUsers((current) => current.map((user) => {
      if (user.id !== userId) return user;
      const status = patch.status || user.status || "active";
      return normalizeUser({ ...user, ...patch, status, bannedAt: status === "banned" || status === "suspended" ? (patch.bannedAt || now) : "", banReason: status === "banned" || status === "suspended" ? (patch.banReason || user.banReason || "Απόφαση Platform Admin") : "" });
    }));
  }

  function deleteCustomerPlatform(userId) {
    const user = users.find((row) => row.id === userId);
    if (typeof window !== "undefined" && !window.confirm(`Οριστική διαγραφή χρήστη ${user?.name || userId}; Τα προσωπικά στοιχεία στις παραγγελίες θα ανωνυμοποιηθούν.`)) return;
    setUsers((current) => current.filter((row) => row.id !== userId));
    setOrders((current) => current.map((order) => order.userId === userId ? { ...order, userId: "", customer: { ...order.customer, name: "Διαγραμμένος χρήστης", phone: "", address: "", floor: "", notes: "" } } : order));
    if (currentUserId === userId) setCurrentUserId("");
  }

  function deleteStorePlatform(storeId) {
    const store = stores.find((row) => row.id === storeId);
    if (typeof window !== "undefined" && !window.confirm(`Οριστική διαγραφή καταστήματος ${store?.profile?.name || storeId}; Θα αφαιρεθούν και οι παραγγελίες του από το dashboard.`)) return;
    setStores((current) => current.filter((row) => row.id !== storeId));
    setApplications((current) => current.filter((app) => app.approvedStoreId !== storeId));
    setOrders((current) => current.filter((order) => order.storeId !== storeId));
    setCart((current) => current.filter((item) => item.storeId !== storeId));
    if (currentMerchantStoreId === storeId) setCurrentMerchantStoreId("");
    if (selectedStoreId === storeId) setSelectedStoreId("all");
  }

  function repeatCustomerOrder(order) {
    setCart(order.items.map((item) => ({ ...item, key: `${item.storeId}-${item.productId}-${safeId("repeat")}` })));
    setCustomerForm((current) => ({ ...current, name: currentUser?.name || order.customer.name, phone: currentUser?.phone || order.customer.phone, address: currentUser?.address || order.customer.address, floor: currentUser?.floor || order.customer.floor, deliveryType: order.deliveryType || "delivery", paymentMethod: getAvailablePaymentOptions(order.deliveryType || "delivery", platform)[0] || "cash" }));
    setAccountOpen(false);
    setCheckoutOpen(true);
  }

  function logoutCustomer() {
    setCurrentUserId("");
    setCustomerForm(emptyCustomerForm());
    setAccountOpen(false);
  }

  function toggleFavoriteProduct(product) {
    if (!currentUser) return setAuthOpen(true);
    const key = `${product.storeId}:${product.id}`;
    setUsers((current) => current.map((user) => {
      if (user.id !== currentUser.id) return user;
      const favorites = user.favorites || [];
      return normalizeUser({ ...user, favorites: favorites.includes(key) ? favorites.filter((item) => item !== key) : [key, ...favorites] });
    }));
  }

  function registerDriver(e) {
    e.preventDefault();
    const prepared = normalizeDriver(driverForm);
    if (!prepared.name || !prepared.phone || !prepared.password || !prepared.vehiclePlate || !prepared.idNumber) return setDriverError("Συμπλήρωσε όνομα, τηλέφωνο, κωδικό, πινακίδα και ταυτότητα/άδεια.");
    if (drivers.some((driver) => driver.phone === prepared.phone)) return setDriverError("Υπάρχει ήδη διανομέας με αυτό το τηλέφωνο.");
    const created = normalizeDriver({ ...prepared, id: safeId("driver"), status: "pending" });
    setDrivers((current) => [created, ...current]);
    setCurrentDriverId(created.id);
    setDriverForm(emptyDriverForm());
    setDriverError("");
  }

  function loginDriver(e) {
    e.preventDefault();
    const found = drivers.find((driver) => driver.phone === driverForm.phone.trim() && driver.password === driverForm.password.trim());
    if (!found) return setDriverError("Δεν βρέθηκε λογαριασμός διανομέα.");
    setCurrentDriverId(found.id);
    setDriverForm(emptyDriverForm());
    setDriverError("");
  }

  function setDriverOnline(online) {
    if (!currentDriver || currentDriver.status !== "approved") return;
    setDrivers((current) => current.map((driver) => driver.id === currentDriver.id ? normalizeDriver({ ...driver, online, liveTrackingEnabled: online ? driver.liveTrackingEnabled : false }) : driver));
  }

  function setDriverLiveTracking(enabled) {
    if (!currentDriver || currentDriver.status !== "approved") return;
    setDrivers((current) => current.map((driver) => driver.id === currentDriver.id ? normalizeDriver({ ...driver, liveTrackingEnabled: Boolean(enabled), trackingError: "" }) : driver));
  }

  function setDriverTrackingError(message) {
    if (!currentDriver) return;
    setDrivers((current) => current.map((driver) => driver.id === currentDriver.id ? normalizeDriver({ ...driver, trackingError: message }) : driver));
  }

  function updateDriverLiveLocation(location) {
    if (!currentDriver) return;
    const prepared = normalizeLocation({ ...location, at: new Date().toISOString() });
    if (!prepared) return;
    setDrivers((current) => current.map((driver) => driver.id === currentDriver.id ? normalizeDriver({ ...driver, lastLocation: prepared, trackingError: "", trackingUpdatedAt: prepared.at }) : driver));
    setOrders((current) => current.map((order) => order.driverId === currentDriver.id && !["completed", "cancelled"].includes(order.status) ? { ...order, driverLastLocation: prepared, driverSnapshot: order.driverSnapshot ? { ...order.driverSnapshot, lastLocation: prepared } : order.driverSnapshot, deliveryAssignment: order.deliveryAssignment ? { ...order.deliveryAssignment, lastLocation: prepared, lastLocationAt: prepared.at } : order.deliveryAssignment } : order));
    setTrackingOrder((current) => current?.driverId === currentDriver.id && !["completed", "cancelled"].includes(current.status) ? { ...current, driverLastLocation: prepared, driverSnapshot: current.driverSnapshot ? { ...current.driverSnapshot, lastLocation: prepared } : current.driverSnapshot, deliveryAssignment: current.deliveryAssignment ? { ...current.deliveryAssignment, lastLocation: prepared, lastLocationAt: prepared.at } : current.deliveryAssignment } : current);
  }

  function logoutDriver() {
    if (currentDriver) setDrivers((current) => current.map((driver) => driver.id === currentDriver.id ? normalizeDriver({ ...driver, online: false }) : driver));
    setCurrentDriverId("");
    setDriverOpen(false);
  }

  function acceptDeliveryOrder(orderId) {
    if (!currentDriver || currentDriver.status !== "approved" || !currentDriver.online || currentDriver.activeOrderId) return;
    const now = new Date().toISOString();
    const eta = calculateDeliveryEta(drivers, platform);
    let accepted = null;
    const nextOrders = orders.map((order) => {
      if (order.id !== orderId || !canDriverClaimOrder(order)) return order;
      accepted = { ...order, status: "driver_assigned", driverId: currentDriver.id, driverSnapshot: { id: currentDriver.id, name: currentDriver.name, phone: currentDriver.phone, vehicleType: currentDriver.vehicleType, vehiclePlate: currentDriver.vehiclePlate, rating: currentDriver.rating, lastLocation: currentDriver.lastLocation || null }, driverLastLocation: currentDriver.lastLocation || null, deliveryAssignment: { ...(order.deliveryAssignment || {}), status: "assigned", assignedAt: now, pickupAt: eta.pickupAt, deliveryAt: eta.deliveryAt, etaMinutes: eta.etaMinutes, driverCommissionPercent: Number(platform.driverCommissionPercent || 40), driverPlatformFeePercent: Number(platform.driverPlatformFeePercent || 60), driverPayout: 0 }, driverEvents: [...(order.driverEvents || []), { type: "accepted", at: now, driverId: currentDriver.id }], statusUpdatedAt: now, statusHistory: [...(order.statusHistory || []), { status: "driver_assigned", at: now }] };
      return accepted;
    });
    setOrders(nextOrders);
    if (accepted) setDrivers((current) => current.map((driver) => driver.id === currentDriver.id ? normalizeDriver({ ...driver, activeOrderId: orderId }) : driver));
  }

  function patchDriverOrder(orderId, status, eventType, assignmentPatch = {}) {
    if (!currentDriver) return;
    const now = new Date().toISOString();
    let changed = null;
    const next = orders.map((order) => {
      if (order.id !== orderId || order.driverId !== currentDriver.id) return order;
      const payout = status === "completed" ? roundMoney(deliveryFeeForOrder(order) * (Number(order.deliveryAssignment?.driverCommissionPercent || platform.driverCommissionPercent || 40) / 100)) : order.deliveryAssignment?.driverPayout || 0;
      changed = { ...order, status, deliveryAssignment: { ...(order.deliveryAssignment || {}), ...assignmentPatch, status, driverPayout: payout, completedAt: status === "completed" ? now : order.deliveryAssignment?.completedAt }, driverEvents: [...(order.driverEvents || []), { type: eventType, at: now, driverId: currentDriver.id }], statusUpdatedAt: now, statusHistory: [...(order.statusHistory || []), { status, at: now }] };
      return changed;
    });
    setOrders(next);
    if (status === "completed") setDrivers((current) => current.map((driver) => driver.id === currentDriver.id ? normalizeDriver({ ...driver, activeOrderId: "", completedDeliveries: Number(driver.completedDeliveries || 0) + 1 }) : driver));
    if (changed && trackingOrder?.id === orderId) setTrackingOrder(changed);
  }

  function requestDriverWithdraw(amountValue) {
    if (!currentDriver || currentDriver.status !== "approved") return;
    const wallet = driverWalletStats(currentDriver.id, orders, driverWithdrawals, platform);
    const amount = roundMoney(amountValue || wallet.available);
    const min = Number(platform.driverMinWithdraw || 300);
    if (amount < min) return setDriverError(`Το ελάχιστο withdraw είναι ${formatEuro(min)}.`);
    if (amount > wallet.available) return setDriverError(`Διαθέσιμο υπόλοιπο: ${formatEuro(wallet.available)}.`);
    setDriverWithdrawals((current) => [{ id: safeId("wd"), driverId: currentDriver.id, driverName: currentDriver.name, driverPhone: currentDriver.phone, iban: currentDriver.iban || "", amount, status: "pending", createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }, ...current]);
    setDriverError("");
  }

  function loginMerchant(e) {
    e.preventDefault();
    const found = stores.find((store) => store.owner.phone === merchantForm.phone.trim() && store.owner.password === merchantForm.password.trim());
    if (!found) return setMerchantError("Δεν βρέθηκε κατάστημα με αυτά τα στοιχεία.");
    if (found.status !== "approved") return setMerchantError(`Το κατάστημα είναι: ${storeStatusLabel(found.status)}.`);
    setCurrentMerchantStoreId(found.id);
    setMerchantError("");
  }

  function submitMerchantApplication(e) {
    e.preventDefault();
    if (!merchantApplication.ownerName || !merchantApplication.ownerPhone || !merchantApplication.ownerPassword || !merchantApplication.storeName || !merchantApplication.storeAddress) return setMerchantError("Συμπλήρωσε ιδιοκτήτη, τηλέφωνο, κωδικό, όνομα και διεύθυνση καταστήματος.");
    const application = { id: safeId("app"), status: "pending", createdAt: new Date().toISOString(), ...merchantApplication };
    setApplications((current) => [application, ...current]);
    setMerchantApplication(emptyMerchantApplication());
    setMerchantError("Η αίτηση στάλθηκε στον κεντρικό διαχειριστή για έγκριση.");
    setMerchantMode("login");
  }

  function saveMerchantStore(updatedStore) {
    setStores((current) => current.map((store) => store.id === updatedStore.id ? updatedStore : store));
  }

  function banCustomerFromStore(storeId, customer, reason = "Αποκλεισμός από κατάστημα") {
    setStores((current) => current.map((store) => {
      if (store.id !== storeId) return store;
      const existing = store.customerBans || [];
      const phone = customer.phone || customer.customer?.phone || "";
      const userId = customer.userId || customer.id || "";
      if (existing.some((ban) => (userId && ban.userId === userId) || (phone && ban.phone === phone))) return store;
      return { ...store, customerBans: [{ id: safeId("ban"), userId, phone, name: customer.name || customer.customer?.name || "Πελάτης", reason, createdAt: new Date().toISOString() }, ...existing] };
    }));
  }

  function unbanCustomerFromStore(storeId, banId) {
    setStores((current) => current.map((store) => store.id === storeId ? { ...store, customerBans: (store.customerBans || []).filter((ban) => ban.id !== banId) } : store));
  }

  function saveMerchantProduct(storeId, product) {
    setStores((current) => current.map((store) => {
      if (store.id !== storeId) return store;
      const prepared = normalizeProduct(product, storeId);
      const exists = store.products.some((row) => row.id === prepared.id);
      const products = exists ? store.products.map((row) => row.id === prepared.id ? prepared : row) : [prepared, ...store.products];
      const categories = prepared.category && !store.categories.includes(prepared.category) ? [...store.categories, prepared.category] : store.categories;
      return { ...store, products, categories };
    }));
  }

  function updateMerchantProduct(storeId, productId, patch) {
    setStores((current) => current.map((store) => store.id === storeId ? { ...store, products: store.products.map((product) => product.id === productId ? normalizeProduct({ ...product, ...patch }, storeId) : product) } : store));
  }

  function deleteMerchantProduct(storeId, productId) {
    setStores((current) => current.map((store) => store.id === storeId ? { ...store, products: store.products.filter((product) => product.id !== productId) } : store));
  }

  function approveApplication(appId) {
    const app = applications.find((row) => row.id === appId);
    if (!app) return;
    const storeId = safeId("store");
    const newStore = { id: storeId, status: "approved", active: true, createdAt: app.createdAt, approvedAt: new Date().toISOString(), owner: { name: app.ownerName, phone: app.ownerPhone, email: app.ownerEmail, password: app.ownerPassword, idNumber: app.ownerIdNumber, taxNumber: app.ownerTaxNumber, iban: app.iban }, profile: { name: app.storeName, subtitle: app.storeType, logo: "", logoEmoji: "🏪", phone: app.storePhone || app.ownerPhone, address: app.storeAddress, area: app.storeArea, openHours: "08:00 - 22:00", deliveryTime: "30-40'", description: app.notes || "Νέο συνεργαζόμενο κατάστημα." }, categories: DEFAULT_CATEGORIES, products: createDefaultProducts(storeId) };
    setStores((current) => [newStore, ...current]);
    setApplications((current) => current.map((row) => row.id === appId ? { ...row, status: "approved", approvedStoreId: storeId, updatedAt: new Date().toISOString() } : row));
  }

  function rejectApplication(appId) {
    setApplications((current) => current.map((row) => row.id === appId ? { ...row, status: "rejected", updatedAt: new Date().toISOString() } : row));
  }

  function updateStorePlatform(storeId, patch) {
    setStores((current) => current.map((store) => store.id === storeId ? { ...store, ...patch } : store));
  }

  function updateDriverAdmin(driverId, patch) {
    const now = new Date().toISOString();
    setDrivers((current) => current.map((driver) => {
      if (driver.id !== driverId) return driver;
      const status = patch.status || driver.status;
      return normalizeDriver({ ...driver, ...patch, approvedAt: status === "approved" && !driver.approvedAt ? now : driver.approvedAt, online: status === "approved" ? Boolean(patch.online ?? driver.online) : false });
    }));
  }

  function updateDriverWithdrawal(id, status) {
    setDriverWithdrawals((current) => current.map((request) => request.id === id ? { ...request, status, updatedAt: new Date().toISOString() } : request));
  }

  function resetDemo() {
    setPlatform(PLATFORM_DEFAULTS);
    setStores(createDemoStores());
    setApplications([]);
    setUsers([]);
    setCurrentUserId("");
    setDrivers([]);
    setCurrentDriverId("");
    setDriverWithdrawals([]);
    setOrders([]);
    setCurrentMerchantStoreId("");
    setCart([]);
    setCustomerForm(emptyCustomerForm());
    setAccessMenuOpen(false);
  }

  function openCustomerAccess() {
    setAccessMenuOpen(false);
    if (currentUser) {
      setAccountOpen(true);
      return;
    }
    setAuthMode("login");
    setAuthOpen(true);
  }

  function openMerchantAccess(mode = "login") {
    setAccessMenuOpen(false);
    setMerchantMode(mode);
    setMerchantOpen(true);
  }

  function openDriverAccess() {
    setAccessMenuOpen(false);
    setDriverOpen(true);
  }

  function openPlatformAccess() {
    setAccessMenuOpen(false);
    setPlatformOpen(true);
  }

  return (
    <div key={lang} data-language={lang} className="min-h-screen bg-slate-50 text-slate-950">
      <header className="sticky top-0 z-40 border-b border-slate-200/70 bg-white/95 backdrop-blur-xl">
        <div className="mx-auto flex max-w-7xl items-center justify-between gap-3 px-4 py-2.5 sm:px-6 lg:px-8">
          <button onClick={() => { setSelectedStoreId("all"); setActiveCategory("Προσφορές"); }} className="flex min-w-0 items-center gap-3 text-left">
            <span className="grid h-12 w-28 shrink-0 overflow-hidden place-items-center sm:h-14 sm:w-32"><BrandLogo src={platform.brandLogo} fallback="🛵" /></span>
            <span className="hidden min-w-0 sm:block"><span className="block truncate text-sm font-black tracking-tight sm:text-base">{tx(platform.brandName, lang)}</span><span className="block max-w-[260px] truncate text-xs font-semibold text-slate-500">{tx(platform.subtitle, lang)}</span></span>
          </button>
          <div className="hidden flex-1 justify-center lg:flex">
            <div className="rounded-full bg-emerald-50 px-4 py-2 text-sm font-black text-emerald-800 ring-1 ring-emerald-100">{approvedStores.length} {t(lang, "activeStores")} · {allProducts.length} {t(lang, "products")}</div>
          </div>
          <div className="flex shrink-0 items-center gap-2">
            <LanguageToggle lang={lang} setLang={setLang} />
            <AccessMenu open={accessMenuOpen} setOpen={setAccessMenuOpen} currentUser={currentUser} lang={lang} onCustomer={openCustomerAccess} onMerchant={() => openMerchantAccess("login")} onMerchantApply={() => openMerchantAccess("apply")} onDriver={openDriverAccess} onPlatform={openPlatformAccess} />
            <button onClick={openCheckout} className="relative rounded-full bg-slate-950 px-3 py-2.5 text-sm font-black text-white shadow-xl shadow-slate-300 sm:px-4">🛒 <span className="hidden sm:inline">{formatEuro(total, lang)}</span>{cart.length > 0 && <span className="absolute -right-1 -top-1 grid h-6 w-6 place-items-center rounded-full bg-emerald-500 text-xs ring-2 ring-white">{cart.reduce((sum, item) => sum + item.qty, 0)}</span>}</button>
          </div>
        </div>
      </header>

      <main className="mx-auto grid max-w-7xl gap-6 px-4 py-5 pb-28 sm:px-6 lg:grid-cols-[1fr_390px] lg:px-8 lg:pb-8">
        <section className="space-y-6">
          <section className="relative overflow-hidden rounded-[2rem] bg-slate-950 p-6 text-white shadow-2xl sm:p-8">
            <div className="absolute -right-16 -top-16 h-56 w-56 rounded-full bg-emerald-400/30 blur-3xl" />
            <div className="relative grid gap-6 md:grid-cols-[1.15fr_0.85fr] md:items-center">
              <div>
                <div className="mb-4 inline-flex rounded-full bg-white/10 px-3 py-1.5 text-xs font-black text-emerald-100 ring-1 ring-white/15">{t(lang, "marketplaceBadge")}</div>
                <h1 className="max-w-2xl text-3xl font-black leading-tight tracking-tight sm:text-4xl">{t(lang, "heroTitle")}</h1>
                <p className="mt-4 max-w-2xl text-sm leading-7 text-slate-300 sm:text-base">{tx(platform.platformAnnouncement, lang)}</p>
                <div className="mt-6 grid grid-cols-2 gap-3 sm:grid-cols-3"><InfoPill icon="🏪" label={approvedStores.length} value={t(lang, "stores")} /><InfoPill icon="🍽️" label={allProducts.length} value={t(lang, "productsCap")} /><InfoPill icon="🎁" label="Live" value={t(lang, "topOffers")} /></div>
              </div>
              <div className="rounded-[1.75rem] bg-white/10 p-4 ring-1 ring-white/15 backdrop-blur"><div className="rounded-[1.5rem] bg-white p-4 text-slate-950"><p className="text-xs font-black uppercase tracking-widest text-emerald-600">{t(lang, "joinPlatform")}</p><h2 className="mt-1 text-xl font-black">{t(lang, "haveStore")}</h2><p className="mt-3 text-sm leading-6 text-slate-600">{t(lang, "merchantPitch")}</p><button onClick={() => { setMerchantMode("apply"); setMerchantOpen(true); }} className="mt-5 w-full rounded-2xl bg-emerald-500 py-3 font-black text-white hover:bg-emerald-600">{t(lang, "storeApply")}</button></div></div>
            </div>
          </section>

          <section className="grid gap-4 md:grid-cols-[1fr_auto] md:items-center">
            <div className="relative"><span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">🔎</span><input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t(lang, "searchPlaceholder")} className="h-14 w-full rounded-2xl border border-slate-200 bg-white pl-12 pr-4 text-sm font-semibold outline-none transition focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100" /></div>
            <div className="grid gap-3 rounded-[1.5rem] bg-white p-3 ring-1 ring-slate-200 md:grid-cols-[1fr_auto]"><Input label={t(lang, "tracking")} value={trackId} onChange={setTrackId} placeholder="ord-..." /><button onClick={openTrackingById} className="h-14 rounded-2xl bg-slate-950 px-5 text-sm font-black text-white">{t(lang, "seeProgress")}</button></div>
          </section>

          <section>
            <div className="mb-3 flex items-center justify-between"><h2 className="text-xl font-black sm:text-2xl">{t(lang, "stores")}</h2><button onClick={() => setSelectedStoreId("all")} className="rounded-full bg-white px-4 py-2 text-sm font-black ring-1 ring-slate-200">{t(lang, "allHub")}</button></div>
            <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{approvedStores.map((store) => <StoreCard key={store.id} store={store} lang={lang} selected={selectedStoreId === store.id} onSelect={() => { setSelectedStoreId(store.id); setActiveCategory(store.categories[0] || "Προσφορές"); }} />)}</div>
          </section>

          <nav className="flex gap-2 overflow-x-auto pb-1">{categories.map((category) => <button key={category} onClick={() => setActiveCategory(category)} className={`whitespace-nowrap rounded-full px-5 py-3 text-sm font-black transition ${activeCategory === category ? "bg-slate-950 text-white shadow-xl shadow-slate-200" : "bg-white text-slate-600 ring-1 ring-slate-200 hover:bg-slate-100"}`}>{tx(category, lang)}</button>)}</nav>

          <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">{filteredProducts.length === 0 ? <EmptyState icon="📭" title={t(lang, "emptyFilter")} /> : filteredProducts.map((product) => <ProductCard key={`${product.storeId}-${product.id}`} product={product} lang={lang} favorite={currentUser?.favorites?.includes(`${product.storeId}:${product.id}`)} onOpen={() => openProduct(product)} onFavorite={() => toggleFavoriteProduct(product)} />)}</section>
        </section>

        <aside className="hidden lg:block"><CartPanel cart={cart} subtotal={subtotal} deliveryFee={deliveryFee} serviceFee={serviceFee} loyaltyDiscount={loyaltyDiscount} total={total} cartStore={cartStore} deliveryType={customerForm.deliveryType} minOrder={platform.minOrder} canOrder={canOrder} updateQty={updateQty} updateItemNote={updateItemNote} checkout={openCheckout} lang={lang} /></aside>
      </main>

      <SiteFooter platform={platform} onPage={setLegalPage} />

      <MobileBar total={total} items={cart.reduce((sum, item) => sum + item.qty, 0)} onCart={openCheckout} onMenu={() => setAccessMenuOpen(true)} onAuth={openCustomerAccess} onAccount={openCustomerAccess} currentUser={currentUser} lang={lang} />

      {selectedProduct && <Modal onClose={() => setSelectedProduct(null)}><ProductModal product={selectedProduct} choices={selectedChoices} setChoices={setSelectedChoices} onAdd={() => { addToCart(selectedProduct, selectedChoices); setSelectedProduct(null); }} /></Modal>}
      {checkoutOpen && <Modal onClose={() => setCheckoutOpen(false)} size="large"><CheckoutModal cart={cart} cartStore={cartStore} subtotal={subtotal} deliveryFee={deliveryFee} serviceFee={serviceFee} loyaltyDiscount={loyaltyDiscount} total={total} form={customerForm} setForm={setCustomerForm} platform={platform} currentUser={currentUser} customerBlockedReason={customerBlockedReason} loyaltyUsage={loyaltyUsage} earnedPointsPreview={earnedPointsPreview} paymentOptions={availablePaymentOptions} canOrder={canOrder} onSubmit={placeOrder} updateQty={updateQty} updateItemNote={updateItemNote} lang={lang} /></Modal>}
      {trackingOrder && <Modal onClose={() => setTrackingOrder(null)} size="large"><OrderTracking order={trackingOrder} /></Modal>}
      {authOpen && <Modal onClose={() => setAuthOpen(false)}><CustomerAuth mode={authMode} setMode={setAuthMode} form={authForm} setForm={setAuthForm} error={authError} onRegister={registerCustomer} onLogin={loginCustomer} /></Modal>}
      {legalPage && <Modal onClose={() => setLegalPage(null)} size="large"><StaticPage page={legalPage} platform={platform} /></Modal>}
      {accountOpen && currentUser && <Modal onClose={() => setAccountOpen(false)} size="large"><CustomerDashboard user={currentUser} orders={customerOrders} products={allProducts} stores={stores} platform={platform} onUpdate={updateCustomerProfile} onLogout={logoutCustomer} onTrack={(order) => { setTrackingOrder(order); setAccountOpen(false); }} onReorder={repeatCustomerOrder} onRateDriver={rateDriverOrder} onOpenProduct={(product) => { setAccountOpen(false); openProduct(product); }} onFavorite={toggleFavoriteProduct} /></Modal>}
      {driverOpen && <Modal onClose={() => setDriverOpen(false)} size="large">{currentDriver ? <DriverDashboard driver={currentDriver} activeOrders={currentDriverOrders} availableOrders={availableDriverOrders} platform={platform} wallet={currentDriverWallet} withdrawals={driverWithdrawals} error={driverError} onOnline={setDriverOnline} onTrackingToggle={setDriverLiveTracking} onLocationUpdate={updateDriverLiveLocation} onTrackingError={setDriverTrackingError} onAccept={acceptDeliveryOrder} onPickedUp={(id) => patchDriverOrder(id, "picked_up", "picked_up", { pickedUpAt: new Date().toISOString() })} onStartDelivery={(id) => patchDriverOrder(id, "delivery", "delivery_started")} onComplete={(id) => patchDriverOrder(id, "completed", "completed")} onWithdraw={requestDriverWithdraw} onLogout={logoutDriver} /> : <DriverAuth mode={driverMode} setMode={setDriverMode} form={driverForm} setForm={setDriverForm} error={driverError} onRegister={registerDriver} onLogin={loginDriver} />}</Modal>}
      {merchantOpen && <Modal onClose={() => setMerchantOpen(false)} size="large">{currentMerchantStore ? <MerchantDashboard store={currentMerchantStore} users={users} orders={orders.filter((order) => order.storeId === currentMerchantStore.id)} stats={getStoreStats(currentMerchantStore.id, orders, platform)} platform={platform} onSaveStore={saveMerchantStore} onSaveProduct={saveMerchantProduct} onUpdateProduct={updateMerchantProduct} onDeleteProduct={deleteMerchantProduct} onBanCustomer={banCustomerFromStore} onUnbanCustomer={unbanCustomerFromStore} onStatus={updateOrderStatus} onLogout={() => { setCurrentMerchantStoreId(""); setMerchantMode("login"); }} /> : <MerchantPortal mode={merchantMode} setMode={setMerchantMode} loginForm={merchantForm} setLoginForm={setMerchantForm} appForm={merchantApplication} setAppForm={setMerchantApplication} error={merchantError} onLogin={loginMerchant} onApply={submitMerchantApplication} />}</Modal>}
      {platformOpen && <Modal onClose={() => setPlatformOpen(false)} size="large">{!platformUnlocked ? <PlatformLogin pin={platform.platformPin} value={platformPin} onChange={setPlatformPin} onUnlock={() => { if (platformPin === String(platform.platformPin)) setPlatformUnlocked(true); }} /> : <PlatformAdmin platform={platform} setPlatform={setPlatform} stats={platformStats} stores={stores} applications={applications} orders={orders} users={users} drivers={drivers} withdrawals={driverWithdrawals} onApproveApplication={approveApplication} onRejectApplication={rejectApplication} onUpdateStore={updateStorePlatform} onDeleteStore={deleteStorePlatform} onUpdateCustomer={updateCustomerAdmin} onDeleteCustomer={deleteCustomerPlatform} onUpdateDriver={updateDriverAdmin} onUpdateWithdrawal={updateDriverWithdrawal} onStatus={updateOrderStatus} onReset={resetDemo} onLock={() => { setPlatformUnlocked(false); setPlatformPin(""); }} />}</Modal>}
    </div>
  );
}

function StoreCard({ store, selected, onSelect, lang = "el" }) {
  const offers = store.products
    .filter((product) => product.active !== false)
    .sort((a, b) => Number(Boolean(b.promo || b.oldPrice)) - Number(Boolean(a.promo || a.oldPrice)) || Number(b.rating || 0) - Number(a.rating || 0))
    .slice(0, 3);
  return (
    <button onClick={onSelect} className={`text-left rounded-[1.5rem] p-4 ring-1 transition hover:-translate-y-1 hover:shadow-xl ${selected ? "bg-slate-950 text-white ring-slate-950" : "bg-white ring-slate-200"}`}>
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-center gap-3">
          <span className="grid h-14 w-14 overflow-hidden place-items-center rounded-2xl bg-emerald-100 text-3xl"><MediaBox src={store.profile.logo} fallback={store.profile.logoEmoji || "🏪"} /></span>
          <div>
            <h3 className="text-base font-black sm:text-lg">{tx(store.profile.name, lang)}</h3>
            <p className={`text-sm font-bold ${selected ? "text-slate-300" : "text-slate-500"}`}>{tx(store.profile.subtitle, lang)}</p>
          </div>
        </div>
        <span className="rounded-full bg-emerald-100 px-3 py-1 text-xs font-black text-emerald-800">{store.products.filter((p) => p.active !== false).length} {t(lang, "products")}</span>
      </div>
      <p className={`mt-3 text-sm leading-6 ${selected ? "text-slate-300" : "text-slate-600"}`}>📍 {tx(store.profile.area, lang)} · ⏱️ {store.profile.deliveryTime} · ☎️ {store.profile.phone}</p>
      <div className={`mt-4 rounded-2xl p-3 ring-1 ${selected ? "bg-white/10 ring-white/15" : "bg-slate-50 ring-slate-100"}`}>
        <p className={`mb-2 text-xs font-black uppercase tracking-widest ${selected ? "text-emerald-200" : "text-emerald-700"}`}>{t(lang, "topOffers")}</p>
        <div className="space-y-2">
          {offers.length === 0 ? <p className={`text-xs font-bold ${selected ? "text-slate-300" : "text-slate-500"}`}>{t(lang, "noOffers")}</p> : offers.map((product) => (
            <div key={product.id} className={`flex items-center justify-between gap-3 rounded-xl p-2 ${selected ? "bg-white/10" : "bg-white"}`}>
              <span className="min-w-0 truncate text-sm font-black">{product.emoji || "🍽️"} {tx(product.title, lang)}</span>
              <span className="shrink-0 text-sm font-black text-emerald-600">{formatEuro(product.price, lang)}</span>
            </div>
          ))}
        </div>
      </div>
    </button>
  );
}

function ProductCard({ product, favorite, onOpen, onFavorite, lang = "el" }) {
  return <article className="group overflow-hidden rounded-[1.6rem] bg-white p-4 shadow-sm ring-1 ring-slate-200 transition hover:-translate-y-1 hover:shadow-xl"><button onClick={onOpen} className="w-full text-left"><div className="relative grid h-36 overflow-hidden place-items-center rounded-[1.35rem] bg-gradient-to-br from-slate-100 to-emerald-50 text-6xl">{(product.badge || product.promo || product.offerType !== "standard") && <span className="absolute left-3 top-3 z-10 rounded-full bg-white px-3 py-1 text-xs font-black text-emerald-700 shadow-sm">{tx(offerLabel(product) || product.badge || "Προσφορές", lang)}</span>}<MediaBox src={product.image} fallback={product.emoji || "🍽️"} className="transition group-hover:scale-110" imgClassName="h-full w-full object-cover transition group-hover:scale-105" /></div><div className="mt-4 flex items-start justify-between gap-3"><div><p className="flex items-center gap-2 text-xs font-black uppercase tracking-widest text-emerald-600"><span className="grid h-6 w-6 overflow-hidden place-items-center rounded-lg bg-emerald-50"><MediaBox src={product.storeLogo} fallback={product.storeLogoEmoji || "🏪"} className="text-sm" /></span>{tx(product.storeName, lang)}</p><h3 className="mt-1 text-base font-black tracking-tight sm:text-lg">{tx(product.title, lang)}</h3><p className="mt-1 text-sm leading-6 text-slate-500">{tx(product.description, lang)}</p></div><div className="text-right"><p className="text-lg font-black">{formatEuro(product.price, lang)}</p>{product.oldPrice && <p className="text-xs font-bold text-slate-400 line-through">{formatEuro(product.oldPrice, lang)}</p>}</div></div><div className="mt-4 flex items-center justify-between text-xs font-bold text-slate-500"><span>⭐ {product.rating}</span><span>⏱️ {product.time}</span></div></button><button onClick={onOpen} className="mt-4 w-full rounded-2xl bg-emerald-500 py-3 text-sm font-black text-white hover:bg-emerald-600">➕ {t(lang, "optionsAdd")}</button><button type="button" onClick={onFavorite} className={`mt-2 w-full rounded-2xl py-3 text-sm font-black ${favorite ? "bg-rose-50 text-rose-700 ring-1 ring-rose-100" : "bg-slate-100 text-slate-700 hover:bg-slate-200"}`}>{favorite ? `❤️ ${t(lang, "favorited")}` : `🤍 ${t(lang, "favorite")}`}</button></article>;
}

function ProductModal({ product, choices, setChoices, onAdd }) {
  const price = roundMoney(Number(product.price) + calculateExtraPriceFromChoices(choices));
  return <div className="p-5 sm:p-6"><div className="grid h-40 overflow-hidden place-items-center rounded-[1.5rem] bg-gradient-to-br from-emerald-50 to-slate-100 text-7xl"><MediaBox src={product.image} fallback={product.emoji || "🍽️"} imgClassName="h-full w-full object-cover" /></div><p className="mt-5 flex items-center gap-2 text-xs font-black uppercase tracking-widest text-emerald-600"><span className="grid h-7 w-7 overflow-hidden place-items-center rounded-lg bg-emerald-50"><MediaBox src={product.storeLogo} fallback={product.storeLogoEmoji || "🏪"} className="text-sm" /></span>{product.storeName}</p><h2 className="mt-1 text-2xl font-black">{product.title}</h2><p className="mt-2 leading-7 text-slate-600">{product.description}</p><div className="mt-5 grid gap-4"><ChoiceGroup title="Γλυκύτητα" options={product.options?.sweetness || ["Κανονικό"]} value={choices.sweetness} onChange={(value) => setChoices({ ...choices, sweetness: value })} /><ChoiceGroup title="Επιλογή" options={product.options?.milk || ["Κανονικό"]} value={choices.milk} onChange={(value) => setChoices({ ...choices, milk: value })} /><MultiChoiceGroup title="Extras" options={product.options?.extras || []} value={choices.extras} onChange={(extras) => setChoices({ ...choices, extras })} /><TextArea label="Ειδικές οδηγίες" value={choices.note} onChange={(note) => setChoices({ ...choices, note })} /></div><button onClick={onAdd} className="mt-6 w-full rounded-2xl bg-slate-950 py-4 font-black text-white hover:bg-slate-800">Προσθήκη · {formatEuro(price)}</button></div>;
}

function CheckoutModal({ cart, cartStore, subtotal, deliveryFee, serviceFee, loyaltyDiscount, total, form, setForm, platform, currentUser, customerBlockedReason, loyaltyUsage, earnedPointsPreview, paymentOptions, canOrder, onSubmit, updateQty, updateItemNote, lang = "el" }) {
  return <div className="grid w-full min-w-0 lg:grid-cols-[0.95fr_1.05fr]"><div className="border-b border-slate-200 p-5 lg:border-b-0 lg:border-r sm:p-6"><CartPanel cart={cart} subtotal={subtotal} deliveryFee={deliveryFee} serviceFee={serviceFee} loyaltyDiscount={loyaltyDiscount} total={total} cartStore={cartStore} deliveryType={form.deliveryType} minOrder={platform.minOrder} canOrder={canOrder} updateQty={updateQty} updateItemNote={updateItemNote} lang={lang} compact /></div><form onSubmit={onSubmit} className="p-5 sm:p-6"><h2 className="text-2xl font-black">Ολοκλήρωση παραγγελίας</h2>{cartStore && <p className="mt-2 text-sm font-bold text-slate-500">Κατάστημα: {tx(cartStore.profile.name, lang)}</p>}<div className="mt-6 grid gap-4"><ChoiceGroup title="Τρόπος εξυπηρέτησης" options={[...(platform.deliveryEnabled !== false ? ["delivery"] : []), ...(platform.pickupEnabled !== false ? ["pickup"] : [])]} value={form.deliveryType} onChange={(value) => setForm({ ...form, deliveryType: value, paymentMethod: getAvailablePaymentOptions(value, platform)[0] || "" })} /><ChoiceGroup title="Πληρωμή" options={paymentOptions} value={form.paymentMethod} onChange={(value) => setForm({ ...form, paymentMethod: value })} /><Input label="Ονοματεπώνυμο" icon="👤" value={form.name} onChange={(v) => setForm({ ...form, name: v })} required /><Input label="Τηλέφωνο" icon="📞" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} required /><Input label={form.deliveryType === "pickup" ? "Διεύθυνση προαιρετικά" : "Διεύθυνση παράδοσης"} icon="🏠" value={form.address} onChange={(v) => setForm({ ...form, address: v })} required={form.deliveryType === "delivery"} /><Input label="Όροφος / κουδούνι" icon="🔔" value={form.floor} onChange={(v) => setForm({ ...form, floor: v })} /><Input label="Ώρα παράδοσης / παραλαβής" icon="⏰" value={form.scheduledTime} onChange={(v) => setForm({ ...form, scheduledTime: v })} placeholder="Άμεσα ή 18:30" /><TextArea label="Σχόλια παραγγελίας" value={form.notes} onChange={(v) => setForm({ ...form, notes: v })} /></div>{currentUser && platform.loyaltyEnabled !== false && platform.loyaltyRedeemEnabled !== false && <div className="mt-5 rounded-[1.25rem] bg-amber-50 p-4 ring-1 ring-amber-100"><div className="flex flex-wrap items-start justify-between gap-3"><div><p className="font-black text-amber-950">⭐ Loyalty επιβράβευση</p><p className="mt-1 text-sm font-bold leading-6 text-amber-800">Διαθέσιμοι πόντοι: {currentUser.loyaltyPoints || 0} · {loyaltyRuleText(platform)}</p><p className="mt-1 text-xs font-bold text-amber-700">Με αυτή την παραγγελία κερδίζεις περίπου +{earnedPointsPreview} πόντους από την αξία προϊόντων. Η εξαργύρωση αφαιρείται μόνο από service/delivery fees.</p></div><div className="rounded-2xl bg-white px-4 py-3 text-right ring-1 ring-amber-100"><p className="text-xs font-black text-amber-700">Έκπτωση</p><p className="text-lg font-black text-amber-950">{formatEuro(loyaltyDiscount)}</p></div></div><div className="mt-4 grid gap-3 sm:grid-cols-[1fr_auto]"><Input label="Πόντοι για εξαργύρωση" type="number" value={form.loyaltyPointsToRedeem} onChange={(v) => setForm({ ...form, loyaltyPointsToRedeem: v })} placeholder={String(platform.loyaltyMinRedeemPoints || 100)} /><button type="button" onClick={() => setForm({ ...form, loyaltyPointsToRedeem: String(currentUser.loyaltyPoints || 0) })} className="h-14 self-end rounded-2xl bg-amber-500 px-5 text-sm font-black text-white">MAX</button></div>{form.loyaltyPointsToRedeem && loyaltyUsage.discount <= 0 && <p className="mt-3 text-xs font-black text-amber-800">Χρειάζονται τουλάχιστον {platform.loyaltyMinRedeemPoints || 100} πόντοι. Η έκπτωση εφαρμόζεται μόνο μέχρι το ύψος των platform fees, όχι στα προϊόντα.</p>}</div>}{customerBlockedReason && <p className="mt-4 rounded-2xl bg-rose-50 p-4 text-sm font-black text-rose-700 ring-1 ring-rose-100">{customerBlockedReason}</p>}{!canOrder && cart.length > 0 && !customerBlockedReason && <p className="mt-4 rounded-2xl bg-amber-50 p-4 text-sm font-black text-amber-800 ring-1 ring-amber-100">Ελάχιστη παραγγελία {formatEuro(platform.minOrder)}</p>}<button disabled={!canOrder || !cartStore} className="mt-6 w-full rounded-2xl bg-emerald-500 py-4 font-black text-white disabled:bg-slate-300">Αποστολή παραγγελίας · {formatEuro(total)}</button></form></div>;
}

function CartPanel({ cart, subtotal, deliveryFee, serviceFee, loyaltyDiscount = 0, total, cartStore, deliveryType, minOrder, canOrder, updateQty, updateItemNote, checkout, compact = false, lang = "el" }) {
  return <div className={`sticky top-24 rounded-[1.75rem] bg-white p-5 shadow-sm ring-1 ring-slate-200 ${compact ? "shadow-none ring-0" : ""}`}><div className="flex items-center justify-between"><h2 className="text-lg font-black sm:text-xl">{t(lang, "cart")}</h2><span className="text-2xl">🛒</span></div>{cartStore && <p className="mt-2 flex items-center gap-2 rounded-2xl bg-emerald-50 p-3 text-sm font-black text-emerald-800 ring-1 ring-emerald-100"><span className="grid h-7 w-7 overflow-hidden place-items-center rounded-lg bg-white"><MediaBox src={cartStore.profile.logo} fallback={cartStore.profile.logoEmoji || "🏪"} className="text-sm" /></span>{cartStore.profile.name}</p>}{cart.length === 0 ? <InfoBox icon="🛍️" title={t(lang, "emptyCart")} text={t(lang, "emptyCartText")} /> : <div className="mt-5 space-y-3">{cart.map((item) => <div key={item.key} className="flex gap-3 rounded-2xl bg-slate-50 p-3 ring-1 ring-slate-100"><div className="grid h-14 w-14 shrink-0 overflow-hidden place-items-center rounded-2xl bg-white text-2xl shadow-sm"><MediaBox src={item.image} fallback={item.emoji || "🍽️"} /></div><div className="min-w-0 flex-1"><p className="font-black">{tx(item.title, lang)}</p><p className="mt-1 text-xs font-semibold leading-5 text-slate-500">{item.optionText}</p>{item.bonusQty > 0 && <p className="mt-1 text-xs font-black text-emerald-700">🎁 +{item.bonusQty} δώρο από 1+1</p>}{item.offerType === "bundle" && item.bundleLabel && <p className="mt-1 text-xs font-black text-amber-700">🤝 {item.bundleLabel}</p>}{updateItemNote && <textarea value={item.productNote || ""} onChange={(e) => updateItemNote(item.key, e.target.value)} placeholder="Σχόλιο προϊόντος" className="mt-3 min-h-16 w-full rounded-2xl border border-slate-200 bg-white p-3 text-xs font-semibold outline-none" />}<div className="mt-3 flex items-center justify-between"><div className="flex items-center gap-2 rounded-full bg-white p-1 ring-1 ring-slate-200"><button onClick={() => updateQty(item.key, -1)} className="grid h-7 w-7 place-items-center rounded-full hover:bg-slate-100">−</button><span className="min-w-5 text-center text-sm font-black">{item.qty}</span><button onClick={() => updateQty(item.key, 1)} className="grid h-7 w-7 place-items-center rounded-full bg-slate-950 text-white">+</button></div><p className="font-black">{formatEuro(item.lineTotal, lang)}</p></div></div></div>)}</div>}<div className="mt-5 space-y-3 border-t border-slate-200 pt-5 text-sm font-bold text-slate-600"><Line label={t(lang, "itemsTotal")} value={formatEuro(subtotal, lang)} /><Line label={deliveryType === "pickup" ? t(lang, "pickup") : "Delivery"} value={deliveryType === "pickup" ? t(lang, "fromStore") : deliveryFee === 0 ? t(lang, "free") : formatEuro(deliveryFee, lang)} /><Line label={t(lang, "serviceFee")} value={formatEuro(serviceFee, lang)} />{loyaltyDiscount > 0 && <Line label={t(lang, "loyaltyFeeDiscount")} value={`-${formatEuro(loyaltyDiscount, lang)}`} />}<div className="flex items-center justify-between pt-2 text-lg font-black text-slate-950"><span>{t(lang, "total")}</span><span>{formatEuro(total, lang)}</span></div></div>{checkout && <button onClick={checkout} disabled={!cart.length} className="mt-5 w-full rounded-2xl bg-emerald-500 py-4 font-black text-white disabled:bg-slate-300">{t(lang, "continue")}</button>}{!canOrder && cart.length > 0 && <p className="mt-3 text-center text-xs font-bold text-amber-700">{t(lang, "minOrder")} {formatEuro(minOrder, lang)}</p>}</div>;
}

function CustomerDashboard({ user, orders, products, stores, platform, onUpdate, onLogout, onTrack, onReorder, onRateDriver, onOpenProduct, onFavorite }) {
  const [tab, setTab] = useState("overview");
  const [draft, setDraft] = useState(user);
  useEffect(() => setDraft(user), [user]);
  const activeOrders = orders.filter((order) => !["completed", "cancelled"].includes(order.status));
  const completedOrders = orders.filter((order) => order.status === "completed");
  const totalSpent = orders.filter((order) => order.status !== "cancelled").reduce((sum, order) => sum + Number(order.totals?.total || 0), 0);
  const loyaltyEarned = orders.reduce((sum, order) => sum + Number(order.loyaltyEarned || 0), 0);
  const loyaltyRedeemed = orders.reduce((sum, order) => sum + Number(order.loyaltyRedeemed || 0), 0);
  const loyaltyDiscounts = orders.reduce((sum, order) => sum + Number(order.loyaltyDiscount || order.totals?.loyaltyDiscount || 0), 0);
  const favoriteProducts = products.filter((product) => (user.favorites || []).includes(`${product.storeId}:${product.id}`));
  const favoriteStores = stores.filter((store) => orders.some((order) => order.storeId === store.id));
  const tabs = [["overview", "Σύνοψη"], ["orders", "Παραγγελίες"], ["loyalty", "Loyalty"], ["profile", "Προφίλ"], ["favorites", "Αγαπημένα"]];
  return <div className="max-h-[88vh] overflow-y-auto bg-slate-50 p-4 sm:p-6"><div className="rounded-[1.75rem] bg-slate-950 p-5 text-white"><div className="flex flex-wrap items-start justify-between gap-4"><div><p className="text-sm font-black uppercase tracking-widest text-emerald-300">Customer Dashboard</p><h2 className="mt-2 text-3xl font-black">Γεια σου, {user.name || "πελάτη"}</h2><p className="mt-2 text-sm font-semibold text-slate-300">Προφίλ, ιστορικό, loyalty πόντοι, ενεργές παραγγελίες και αγαπημένα προϊόντα.</p></div><button onClick={onLogout} className="rounded-2xl bg-white/10 px-4 py-3 text-sm font-black text-white ring-1 ring-white/15">Logout</button></div><div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-5"><DashboardCard icon="🔥" label="Ενεργές" value={activeOrders.length} dark /><DashboardCard icon="🧾" label="Παραγγελίες" value={orders.length} dark /><DashboardCard icon={loyaltyTier(user.loyaltyPoints, platform).icon} label={`Loyalty ${loyaltyTier(user.loyaltyPoints, platform).name}`} value={user.loyaltyPoints || 0} hint={`${Math.round(loyaltyProgress(user.loyaltyPoints, platform))}% προς επόμενο tier`} dark /><DashboardCard icon="💶" label="Σύνολο αγορών" value={formatEuro(totalSpent)} dark /><DashboardCard icon="❤️" label="Αγαπημένα" value={favoriteProducts.length} dark /></div></div><div className="mt-5 flex gap-2 overflow-x-auto">{tabs.map(([key, label]) => <button key={key} onClick={() => setTab(key)} className={`rounded-full px-4 py-3 text-sm font-black ${tab === key ? "bg-slate-950 text-white" : "bg-white text-slate-700 ring-1 ring-slate-200"}`}>{label}</button>)}</div>{tab === "overview" && <div className="mt-5 grid gap-5 xl:grid-cols-[0.9fr_1.1fr]"><Panel title="Γρήγορη σύνοψη"><InfoLine label="Τηλέφωνο" value={user.phone || "-"} /><InfoLine label="Email" value={user.email || "-"} /><InfoLine label="Διεύθυνση" value={`${user.address || "-"} ${user.floor || ""}`} /><InfoLine label="Loyalty διαθέσιμοι πόντοι" value={user.loyaltyPoints || 0} /><InfoLine label="Καταστήματα που έχεις χρησιμοποιήσει" value={favoriteStores.length} /><InfoLine label="Ολοκληρωμένες παραγγελίες" value={completedOrders.length} /></Panel><Panel title="Ενεργές παραγγελίες">{activeOrders.length === 0 ? <InfoBox icon="✅" title="Δεν έχεις ενεργή παραγγελία" /> : activeOrders.map((order) => <CustomerOrderCard key={order.id} order={order} onTrack={onTrack} onReorder={onReorder} onRateDriver={onRateDriver} compact />)}</Panel></div>}{tab === "orders" && <Panel title="Ιστορικό παραγγελιών">{orders.length === 0 ? <InfoBox icon="📭" title="Δεν υπάρχουν παραγγελίες" /> : orders.map((order) => <CustomerOrderCard key={order.id} order={order} onTrack={onTrack} onReorder={onReorder} onRateDriver={onRateDriver} />)}</Panel>}{tab === "loyalty" && <LoyaltyRewards user={user} orders={orders} platform={platform} loyaltyEarned={loyaltyEarned} loyaltyRedeemed={loyaltyRedeemed} loyaltyDiscounts={loyaltyDiscounts} />}{tab === "profile" && <Panel title="Προφίλ πελάτη"><div className="grid gap-4 sm:grid-cols-2"><Input label="Ονοματεπώνυμο" value={draft.name} onChange={(v) => setDraft({ ...draft, name: v })} /><Input label="Τηλέφωνο" value={draft.phone} onChange={(v) => setDraft({ ...draft, phone: v })} /><Input label="Email" value={draft.email} onChange={(v) => setDraft({ ...draft, email: v })} /><Input label="Κωδικός" type="password" value={draft.password} onChange={(v) => setDraft({ ...draft, password: v })} /><Input label="Διεύθυνση" value={draft.address} onChange={(v) => setDraft({ ...draft, address: v })} /><Input label="Όροφος / κουδούνι" value={draft.floor} onChange={(v) => setDraft({ ...draft, floor: v })} /></div><button onClick={() => onUpdate(draft)} className="rounded-2xl bg-slate-950 py-4 font-black text-white">Αποθήκευση προφίλ</button></Panel>}{tab === "favorites" && <Panel title="Αγαπημένα προϊόντα">{favoriteProducts.length === 0 ? <InfoBox icon="🤍" title="Δεν έχεις αγαπημένα ακόμα" /> : <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">{favoriteProducts.map((product) => <article key={`${product.storeId}-${product.id}`} className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100"><div className="grid h-28 w-full overflow-hidden place-items-center rounded-2xl bg-white text-5xl"><MediaBox src={product.image} fallback={product.emoji || "🍽️"} imgClassName="h-full w-full object-cover" /></div><p className="mt-3 flex items-center gap-2 text-xs font-black uppercase tracking-widest text-emerald-600"><span className="grid h-6 w-6 overflow-hidden place-items-center rounded-lg bg-white"><MediaBox src={product.storeLogo} fallback={product.storeLogoEmoji || "🏪"} className="text-sm" /></span>{product.storeName}</p><h4 className="mt-1 font-black">{product.title}</h4><p className="mt-1 text-sm font-semibold leading-6 text-slate-500">{product.description}</p><p className="mt-3 text-lg font-black">{formatEuro(product.price)}</p><div className="mt-4 grid gap-2"><button onClick={() => onOpenProduct(product)} className="rounded-2xl bg-emerald-500 py-3 text-sm font-black text-white">Παραγγελία</button><button onClick={() => onFavorite(product)} className="rounded-2xl bg-rose-50 py-3 text-sm font-black text-rose-700">Αφαίρεση</button></div></article>)}</div>}</Panel>}</div>;
}

function LoyaltyRewards({ user, orders, platform, loyaltyEarned, loyaltyRedeemed, loyaltyDiscounts }) {
  const tier = loyaltyTier(user.loyaltyPoints, platform);
  const progress = loyaltyProgress(user.loyaltyPoints, platform);
  const streak = calculateStreak(orders);
  const nextText = tier.next ? `${Math.max(0, tier.next - Number(user.loyaltyPoints || 0))} πόντοι για ${tier.key === "starter" ? "Silver" : tier.key === "silver" ? "Gold" : "Black"}` : "Έφτασες το ανώτερο tier";
  return <div className="mt-5 grid gap-5 xl:grid-cols-[0.85fr_1.15fr]"><div className="overflow-hidden rounded-[1.75rem] bg-gradient-to-br from-amber-400 via-orange-400 to-rose-500 p-5 text-white shadow-xl"><div className="flex items-start justify-between gap-4"><div><p className="text-xs font-black uppercase tracking-[0.2em] text-white/80">Road Runner Rewards</p><h3 className="mt-2 text-3xl font-black">{tier.icon} {tier.name}</h3><p className="mt-1 text-5xl font-black">{user.loyaltyPoints || 0}</p><p className="text-sm font-black text-white/80">διαθέσιμοι πόντοι</p></div><div className="rounded-3xl bg-white/20 px-4 py-3 text-right ring-1 ring-white/25"><p className="text-xs font-black text-white/80">Streak</p><p className="text-2xl font-black">🔥 {streak}</p></div></div><div className="mt-6 rounded-full bg-white/20 p-1"><div className="h-3 rounded-full bg-white" style={{ width: `${progress}%` }} /></div><p className="mt-3 text-sm font-black text-white/90">{nextText}</p><div className="mt-5 grid gap-3 sm:grid-cols-3"><MiniMetric dark label="Earn boost" value={`x${tier.multiplier}`} /><MiniMetric dark label="Streak bonus" value={`+${platform.loyaltyStreakBonusPoints || 0}`} /><MiniMetric dark label="Redeem" value={`${platform.loyaltyRedeemPoints} pts`} /></div></div><Panel title="Προηγμένο loyalty wallet"><InfoLine label="Κανόνας" value={loyaltyRuleText(platform)} /><InfoLine label="Συνολικά κερδισμένοι πόντοι" value={loyaltyEarned} /><InfoLine label="Συνολικά εξαργυρωμένοι πόντοι" value={loyaltyRedeemed} /><InfoLine label="Συνολική έκπτωση από loyalty στα fees" value={formatEuro(loyaltyDiscounts)} /><InfoLine label="Τρέχον tier" value={`${tier.icon} ${tier.name}`} /><InfoLine label="Daily streak bonus" value={`+${platform.loyaltyStreakBonusPoints || 0} πόντοι όταν υπάρχει συνεχόμενο activity`} /><InfoLine label="Πού εφαρμόζεται" value="Μόνο σε service fee + delivery fee" /><div className="rounded-2xl bg-emerald-50 p-4 text-sm font-bold leading-6 text-emerald-900 ring-1 ring-emerald-100">Το loyalty πλέον δουλεύει σαν gamified wallet: tier progress, streak bonus, earn boost και καθαρή εξαργύρωση στα platform fees χωρίς να επηρεάζει τον τζίρο του καταστήματος.</div></Panel></div>;
}

function CustomerOrderCard({ order, onTrack, onReorder, onRateDriver, compact = false }) {
  const canRate = order.status === "completed" && order.driverId && onRateDriver;
  return (
    <article className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <p className="text-lg font-black">#{order.id}</p>
          <p className="mt-1 flex items-center gap-2 text-sm font-black text-emerald-700">
            <span className="grid h-7 w-7 overflow-hidden place-items-center rounded-lg bg-white"><MediaBox src={order.storeSnapshot.logo} fallback={order.storeSnapshot.logoEmoji || "🏪"} className="text-sm" /></span>
            {order.storeSnapshot.name}
          </p>
          <p className="mt-1 text-sm font-bold text-slate-600">{new Date(order.createdAt).toLocaleString("el-GR")} · {serviceLabel(order.deliveryType)}</p>
          <p className="mt-1 text-xs font-black text-slate-500">{statusLabels[order.status]} · {paymentLabel(order.paymentMethod)}</p>
          {(order.loyaltyEarned || order.loyaltyRedeemed) && <p className="mt-1 text-xs font-black text-amber-700">⭐ +{order.loyaltyEarned || 0} πόντοι · χρήση {order.loyaltyRedeemed || 0} · έκπτωση {formatEuro(order.loyaltyDiscount || order.totals?.loyaltyDiscount || 0)}</p>}
          {order.driverSnapshot && <p className="mt-1 text-xs font-black text-amber-700">🛵 {order.driverSnapshot.name} · {order.driverSnapshot.phone} · Rating {order.driverRating?.rating ? `${order.driverRating.rating}/5` : "αναμονή"}</p>}
        </div>
        <div className="rounded-2xl bg-white px-4 py-3 text-right ring-1 ring-slate-100">
          <p className="text-xs font-black text-slate-500">Σύνολο</p>
          <p className="text-xl font-black">{formatEuro(order.totals.total)}</p>
        </div>
      </div>
      {!compact && <div className="mt-3 grid gap-2">{order.items.map((item) => <div key={item.key} className="rounded-2xl bg-white p-3 text-sm ring-1 ring-slate-100"><p className="flex items-center gap-2 font-black"><span className="grid h-8 w-8 overflow-hidden place-items-center rounded-lg bg-slate-50 text-base"><MediaBox src={item.image} fallback={item.emoji || "🍽️"} className="text-base" /></span>{item.qty}x {item.title}</p><p className="text-slate-500">{item.optionText}</p>{item.bonusQty > 0 && <p className="text-xs font-black text-emerald-700">🎁 +{item.bonusQty} δώρο</p>}{item.offerType === "bundle" && item.bundleLabel && <p className="text-xs font-black text-amber-700">🤝 {item.bundleLabel}</p>}</div>)}</div>}
      {canRate && (
        <div className="mt-4 rounded-2xl bg-amber-50 p-3 ring-1 ring-amber-100">
          <p className="text-sm font-black text-amber-950">Αξιολόγηση διανομέα</p>
          <div className="mt-2 flex flex-wrap gap-2">
            {[1, 2, 3, 4, 5].map((star) => (
              <button key={star} onClick={() => onRateDriver(order.id, star)} className={`rounded-full px-3 py-2 text-sm font-black ${Number(order.driverRating?.rating || 0) === star ? "bg-amber-500 text-white" : "bg-white text-amber-800 ring-1 ring-amber-100"}`}>{star} ⭐</button>
            ))}
          </div>
          {order.driverRating?.rating && <p className="mt-2 text-xs font-bold text-amber-800">Έδωσες {order.driverRating.rating}/5. Αν είναι πάνω από το όριο επιβράβευσης, ο διανομέας παίρνει bonus.</p>}
        </div>
      )}
      <div className="mt-4 grid gap-2 sm:grid-cols-2">
        <button onClick={() => onTrack(order)} className="rounded-2xl bg-slate-950 py-3 text-sm font-black text-white">Tracking</button>
        <button onClick={() => onReorder(order)} className="rounded-2xl bg-emerald-500 py-3 text-sm font-black text-white">Επανάληψη</button>
      </div>
    </article>
  );
}

function CustomerAuth({ mode, setMode, form, setForm, error, onRegister, onLogin }) {
  const isRegister = mode === "register";
  return <form onSubmit={isRegister ? onRegister : onLogin} className="p-6 sm:p-8"><div className="mx-auto grid h-16 w-16 place-items-center rounded-full bg-emerald-100 text-3xl">👤</div><h2 className="mt-5 text-center text-3xl font-black">{isRegister ? "Εγγραφή πελάτη" : "Είσοδος πελάτη"}</h2>{error && <p className="mt-4 rounded-2xl bg-rose-50 p-4 text-sm font-black text-rose-700 ring-1 ring-rose-100">{error}</p>}<div className="mt-6 grid gap-4">{isRegister && <><Input label="Ονοματεπώνυμο" value={form.name} onChange={(v) => setForm({ ...form, name: v })} required /><Input label="Email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} /></>}<Input label="Τηλέφωνο" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} required /><Input label="Κωδικός" type="password" value={form.password} onChange={(v) => setForm({ ...form, password: v })} required />{isRegister && <><Input label="Διεύθυνση" value={form.address} onChange={(v) => setForm({ ...form, address: v })} /><Input label="Όροφος" value={form.floor} onChange={(v) => setForm({ ...form, floor: v })} /></>}</div><button className="mt-6 w-full rounded-2xl bg-emerald-500 py-4 font-black text-white">{isRegister ? "Δημιουργία λογαριασμού" : "Είσοδος"}</button><button type="button" onClick={() => setMode(isRegister ? "login" : "register")} className="mt-3 w-full rounded-2xl bg-slate-100 py-4 text-sm font-black text-slate-700">{isRegister ? "Έχω λογαριασμό" : "Νέα εγγραφή"}</button></form>;
}

function DriverAuth({ mode, setMode, form, setForm, error, onRegister, onLogin }) {
  const isRegister = mode === "register";
  return <form onSubmit={isRegister ? onRegister : onLogin} className="p-6 sm:p-8"><div className="mx-auto grid h-16 w-16 place-items-center rounded-full bg-amber-100 text-3xl">🛵</div><h2 className="mt-5 text-center text-3xl font-black">{isRegister ? "Εγγραφή διανομέα" : "Είσοδος διανομέα"}</h2><p className="mx-auto mt-2 max-w-2xl text-center leading-7 text-slate-600">Οι διανομείς βλέπουν orders από όλα τα εγκεκριμένα καταστήματα και πρέπει να ακολουθούν κανόνες προσωπικών δεδομένων, παραλαβής, παράδοσης και διαχείρισης μετρητών.</p>{isRegister && <div className="mt-4 rounded-2xl bg-amber-50 p-4 text-sm font-bold leading-6 text-amber-900 ring-1 ring-amber-100">Με την αίτηση αποδέχεσαι ότι τα στοιχεία πελατών χρησιμοποιούνται μόνο για την αντίστοιχη παράδοση, ότι η ολοκλήρωση πατιέται μόνο μετά την πραγματική παράδοση και ότι χαμηλές αξιολογήσεις ή παράπονα μπορούν να οδηγήσουν σε αναστολή.</div>}{error && <p className="mt-4 rounded-2xl bg-rose-50 p-4 text-sm font-black text-rose-700 ring-1 ring-rose-100">{error}</p>}<div className="mt-6 grid gap-4 md:grid-cols-2">{isRegister && <Input label="Ονοματεπώνυμο" value={form.name} onChange={(v) => setForm({ ...form, name: v })} required />}<Input label="Τηλέφωνο" value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} required /><Input label="Κωδικός" type="password" value={form.password} onChange={(v) => setForm({ ...form, password: v })} required />{isRegister && <><Input label="Email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} /><label className="block"><span className="mb-2 block text-sm font-black text-slate-700">Όχημα</span><select value={form.vehicleType} onChange={(e) => setForm({ ...form, vehicleType: e.target.value })} className="h-14 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm font-semibold"><option value="motorbike">Μηχανάκι</option><option value="scooter">Scooter</option><option value="car">Αυτοκίνητο</option><option value="bicycle">Ποδήλατο</option></select></label><Input label="Πινακίδα" value={form.vehiclePlate} onChange={(v) => setForm({ ...form, vehiclePlate: v })} required /><Input label="Ταυτότητα / άδεια" value={form.idNumber} onChange={(v) => setForm({ ...form, idNumber: v })} required /><Input label="ΑΦΜ" value={form.taxNumber} onChange={(v) => setForm({ ...form, taxNumber: v })} /><Input label="IBAN" value={form.iban} onChange={(v) => setForm({ ...form, iban: v })} /><Input label="Περιοχή" value={form.area} onChange={(v) => setForm({ ...form, area: v })} /><TextArea label="Σημειώσεις" value={form.notes} onChange={(v) => setForm({ ...form, notes: v })} /></>}</div><button className="mt-6 w-full rounded-2xl bg-amber-500 py-4 font-black text-white">{isRegister ? "Αποστολή αίτησης" : "Είσοδος"}</button><button type="button" onClick={() => setMode(isRegister ? "login" : "register")} className="mt-3 w-full rounded-2xl bg-slate-100 py-4 text-sm font-black text-slate-700">{isRegister ? "Έχω λογαριασμό" : "Εγγραφή διανομέα"}</button></form>;
}

function DriverDashboard({ driver, activeOrders, availableOrders, platform, wallet, withdrawals, error, onOnline, onTrackingToggle, onLocationUpdate, onTrackingError, onAccept, onPickedUp, onStartDelivery, onComplete, onWithdraw, onLogout }) {
  const [amount, setAmount] = useState("");
  const approved = driver.status === "approved";
  const active = activeOrders[0] || null;
  const requests = withdrawals.filter((request) => request.driverId === driver.id).slice(0, 5);
  const trackingSupported = typeof navigator !== "undefined" && Boolean(navigator.geolocation);
  useEffect(() => {
    if (!platform.liveDriverTrackingEnabled || !driver.online || !driver.liveTrackingEnabled || !trackingSupported) return undefined;
    const watchId = navigator.geolocation.watchPosition(
      (position) => onLocationUpdate({ lat: position.coords.latitude, lng: position.coords.longitude, accuracy: position.coords.accuracy, heading: position.coords.heading, speed: position.coords.speed }),
      (geoError) => onTrackingError(geoError?.message || "Δεν δόθηκε άδεια GPS ή δεν βρέθηκε τοποθεσία."),
      { enableHighAccuracy: true, maximumAge: 5000, timeout: 15000 }
    );
    return () => navigator.geolocation.clearWatch(watchId);
  }, [driver.id, driver.online, driver.liveTrackingEnabled, platform.liveDriverTrackingEnabled]);
  return <div className="max-h-[88vh] overflow-y-auto bg-slate-50 p-4 sm:p-6"><div className="rounded-[1.75rem] bg-slate-950 p-5 text-white"><div className="flex flex-wrap items-start justify-between gap-4"><div><p className="text-sm font-black uppercase tracking-widest text-amber-300">Shared Driver Fleet</p><h2 className="mt-2 text-3xl font-black">{driver.name}</h2><p className="mt-2 text-sm font-semibold text-slate-300">{vehicleLabel(driver.vehicleType)} · {driver.vehiclePlate} · {driver.phone}</p></div><div className="flex gap-2">{approved && <button onClick={() => onOnline(!driver.online)} className={`rounded-2xl px-4 py-3 text-sm font-black ${driver.online ? "bg-emerald-400 text-emerald-950" : "bg-white/10 text-white"}`}>{driver.online ? "🟢 Online" : "⚪ Offline"}</button>}<button onClick={onLogout} className="rounded-2xl bg-white/10 px-4 py-3 text-sm font-black text-white">Logout</button></div></div><div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4"><DashboardCard icon="✅" label="Status" value={driverStatusLabel(driver.status)} dark /><DashboardCard icon="🧾" label="Active" value={activeOrders.length} dark /><DashboardCard icon="💰" label="Wallet" value={formatEuro(wallet?.available || 0)} hint={`min ${formatEuro(platform.driverMinWithdraw)}`} dark /><DashboardCard icon="⭐" label="Rating" value={wallet?.averageRating || driver.rating || 5} hint={`${wallet?.ratedOrders || 0} ratings`} dark /></div></div>{approved && <Panel title="Live GPS tracking"><div className="rounded-2xl bg-blue-50 p-4 text-sm font-bold leading-6 text-blue-950 ring-1 ring-blue-100">Το live tracking λειτουργεί μέσω browser GPS. Χρειάζεται HTTPS, ανοιχτό browser, άδεια τοποθεσίας και ενεργό Online + GPS από τον διανομέα. Η θέση εμφανίζεται σε πελάτη, κατάστημα και Platform Admin όσο υπάρχει ενεργή διανομή.</div><div className="grid gap-3 sm:grid-cols-3"><Toggle label="GPS tracking" checked={Boolean(driver.liveTrackingEnabled)} onChange={onTrackingToggle} /><InfoLine label="Υποστήριξη browser" value={trackingSupported ? "Ναι" : "Όχι"} /><InfoLine label="Τελευταία ενημέρωση" value={driver.lastLocation ? locationAgeText(driver.lastLocation) : "Δεν υπάρχει ακόμα"} /></div>{driver.trackingError && <p className="rounded-2xl bg-rose-50 p-3 text-sm font-black text-rose-700 ring-1 ring-rose-100">GPS error: {driver.trackingError}</p>}<DriverLiveMap location={driver.lastLocation} title="Η τρέχουσα θέση σου" /></Panel>}{approved && <Panel title="Driver Wallet"><p className="text-sm font-semibold text-slate-500">Ο οδηγός παίρνει {platform.driverCommissionPercent}% από κάθε delivery fee. Αν delivery fee = 1€, wallet = {formatEuro(Number(platform.driverCommissionPercent || 40) / 100)}. Με rating τουλάχιστον {platform.driverRewardMinRating}/5 μπορεί να παίρνει bonus {formatEuro(platform.driverRewardBonusPerOrder)} ανά ολοκληρωμένη αξιολογημένη διανομή.</p><div className="rounded-2xl bg-amber-50 p-4 text-sm font-bold leading-6 text-amber-900 ring-1 ring-amber-100">{platform.deliveryFlowText}<br /><br />{platform.cashHandlingText}</div><div className="grid gap-3 sm:grid-cols-4"><InfoLine label="Earned" value={formatEuro(wallet?.earned)} /><InfoLine label="Base delivery" value={formatEuro(wallet?.baseEarned)} /><InfoLine label="Rating bonus" value={formatEuro(wallet?.ratingBonus)} /><InfoLine label="Pending" value={formatEuro(wallet?.pending)} /><InfoLine label="Paid" value={formatEuro(wallet?.paid)} /><InfoLine label="Available" value={formatEuro(wallet?.available)} /></div><div className="grid gap-3 sm:grid-cols-[1fr_auto]"><Input label="Withdraw amount" type="number" value={amount} onChange={setAmount} placeholder={String(platform.driverMinWithdraw)} /><button onClick={() => { onWithdraw(amount || wallet?.available); setAmount(""); }} disabled={(wallet?.available || 0) < Number(platform.driverMinWithdraw)} className="h-14 self-end rounded-2xl bg-slate-950 px-5 text-sm font-black text-white disabled:bg-slate-300">Request withdraw</button></div>{error && <p className="rounded-2xl bg-rose-50 p-3 text-sm font-black text-rose-700 ring-1 ring-rose-100">{error}</p>}{requests.map((request) => <InfoLine key={request.id} label={`${formatEuro(request.amount)} · ${request.status}`} value={new Date(request.createdAt).toLocaleString("el-GR")} />)}</Panel>}{!approved ? <InfoBox icon="⏳" title="Περιμένεις έγκριση Platform Admin" tone="amber" /> : !driver.online ? <InfoBox icon="📴" title="Είσαι offline" text="Γίνε online για να βλέπεις διαθέσιμες παραγγελίες από όλα τα καταστήματα." /> : <div className="mt-5 grid gap-5 xl:grid-cols-[0.9fr_1.1fr]"><Panel title="Τρέχουσα διανομή">{active ? <DriverOrderCard order={active} onPickedUp={onPickedUp} onStartDelivery={onStartDelivery} onComplete={onComplete} /> : <InfoBox icon="🛵" title="Δεν έχεις ενεργή διανομή" />}</Panel><Panel title="Διαθέσιμες παραγγελίες όλων των καταστημάτων">{availableOrders.length === 0 ? <InfoBox icon="📭" title="Δεν υπάρχουν διαθέσιμες παραγγελίες" /> : availableOrders.map((order) => <DriverOrderCard key={order.id} order={order} onAccept={active ? null : onAccept} />)}</Panel></div>}</div>;
}

function DriverOrderCard({ order, onAccept, onPickedUp, onStartDelivery, onComplete }) {
  const payout = Number(order.deliveryAssignment?.driverPayout || roundMoney(deliveryFeeForOrder(order) * (Number(order.deliveryAssignment?.driverCommissionPercent || 40) / 100)));
  const cashPayment = order.paymentMethod === "cash";
  return (
    <article className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100">
      <div className="flex flex-wrap justify-between gap-3">
        <div>
          <p className="text-lg font-black">#{order.id}</p>
          <p className="mt-1 flex items-center gap-2 text-sm font-black text-emerald-700"><span className="grid h-7 w-7 overflow-hidden place-items-center rounded-lg bg-white"><MediaBox src={order.storeSnapshot.logo} fallback={order.storeSnapshot.logoEmoji || "🏪"} className="text-sm" /></span>{order.storeSnapshot.name}</p>
          <p className="mt-1 text-sm font-bold text-slate-600">Pickup: {order.storeSnapshot.address} · ☎️ {order.storeSnapshot.phone}</p>
          <p className="mt-1 text-sm font-bold text-slate-800">Πελάτης: {order.customer.name} · ☎️ {order.customer.phone}</p>
          <p className="mt-1 text-sm font-bold text-slate-800">Προορισμός: {order.customer.address} {order.customer.floor}</p>
          <p className="mt-1 text-xs font-bold text-slate-500">{statusLabels[order.status]} · {paymentLabel(order.paymentMethod)} · {order.contactPreference === "phone" ? "Επικοινωνία με τηλέφωνο" : "Επικοινωνία με μήνυμα"}</p>
          {order.scheduledTime && <p className="mt-1 text-xs font-black text-amber-700">⏰ Προγραμματισμός: {order.scheduledTime}</p>}
          {order.customer.notes && <p className="mt-1 text-xs font-black text-slate-600">📝 Οδηγίες: {order.customer.notes}</p>}
        </div>
        <div className="rounded-2xl bg-white px-4 py-3 text-right ring-1 ring-slate-100">
          <p className="text-xs font-black text-slate-500">Wallet</p>
          <p className="text-xl font-black">{formatEuro(payout)}</p>
          <p className="text-xs font-bold text-amber-700">{Number(order.deliveryAssignment?.driverCommissionPercent || 40)}% delivery fee</p>
        </div>
      </div>
      <div className={`mt-4 rounded-2xl p-4 text-sm font-bold ring-1 ${cashPayment ? "bg-amber-50 text-amber-950 ring-amber-100" : "bg-emerald-50 text-emerald-950 ring-emerald-100"}`}>
        {cashPayment ? <>💶 Μετρητά: εισπράττεις {formatEuro(order.totals.total)} από τον πελάτη. {order.customer.changeFor ? `Ρέστα από ${order.customer.changeFor}.` : "Έλεγξε αν χρειάζονται ρέστα."}</> : <>💳 Πληρωμή: {paymentLabel(order.paymentMethod)}. Ακολούθησε τη διαδικασία POS/καταστήματος.</>}
      </div>
      <div className="mt-3 grid gap-2">
        {order.items.map((item) => (
          <div key={item.key} className="rounded-2xl bg-white p-3 text-sm ring-1 ring-slate-100">
            <p className="flex items-center gap-2 font-black"><span className="grid h-8 w-8 overflow-hidden place-items-center rounded-lg bg-slate-50 text-base"><MediaBox src={item.image} fallback={item.emoji || "🍽️"} className="text-base" /></span>{item.qty}x {item.title}</p>
            <p className="text-slate-500">{item.optionText}</p>
            {item.bonusQty > 0 && <p className="text-xs font-black text-emerald-700">🎁 +{item.bonusQty} δώρο</p>}
            {item.offerType === "bundle" && item.bundleLabel && <p className="text-xs font-black text-amber-700">🤝 {item.bundleLabel}</p>}
            {item.productNote && <p className="mt-1 text-xs font-black text-amber-700">Σχόλιο: {item.productNote}</p>}
          </div>
        ))}
      </div>
      <div className="mt-4 grid gap-2 sm:grid-cols-2">
        {onAccept && <button onClick={() => onAccept(order.id)} className="sm:col-span-2 rounded-2xl bg-amber-500 py-3 text-sm font-black text-white">Αποδοχή διανομής</button>}
        {onPickedUp && order.status === "driver_assigned" && <button onClick={() => onPickedUp(order.id)} className="rounded-2xl bg-slate-950 py-3 text-sm font-black text-white">Παρέλαβα από κατάστημα</button>}
        {onStartDelivery && order.status === "picked_up" && <button onClick={() => onStartDelivery(order.id)} className="rounded-2xl bg-emerald-500 py-3 text-sm font-black text-white">Ξεκίνησα προς πελάτη</button>}
        {onComplete && ["picked_up", "delivery"].includes(order.status) && <button onClick={() => onComplete(order.id)} className="rounded-2xl bg-emerald-600 py-3 text-sm font-black text-white">Ολοκλήρωση παράδοσης</button>}
      </div>
    </article>
  );
}

function MerchantPortal({ mode, setMode, loginForm, setLoginForm, appForm, setAppForm, error, onLogin, onApply }) {
  const apply = mode === "apply";
  return <form onSubmit={apply ? onApply : onLogin} className="p-6 sm:p-8"><div className="mx-auto grid h-16 w-16 place-items-center rounded-full bg-emerald-100 text-3xl">🏪</div><h2 className="mt-5 text-center text-3xl font-black">{apply ? "Αίτηση συμμετοχής καταστήματος" : "Merchant Login"}</h2><p className="mx-auto mt-2 max-w-2xl text-center leading-7 text-slate-600">Το Merchant Admin είναι ξεχωριστό από το Platform Admin. Ο καταστηματάρχης διαχειρίζεται προϊόντα, κατηγορίες και orders μόνο του δικού του καταστήματος.</p><div className="mt-4 rounded-2xl bg-amber-50 p-4 text-sm font-bold leading-6 text-amber-900 ring-1 ring-amber-100">Με την αίτηση αποδέχεσαι ότι η πλατφόρμα μπορεί να εφαρμόζει service/delivery fees προς τον πελάτη και να τα αλλάζει οποιαδήποτε στιγμή. Το κατάστημα βλέπει τα δικά του έσοδα προϊόντων, ενώ η πλατφόρμα διατηρεί τον κεντρικό έλεγχο κανόνων, fees και πρόσβασης.</div>{error && <p className={`mt-4 rounded-2xl p-4 text-sm font-black ring-1 ${error.includes("στάλθηκε") ? "bg-emerald-50 text-emerald-700 ring-emerald-100" : "bg-rose-50 text-rose-700 ring-rose-100"}`}>{error}</p>}{apply ? <div className="mt-6 grid gap-4 md:grid-cols-2"><Input label="Ιδιοκτήτης" value={appForm.ownerName} onChange={(v) => setAppForm({ ...appForm, ownerName: v })} required /><Input label="Τηλέφωνο ιδιοκτήτη / login" value={appForm.ownerPhone} onChange={(v) => setAppForm({ ...appForm, ownerPhone: v })} required /><Input label="Email" value={appForm.ownerEmail} onChange={(v) => setAppForm({ ...appForm, ownerEmail: v })} /><Input label="Κωδικός merchant" type="password" value={appForm.ownerPassword} onChange={(v) => setAppForm({ ...appForm, ownerPassword: v })} required /><Input label="Αριθμός ταυτότητας" value={appForm.ownerIdNumber} onChange={(v) => setAppForm({ ...appForm, ownerIdNumber: v })} /><Input label="ΑΦΜ" value={appForm.ownerTaxNumber} onChange={(v) => setAppForm({ ...appForm, ownerTaxNumber: v })} /><Input label="Όνομα καταστήματος" value={appForm.storeName} onChange={(v) => setAppForm({ ...appForm, storeName: v })} required /><Input label="Τηλέφωνο καταστήματος" value={appForm.storePhone} onChange={(v) => setAppForm({ ...appForm, storePhone: v })} /><Input label="Διεύθυνση καταστήματος" value={appForm.storeAddress} onChange={(v) => setAppForm({ ...appForm, storeAddress: v })} required /><Input label="Περιοχή" value={appForm.storeArea} onChange={(v) => setAppForm({ ...appForm, storeArea: v })} /><Input label="Τύπος καταστήματος" value={appForm.storeType} onChange={(v) => setAppForm({ ...appForm, storeType: v })} /><Input label="IBAN καταστήματος" value={appForm.iban} onChange={(v) => setAppForm({ ...appForm, iban: v })} /><div className="md:col-span-2"><TextArea label="Σημειώσεις" value={appForm.notes} onChange={(v) => setAppForm({ ...appForm, notes: v })} /></div></div> : <div className="mx-auto mt-6 grid max-w-md gap-4"><Input label="Τηλέφωνο merchant" value={loginForm.phone} onChange={(v) => setLoginForm({ ...loginForm, phone: v })} /><Input label="Κωδικός" type="password" value={loginForm.password} onChange={(v) => setLoginForm({ ...loginForm, password: v })} /></div>}<button className="mt-6 w-full rounded-2xl bg-emerald-500 py-4 font-black text-white">{apply ? "Αποστολή αίτησης" : "Είσοδος Merchant"}</button><button type="button" onClick={() => setMode(apply ? "login" : "apply")} className="mt-3 w-full rounded-2xl bg-slate-100 py-4 text-sm font-black text-slate-700">{apply ? "Έχω ήδη έγκριση / Login" : "Νέα αίτηση καταστήματος"}</button></form>;
}

function MerchantDashboard({ store, users, orders, stats, platform, onSaveStore, onSaveProduct, onUpdateProduct, onDeleteProduct, onBanCustomer, onUnbanCustomer, onStatus, onLogout }) {
  const [tab, setTab] = useState("overview");
  const [profile, setProfile] = useState(store.profile);
  const [categoryText, setCategoryText] = useState(store.categories.join(", "));
  const [draft, setDraft] = useState(() => newProductDraft(store.categories[0] || "Καφέδες"));
  const [editingId, setEditingId] = useState(null);
  const seenNewOrderIdsRef = useRef(new Set(orders.filter((order) => order.status === "new").map((order) => order.id)));

  useEffect(() => {
    setProfile(store.profile);
    setCategoryText(store.categories.join(", "));
  }, [store]);

  useEffect(() => {
    const newOrders = orders.filter((order) => order.status === "new");
    const unseen = newOrders.filter((order) => !seenNewOrderIdsRef.current.has(order.id));
    if (unseen.length && tab === "orders" && store.orderSoundMuted !== true) playNewOrderSound(5, Number(store.orderSoundVolume ?? 0.9));
    newOrders.forEach((order) => seenNewOrderIdsRef.current.add(order.id));
  }, [orders, tab, store.orderSoundMuted, store.orderSoundVolume]);

  const storeBans = store.customerBans || [];
  const customerRows = (() => {
    const rows = new Map();
    orders.forEach((order) => {
      const linked = users.find((user) => user.id === order.userId || user.phone === order.customer?.phone);
      const userId = order.userId || linked?.id || "";
      const phone = linked?.phone || order.customer?.phone || "";
      const key = userId || phone || order.id;
      const existing = rows.get(key) || {
        userId,
        name: linked?.name || order.customer?.name || "Πελάτης",
        phone,
        email: linked?.email || "",
        orders: 0,
        spent: 0,
        banned: false,
      };
      existing.orders += 1;
      existing.spent = roundMoney(existing.spent + Number(order.totals?.total || 0));
      existing.banned = storeBans.some((ban) => (userId && ban.userId === userId) || (phone && ban.phone === phone));
      rows.set(key, existing);
    });
    return Array.from(rows.values());
  })();

  const tabs = [
    ["overview", "Σύνοψη"],
    ["orders", `Παραγγελίες${orders.filter((order) => order.status === "new").length ? ` (${orders.filter((order) => order.status === "new").length})` : ""}`],
    ["customers", "Πελάτες / Ban"],
    ["products", "Προϊόντα & Προσφορές"],
    ["settings", "Store setup"],
  ];

  function submitProduct(e) {
    e.preventDefault();
    onSaveProduct(store.id, {
      ...draft,
      id: editingId || draft.id,
      price: Number(draft.price || 0),
      oldPrice: draft.oldPrice === "" ? null : Number(draft.oldPrice || 0),
      offerType: draft.offerType || "standard",
      bundleProductId: draft.bundleProductId || "",
      bundleLabel: draft.bundleLabel || "",
      promo: Boolean(draft.promo || draft.offerType === "bogo" || draft.offerType === "bundle"),
      options: {
        sweetness: splitList(draft.options.sweetness),
        milk: splitList(draft.options.milk),
        extras: splitList(draft.options.extras),
      },
    });
    setDraft(newProductDraft(store.categories[0] || "Καφέδες"));
    setEditingId(null);
  }

  function editProduct(product) {
    setDraft(productToDraft(product));
    setEditingId(product.id);
    setTab("products");
  }

  function toggleCustomerBan(customer) {
    const existing = storeBans.find((ban) => (customer.userId && ban.userId === customer.userId) || (customer.phone && ban.phone === customer.phone));
    if (existing) {
      onUnbanCustomer(store.id, existing.id);
      return;
    }
    onBanCustomer(store.id, customer, "Αποκλεισμός από Merchant");
  }

  return (
    <div className="max-h-[88vh] overflow-y-auto bg-slate-50 p-4 sm:p-6">
      <div className="rounded-[1.75rem] bg-slate-950 p-5 text-white">
        <div className="flex flex-wrap justify-between gap-4">
          <div>
            <p className="text-sm font-black uppercase tracking-widest text-emerald-300">Merchant Admin</p>
            <div className="mt-2 flex items-center gap-3">
              <span className="grid h-14 w-14 overflow-hidden place-items-center rounded-2xl bg-white/10 text-3xl ring-1 ring-white/15">
                <MediaBox src={store.profile.logo} fallback={store.profile.logoEmoji || "🏪"} />
              </span>
              <h2 className="text-3xl font-black">{store.profile.name}</h2>
            </div>
            <p className="mt-2 text-sm font-semibold text-slate-300">Ο Merchant ελέγχει προϊόντα, orders και μπορεί να αποκλείει πελάτες μόνο από το δικό του κατάστημα.</p>
          </div>
          <button onClick={onLogout} className="rounded-2xl bg-white/10 px-4 py-3 text-sm font-black text-white">Logout</button>
        </div>
        <div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
          <DashboardCard icon="🧾" label="Orders" value={stats.orders} dark />
          <DashboardCard icon="🔥" label="Active" value={stats.active} dark />
          <DashboardCard icon="💶" label="Product revenue" value={formatEuro(stats.productRevenue)} dark />
          <DashboardCard icon="🚫" label="Banned customers" value={storeBans.length} dark />
          <DashboardCard icon="📊" label="Μέσο order" value={formatEuro(stats.avgOrder)} dark />
        </div>
      </div>

      <div className="mt-5 flex gap-2 overflow-x-auto">
        {tabs.map(([key, label]) => (
          <button key={key} onClick={() => setTab(key)} className={`rounded-full px-4 py-3 text-sm font-black ${tab === key ? "bg-slate-950 text-white" : "bg-white text-slate-700 ring-1 ring-slate-200"}`}>
            {label}
          </button>
        ))}
      </div>

      {tab === "overview" && (
        <Panel title="Store οικονομικά">
          <div className="rounded-2xl bg-amber-50 p-4 text-sm font-bold leading-6 text-amber-900 ring-1 ring-amber-100">Οι χρεώσεις service/delivery fees της πλατφόρμας εμφανίζονται στον πελάτη και μπορούν να αλλάξουν από την πλατφόρμα οποιαδήποτε στιγμή. Το κατάστημα βλέπει εδώ μόνο τα δικά του έσοδα προϊόντων.</div>
          <InfoLine label="Τζίρος προϊόντων καταστήματος" value={formatEuro(stats.productRevenue)} />
          <InfoLine label="Ολοκληρωμένες παραγγελίες" value={stats.completed} />
          <InfoLine label="Ενεργές παραγγελίες" value={stats.active} />
          <InfoLine label="Μέσο order προϊόντων" value={formatEuro(stats.avgOrder)} />
          <InfoLine label="Προϊόντα" value={store.products.length} />
          <InfoLine label="Store bans" value={storeBans.length} />
        </Panel>
      )}

      {tab === "orders" && <div className="mt-5"><div className="mb-4 rounded-2xl bg-amber-50 p-4 ring-1 ring-amber-100"><div className="flex flex-wrap items-start justify-between gap-3"><div><p className="text-sm font-black text-amber-950">🚨 Δυνατή ηχητική ειδοποίηση νέας παραγγελίας</p><p className="mt-1 text-xs font-bold text-amber-800">Παίζει έντονο alarm για 5 δευτερόλεπτα σε κάθε νέα παραγγελία όταν το Order tab είναι ανοιχτό.</p></div><div className="flex flex-wrap gap-2"><button onClick={() => playNewOrderSound(3, Number(store.orderSoundVolume ?? 0.9))} className="rounded-full bg-white px-3 py-2 text-xs font-black text-amber-800 ring-1 ring-amber-100">Test loud sound</button><button onClick={() => onSaveStore({ ...store, orderSoundMuted: !store.orderSoundMuted })} className={`rounded-full px-3 py-2 text-xs font-black ${store.orderSoundMuted ? "bg-slate-950 text-white" : "bg-emerald-500 text-white"}`}>{store.orderSoundMuted ? "🔇 Muted" : "🔊 Sound on"}</button></div></div><div className="mt-4 grid gap-3 rounded-2xl bg-white p-3 ring-1 ring-amber-100 sm:grid-cols-[1fr_auto]"><label className="block"><span className="mb-2 flex items-center justify-between text-xs font-black text-amber-900"><span>Ένταση ειδοποίησης</span><span>{Math.round(Number(store.orderSoundVolume ?? 0.9) * 100)}%</span></span><input type="range" min="0.2" max="1" step="0.05" value={Number(store.orderSoundVolume ?? 0.9)} onChange={(e) => onSaveStore({ ...store, orderSoundVolume: Number(e.target.value) })} className="w-full accent-amber-500" /></label><div className="flex gap-2 self-end"><button type="button" onClick={() => onSaveStore({ ...store, orderSoundVolume: 0.6 })} className="rounded-full bg-amber-50 px-3 py-2 text-xs font-black text-amber-800 ring-1 ring-amber-100">60%</button><button type="button" onClick={() => onSaveStore({ ...store, orderSoundVolume: 0.85 })} className="rounded-full bg-amber-50 px-3 py-2 text-xs font-black text-amber-800 ring-1 ring-amber-100">85%</button><button type="button" onClick={() => onSaveStore({ ...store, orderSoundVolume: 1 })} className="rounded-full bg-rose-50 px-3 py-2 text-xs font-black text-rose-800 ring-1 ring-rose-100">MAX</button></div></div></div><OrdersList orders={orders} platform={platform} onStatus={onStatus} storeView /></div>}

      {tab === "customers" && (
        <Panel title="Πελάτες καταστήματος & αποκλεισμοί">
          {customerRows.length === 0 ? (
            <InfoBox icon="👤" title="Δεν υπάρχουν πελάτες ακόμα" />
          ) : (
            customerRows.map((customer) => (
              <article key={customer.userId || customer.phone} className="rounded-2xl bg-slate-50 p-4 ring-1 ring-slate-100">
                <div className="flex flex-wrap items-start justify-between gap-3">
                  <div>
                    <p className="text-lg font-black">{customer.name}</p>
                    <p className="text-sm font-bold text-slate-600">{customer.phone} · {customer.email || "χωρίς email"}</p>
                    <p className="text-xs font-black text-emerald-700">Orders {customer.orders} · Spend {formatEuro(customer.spent)} · {customer.banned ? "Banned από αυτό το κατάστημα" : "Allowed"}</p>
                  </div>
                  <button onClick={() => toggleCustomerBan(customer)} className={`rounded-full px-4 py-2 text-xs font-black ${customer.banned ? "bg-emerald-100 text-emerald-800" : "bg-rose-100 text-rose-800"}`}>
                    {customer.banned ? "Unban από κατάστημα" : "Ban από κατάστημα"}
                  </button>
                </div>
              </article>
            ))
          )}
          {storeBans.length > 0 && (
            <div className="mt-4 rounded-2xl bg-rose-50 p-4 ring-1 ring-rose-100">
              <p className="font-black text-rose-900">Ενεργοί αποκλεισμοί</p>
              {storeBans.map((ban) => (
                <div key={ban.id} className="mt-2 flex flex-wrap items-center justify-between gap-2 rounded-xl bg-white p-3 text-sm font-bold">
                  <span>{ban.name} · {ban.phone} · {ban.reason}</span>
                  <button onClick={() => onUnbanCustomer(store.id, ban.id)} className="rounded-full bg-emerald-100 px-3 py-2 text-xs font-black text-emerald-800">Remove</button>
                </div>
              ))}
            </div>
          )}
        </Panel>
      )}

      {tab === "products" && (
        <div className="mt-5 grid gap-5 xl:grid-cols-[0.95fr_1.05fr]">
          <ProductEditor draft={draft} setDraft={setDraft} categories={store.categories} products={store.products} editingId={editingId} onSubmit={submitProduct} onCancel={() => { setDraft(newProductDraft(store.categories[0] || "Καφέδες")); setEditingId(null); }} />
          <ProductsList products={store.products} onEdit={editProduct} onUpdate={(id, patch) => onUpdateProduct(store.id, id, patch)} onDelete={(id) => onDeleteProduct(store.id, id)} />
        </div>
      )}

      {tab === "settings" && (
        <div className="mt-5 grid gap-5 xl:grid-cols-[1fr_0.9fr]">
          <Panel title="Store setup">
            <div className="grid gap-4 sm:grid-cols-2">
              <Input label="Όνομα" value={profile.name} onChange={(v) => setProfile({ ...profile, name: v })} />
              <ImageUpload label="Logo καταστήματος" value={profile.logo || ""} onChange={(logo) => setProfile({ ...profile, logo })} fallback={profile.logoEmoji || "🏪"} />
              <Input label="Fallback emoji" value={profile.logoEmoji} onChange={(v) => setProfile({ ...profile, logoEmoji: v })} />
              <Input label="Υπότιτλος" value={profile.subtitle} onChange={(v) => setProfile({ ...profile, subtitle: v })} />
              <Input label="Τηλέφωνο" value={profile.phone} onChange={(v) => setProfile({ ...profile, phone: v })} />
              <Input label="Διεύθυνση" value={profile.address} onChange={(v) => setProfile({ ...profile, address: v })} />
              <Input label="Περιοχή" value={profile.area} onChange={(v) => setProfile({ ...profile, area: v })} />
              <Input label="Ωράριο" value={profile.openHours} onChange={(v) => setProfile({ ...profile, openHours: v })} />
              <Input label="Χρόνος παράδοσης" value={profile.deliveryTime} onChange={(v) => setProfile({ ...profile, deliveryTime: v })} />
            </div>
            <TextArea label="Περιγραφή" value={profile.description} onChange={(v) => setProfile({ ...profile, description: v })} />
            <button onClick={() => onSaveStore({ ...store, profile })} className="rounded-2xl bg-slate-950 py-4 font-black text-white">Αποθήκευση store setup</button>
          </Panel>
          <Panel title="Κατηγορίες">
            <TextArea label="Με κόμμα" value={categoryText} onChange={setCategoryText} />
            <button onClick={() => onSaveStore({ ...store, categories: splitList(categoryText) })} className="rounded-2xl bg-emerald-500 py-4 font-black text-white">Αποθήκευση κατηγοριών</button>
          </Panel>
        </div>
      )}
    </div>
  );
}

function PlatformLogin({ pin, value, onChange, onUnlock }) {
  return <div className="p-6 sm:p-8"><div className="mx-auto grid h-16 w-16 place-items-center rounded-full bg-slate-100 text-3xl">🔐</div><h2 className="mt-5 text-center text-3xl font-black">Platform Admin</h2><p className="mx-auto mt-2 max-w-md text-center leading-7 text-slate-600">Κεντρικός έλεγχος πλατφόρμας. Η πρόσβαση προορίζεται μόνο για εξουσιοδοτημένη διαχείριση.</p><div className="mx-auto mt-6 max-w-sm"><Input label="Platform PIN" value={value} onChange={onChange} /><button onClick={onUnlock} className="mt-4 w-full rounded-2xl bg-slate-950 py-4 font-black text-white">Είσοδος</button></div></div>;
}

function PlatformAdmin({ platform, setPlatform, stats, stores, applications, orders, users, drivers, withdrawals, onApproveApplication, onRejectApplication, onUpdateStore, onDeleteStore, onUpdateCustomer, onDeleteCustomer, onUpdateDriver, onUpdateWithdrawal, onStatus, onReset, onLock }) {
  const [tab, setTab] = useState("overview");
  const tabs = [
    ["overview", "Overview"],
    ["users", "Χρήστες"],
    ["applications", "Αιτήσεις"],
    ["stores", "Καταστήματα"],
    ["orders", "Orders"],
    ["drivers", "Drivers"],
    ["fees", "Fees"],
    ["controls", "Platform"],
    ["pages", "Σελίδες"],
  ];

  return (
    <div className="max-h-[88vh] overflow-y-auto p-5 sm:p-6">
      <div className="flex flex-wrap justify-between gap-3">
        <div>
          <h2 className="text-3xl font-black">Platform Admin</h2>
          <p className="mt-1 text-sm font-semibold text-slate-500">Κεντρικός έλεγχος για χρήστες, καταστήματα, delivery, fees, branding, νομικές σελίδες και αποκλεισμούς.</p>
        </div>
        <div className="flex gap-2">
          <button onClick={onReset} className="rounded-2xl bg-amber-50 px-4 py-3 text-sm font-black text-amber-700">Reset data</button>
          <button onClick={onLock} className="rounded-2xl bg-slate-100 px-4 py-3 text-sm font-black text-slate-700">Lock</button>
        </div>
      </div>

      <div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-8">
        <Stat label="Users" value={stats.users} icon="👤" />
        <Stat label="Banned" value={stats.bannedUsers} icon="🚫" />
        <Stat label="Stores" value={stats.approvedStores} icon="🏪" />
        <Stat label="Pending apps" value={stats.pendingStores} icon="⏳" />
        <Stat label="Orders" value={stats.orders} icon="🧾" />
        <Stat label="Avg basket" value={formatEuro(stats.avgBasket)} icon="🛒" />
        <Stat label="Platform net" value={formatEuro(stats.platformNet)} icon="🏦" />
        <Stat label="Online drivers" value={stats.onlineDrivers} icon="🛵" />
      </div>

      <div className="mt-6 flex flex-wrap gap-2">
        {tabs.map(([key, label]) => (
          <button key={key} onClick={() => setTab(key)} className={`rounded-full px-4 py-3 text-sm font-black ${tab === key ? "bg-slate-950 text-white" : "bg-white text-slate-700 ring-1 ring-slate-200"}`}>
            {label}
          </button>
        ))}
      </div>

      {tab === "overview" && (
        <div className="grid gap-5 xl:grid-cols-2">
          <Panel title="Οικονομικά πλατφόρμας">
            <InfoLine label="Service fees" value={formatEuro(stats.serviceFees)} />
            <InfoLine label="Delivery fees" value={formatEuro(stats.deliveryFees)} />
            <InfoLine label="Loyalty discounts στα fees" value={formatEuro(stats.loyaltyDiscounts)} />
            <InfoLine label="Driver wallets" value={formatEuro(stats.driverEarnings)} />
            <InfoLine label="Καθαρό platform net" value={formatEuro(stats.platformNet)} />
            <InfoLine label="Pending driver withdraw" value={formatEuro(stats.driverPendingWithdrawals)} />
          </Panel>
          <Panel title="Έλεγχος δεδομένων">
            <InfoLine label="Ενεργοί χρήστες" value={stats.activeUsers} />
            <InfoLine label="Banned/suspended χρήστες" value={stats.bannedUsers} />
            <InfoLine label="Returning users" value={stats.returningUsers} />
            <InfoLine label="Completed orders" value={stats.completedOrders} />
            <InfoLine label="Cancelled orders" value={stats.cancelledOrders} />
            <InfoLine label="Suspended/ban καταστήματα" value={stats.suspendedStores} />
            <InfoLine label="Hidden stores" value={stats.hiddenStores} />
            <InfoLine label="Loyalty issued/redeemed" value={`${stats.loyaltyPointsIssued} / ${stats.loyaltyPointsRedeemed}`} />
          </Panel>
        </div>
      )}

      {tab === "users" && <PlatformUsers users={users} orders={orders} stores={stores} onUpdateCustomer={onUpdateCustomer} onDeleteCustomer={onDeleteCustomer} />}

      {tab === "applications" && (
        <Panel title="Αιτήσεις καταστημάτων">
          {applications.length === 0 ? <InfoBox icon="📭" title="Δεν υπάρχουν αιτήσεις" /> : applications.map((app) => (
            <article key={app.id} className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100">
              <div className="flex flex-wrap justify-between gap-3">
                <div>
                  <p className="text-lg font-black">{app.storeName}</p>
                  <p className="text-sm font-bold text-slate-600">Ιδιοκτήτης: {app.ownerName} · {app.ownerPhone}</p>
                  <p className="text-sm font-bold text-slate-600">{app.storeAddress} · {app.storeArea}</p>
                  <p className="text-xs font-black text-emerald-700">Status: {app.status}</p>
                </div>
                <div className="flex gap-2">
                  <button onClick={() => onApproveApplication(app.id)} disabled={app.status !== "pending"} className="rounded-full bg-emerald-100 px-3 py-2 text-xs font-black text-emerald-800 disabled:opacity-40">Approve</button>
                  <button onClick={() => onRejectApplication(app.id)} disabled={app.status !== "pending"} className="rounded-full bg-rose-100 px-3 py-2 text-xs font-black text-rose-800 disabled:opacity-40">Reject</button>
                </div>
              </div>
            </article>
          ))}
        </Panel>
      )}

      {tab === "stores" && (
        <Panel title="Καταστήματα πλατφόρμας">
          {stores.map((store) => {
            const storeOrders = orders.filter((order) => order.storeId === store.id && order.status !== "cancelled");
            const revenue = storeOrders.reduce((sum, order) => sum + Number(order.totals?.subtotal || 0), 0);
            return (
              <article key={store.id} className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100">
                <div className="flex flex-wrap justify-between gap-3">
                  <div>
                    <div className="flex items-center gap-3">
                      <span className="grid h-12 w-12 overflow-hidden place-items-center rounded-2xl bg-white text-2xl ring-1 ring-slate-200">
                        <MediaBox src={store.profile.logo} fallback={store.profile.logoEmoji || "🏪"} />
                      </span>
                      <div>
                        <p className="text-lg font-black">{store.profile.name}</p>
                        <p className="text-sm font-bold text-slate-600">Owner: {store.owner.name} · {store.owner.phone}</p>
                      </div>
                    </div>
                    <p className="mt-2 text-xs font-black text-emerald-700">
                      {storeStatusLabel(store.status)} · {store.active !== false ? "Public" : "Hidden"} · Orders {storeOrders.length} · Revenue {formatEuro(revenue)} · Store bans {(store.customerBans || []).length}
                    </p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <button onClick={() => onUpdateStore(store.id, { status: "approved", active: true, bannedAt: "", banReason: "" })} className="rounded-full bg-emerald-100 px-3 py-2 text-xs font-black text-emerald-800">Approve</button>
                    <button onClick={() => onUpdateStore(store.id, { status: "suspended", active: false })} className="rounded-full bg-amber-100 px-3 py-2 text-xs font-black text-amber-800">Suspend</button>
                    <button onClick={() => onUpdateStore(store.id, { status: "banned", active: false, bannedAt: new Date().toISOString(), banReason: "Permanent Platform Admin ban" })} className="rounded-full bg-rose-100 px-3 py-2 text-xs font-black text-rose-800">Permanent ban</button>
                    <button onClick={() => onUpdateStore(store.id, { active: store.active === false })} className="rounded-full bg-white px-3 py-2 text-xs font-black text-slate-700 ring-1 ring-slate-200">{store.active === false ? "Show" : "Hide"}</button>
                    <button onClick={() => onDeleteStore(store.id)} className="rounded-full bg-red-600 px-3 py-2 text-xs font-black text-white">Delete store</button>
                  </div>
                </div>
              </article>
            );
          })}
        </Panel>
      )}

      {tab === "orders" && <OrdersList orders={orders} platform={platform} onStatus={onStatus} />}
      {tab === "drivers" && <PlatformDrivers drivers={drivers} orders={orders} withdrawals={withdrawals} platform={platform} onUpdateDriver={onUpdateDriver} onUpdateWithdrawal={onUpdateWithdrawal} />}

      {tab === "fees" && (
        <Panel title="Κεντρικά fees πλατφόρμας">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <Input label="Service fee" type="number" step="0.01" value={platform.serviceFee} onChange={(v) => setPlatform({ ...platform, serviceFee: Number(v) })} />
            <Input label="Delivery fee" type="number" step="0.01" value={platform.deliveryFee} onChange={(v) => setPlatform({ ...platform, deliveryFee: Number(v) })} />
            <Input label="Free delivery from" type="number" step="0.01" value={platform.freeDeliveryFrom} onChange={(v) => setPlatform({ ...platform, freeDeliveryFrom: Number(v) })} />
            <Input label="Minimum order" type="number" step="0.01" value={platform.minOrder} onChange={(v) => setPlatform({ ...platform, minOrder: Number(v) })} />
            <Input label="Driver %" type="number" value={platform.driverCommissionPercent} onChange={(v) => setPlatform({ ...platform, driverCommissionPercent: Number(v), driverPlatformFeePercent: Math.max(0, 100 - Number(v || 0)) })} />
            <Input label="Driver min withdraw" type="number" value={platform.driverMinWithdraw} onChange={(v) => setPlatform({ ...platform, driverMinWithdraw: Number(v) })} />
            <Toggle label="Driver rating reward" checked={platform.driverRewardEnabled !== false} onChange={(checked) => setPlatform({ ...platform, driverRewardEnabled: checked })} />
            <Input label="Min rating για bonus" type="number" step="0.1" value={platform.driverRewardMinRating} onChange={(v) => setPlatform({ ...platform, driverRewardMinRating: Number(v) })} />
            <Input label="Bonus ανά rated order" type="number" step="0.01" value={platform.driverRewardBonusPerOrder} onChange={(v) => setPlatform({ ...platform, driverRewardBonusPerOrder: Number(v) })} />
            <Toggle label="Loyalty ενεργό" checked={platform.loyaltyEnabled !== false} onChange={(checked) => setPlatform({ ...platform, loyaltyEnabled: checked })} />
            <Toggle label="Εξαργύρωση loyalty" checked={platform.loyaltyRedeemEnabled !== false} onChange={(checked) => setPlatform({ ...platform, loyaltyRedeemEnabled: checked })} />
            <Input label="Πόντοι που κερδίζει" type="number" value={platform.loyaltyEarnPoints} onChange={(v) => setPlatform({ ...platform, loyaltyEarnPoints: Number(v) })} />
            <Input label="Ανά πόσα €" type="number" step="0.01" value={platform.loyaltyEarnEuro} onChange={(v) => setPlatform({ ...platform, loyaltyEarnEuro: Number(v) })} />
            <Input label="Πόντοι εξαργύρωσης" type="number" value={platform.loyaltyRedeemPoints} onChange={(v) => setPlatform({ ...platform, loyaltyRedeemPoints: Number(v) })} />
            <Input label="Αξία έκπτωσης €" type="number" step="0.01" value={platform.loyaltyRedeemEuro} onChange={(v) => setPlatform({ ...platform, loyaltyRedeemEuro: Number(v) })} />
            <Input label="Ελάχιστοι πόντοι" type="number" value={platform.loyaltyMinRedeemPoints} onChange={(v) => setPlatform({ ...platform, loyaltyMinRedeemPoints: Number(v) })} />
            <Toggle label="Loyalty μόνο στα platform fees" checked={true} onChange={() => setPlatform({ ...platform, loyaltyApplyOnFees: true })} />
          </div>
          <div className="rounded-2xl bg-amber-50 p-4 text-sm font-bold leading-6 text-amber-900 ring-1 ring-amber-100">
            ⭐ Κανόνας loyalty: {loyaltyRuleText(platform)}. Η εξαργύρωση καλύπτει μόνο service/delivery fees της πλατφόρμας.
          </div>
        </Panel>
      )}

      {tab === "controls" && (
        <Panel title="Branding & βασικές πληροφορίες πλατφόρμας">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            <ImageUpload label="Platform logo" value={platform.brandLogo || ""} onChange={(brandLogo) => setPlatform({ ...platform, brandLogo })} fallback="🛵" />
            <Input label="Brand name" value={platform.brandName} onChange={(v) => setPlatform({ ...platform, brandName: v })} />
            <Input label="Υπότιτλος" value={platform.subtitle} onChange={(v) => setPlatform({ ...platform, subtitle: v })} />
            <Input label="Company name" value={platform.companyName} onChange={(v) => setPlatform({ ...platform, companyName: v })} />
            <Input label="Support email" value={platform.supportEmail} onChange={(v) => setPlatform({ ...platform, supportEmail: v })} />
            <Input label="Support phone" value={platform.supportPhone} onChange={(v) => setPlatform({ ...platform, supportPhone: v })} />
            <Input label="Legal address" value={platform.legalAddress} onChange={(v) => setPlatform({ ...platform, legalAddress: v })} />
            <Input label="Platform PIN" value={platform.platformPin} onChange={(v) => setPlatform({ ...platform, platformPin: v })} />
            <Toggle label="Delivery ενεργό" checked={platform.deliveryEnabled !== false} onChange={(checked) => setPlatform({ ...platform, deliveryEnabled: checked })} />
            <Toggle label="Live GPS tracking" checked={platform.liveDriverTrackingEnabled !== false} onChange={(checked) => setPlatform({ ...platform, liveDriverTrackingEnabled: checked })} />
            <Toggle label="Pickup ενεργό" checked={platform.pickupEnabled !== false} onChange={(checked) => setPlatform({ ...platform, pickupEnabled: checked })} />
            <Toggle label="Cash πληρωμές" checked={platform.payCashEnabled !== false} onChange={(checked) => setPlatform({ ...platform, payCashEnabled: checked })} />
            <Toggle label="Card στον διανομέα" checked={platform.payCardDeliveryEnabled !== false} onChange={(checked) => setPlatform({ ...platform, payCardDeliveryEnabled: checked })} />
          </div>
          <TextArea label="Hub announcement" value={platform.platformAnnouncement} onChange={(v) => setPlatform({ ...platform, platformAnnouncement: v })} />
        </Panel>
      )}

      {tab === "pages" && (
        <Panel title="Footer / Νομικές σελίδες">
          <TextArea label="Επικοινωνία" value={platform.contactText} onChange={(v) => setPlatform({ ...platform, contactText: v })} />
          <TextArea label="Όροι χρήσης" value={platform.termsText} onChange={(v) => setPlatform({ ...platform, termsText: v })} />
          <TextArea label="Πολιτική απορρήτου" value={platform.privacyText} onChange={(v) => setPlatform({ ...platform, privacyText: v })} />
          <TextArea label="Ακυρώσεις / Επιστροφές" value={platform.refundText} onChange={(v) => setPlatform({ ...platform, refundText: v })} />
          <TextArea label="Όροι καταστημάτων" value={platform.merchantTermsText} onChange={(v) => setPlatform({ ...platform, merchantTermsText: v })} />
          <TextArea label="Κανόνες διανομέων" value={platform.driverRulesText} onChange={(v) => setPlatform({ ...platform, driverRulesText: v })} />
          <TextArea label="Λειτουργία μετρητών" value={platform.cashHandlingText} onChange={(v) => setPlatform({ ...platform, cashHandlingText: v })} />
          <TextArea label="Ροή παραλαβής / παράδοσης" value={platform.deliveryFlowText} onChange={(v) => setPlatform({ ...platform, deliveryFlowText: v })} />
        </Panel>
      )}
    </div>
  );
}

function PlatformUsers({ users, orders, stores, onUpdateCustomer, onDeleteCustomer }) {
  return <Panel title="Χρήστες / πελάτες πλατφόρμας">{users.length === 0 ? <InfoBox icon="👤" title="Δεν υπάρχουν εγγεγραμμένοι χρήστες" /> : users.map((user) => { const userOrders = orders.filter((order) => order.userId === user.id || order.customer?.phone === user.phone); const spent = userOrders.filter((order) => order.status !== "cancelled").reduce((sum, order) => sum + Number(order.totals?.total || 0), 0); const usedStores = stores.filter((store) => userOrders.some((order) => order.storeId === store.id)); const storeBans = stores.filter((store) => (store.customerBans || []).some((ban) => (ban.userId && ban.userId === user.id) || (ban.phone && ban.phone === user.phone))); return <article key={user.id} className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100"><div className="flex flex-wrap items-start justify-between gap-3"><div><p className="text-lg font-black">{user.name || "Πελάτης"}</p><p className="text-sm font-bold text-slate-600">{user.phone} · {user.email || "χωρίς email"}</p><p className="text-xs font-black text-emerald-700">{userStatusLabel(user.status)} · Orders {userOrders.length} · Spend {formatEuro(spent)} · Loyalty {user.loyaltyPoints || 0}</p><p className="text-xs font-bold text-slate-500">Stores: {usedStores.map((store) => store.profile.name).join(", ") || "-"} · Store bans: {storeBans.map((store) => store.profile.name).join(", ") || "-"}</p>{user.banReason && <p className="mt-1 text-xs font-black text-rose-700">Reason: {user.banReason}</p>}</div><div className="flex flex-wrap gap-2"><button onClick={() => onUpdateCustomer(user.id, { loyaltyPoints: Number(user.loyaltyPoints || 0) + 100 })} className="rounded-full bg-amber-100 px-3 py-2 text-xs font-black text-amber-800">+100 pts</button><button onClick={() => onUpdateCustomer(user.id, { loyaltyPoints: Math.max(0, Number(user.loyaltyPoints || 0) - 100) })} className="rounded-full bg-white px-3 py-2 text-xs font-black text-slate-700 ring-1 ring-slate-200">-100 pts</button><button onClick={() => onUpdateCustomer(user.id, { status: "active", banReason: "", bannedAt: "" })} className="rounded-full bg-emerald-100 px-3 py-2 text-xs font-black text-emerald-800">Unban</button><button onClick={() => onUpdateCustomer(user.id, { status: "suspended", banReason: "Προσωρινή αναστολή από Platform Admin" })} className="rounded-full bg-amber-100 px-3 py-2 text-xs font-black text-amber-800">Suspend</button><button onClick={() => onUpdateCustomer(user.id, { status: "banned", banReason: "Μόνιμος αποκλεισμός από Platform Admin" })} className="rounded-full bg-rose-100 px-3 py-2 text-xs font-black text-rose-800">Permanent ban</button><button onClick={() => onDeleteCustomer(user.id)} className="rounded-full bg-red-600 px-3 py-2 text-xs font-black text-white">Delete user</button></div></div></article>; })}</Panel>;
}

function OrdersList({ orders, platform, onStatus, storeView = false }) {
  return <Panel title={storeView ? "Παραγγελίες καταστήματος" : "Όλες οι παραγγελίες"}>{orders.length === 0 ? <InfoBox icon="📭" title="Δεν υπάρχουν παραγγελίες" /> : orders.map((order) => <article key={order.id} className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100"><div className="flex flex-wrap justify-between gap-3"><div><p className="text-lg font-black">#{order.id}</p><p className="flex items-center gap-2 text-sm font-black text-emerald-700"><span className="grid h-7 w-7 overflow-hidden place-items-center rounded-lg bg-white"><MediaBox src={order.storeSnapshot.logo} fallback={order.storeSnapshot.logoEmoji || "🏪"} className="text-sm" /></span>{order.storeSnapshot.name}</p><p className="text-sm font-bold text-slate-600">{order.customer.name} · {order.customer.phone}</p><p className="text-sm font-bold text-slate-600">{serviceLabel(order.deliveryType)} · {paymentLabel(order.paymentMethod)} · {statusLabels[order.status]}</p>{order.driverSnapshot && <p className="text-xs font-black text-amber-700">🛵 {order.driverSnapshot.name} · {order.driverSnapshot.phone}</p>}{(order.driverLastLocation || order.deliveryAssignment?.lastLocation) && <DriverLiveMap location={order.driverLastLocation || order.deliveryAssignment?.lastLocation} title="Live GPS διανομέα" compact />}</div><div className="rounded-2xl bg-white px-4 py-3 text-right ring-1 ring-slate-100"><p className="text-xs font-black text-slate-500">Total</p><p className="text-xl font-black">{formatEuro(order.totals.total)}</p>{!storeView && <p className="text-xs font-bold text-slate-500">Platform net {formatEuro(platformNetForOrder(order, platform))}</p>}{loyaltyDiscountForOrder(order) > 0 && <p className="text-xs font-bold text-amber-700">Loyalty fees discount -{formatEuro(loyaltyDiscountForOrder(order))}</p>}</div></div><div className="mt-3 grid gap-2">{order.items.map((item) => <div key={item.key} className="rounded-2xl bg-white p-3 text-sm ring-1 ring-slate-100"><p className="flex items-center gap-2 font-black"><span className="grid h-8 w-8 overflow-hidden place-items-center rounded-lg bg-slate-50 text-base"><MediaBox src={item.image} fallback={item.emoji || "🍽️"} className="text-base" /></span>{item.qty}x {item.title}</p><p className="text-slate-500">{item.optionText}</p>{item.bonusQty > 0 && <p className="text-xs font-black text-emerald-700">🎁 +{item.bonusQty} δώρο</p>}{item.offerType === "bundle" && item.bundleLabel && <p className="text-xs font-black text-amber-700">🤝 {item.bundleLabel}</p>}{item.productNote && <p className="mt-1 text-xs font-black text-amber-700">Σχόλιο: {item.productNote}</p>}</div>)}</div><div className="mt-4 flex flex-wrap gap-2">{Object.entries(statusLabels).map(([key, label]) => <button key={key} onClick={() => onStatus(order.id, key)} className={`rounded-full px-3 py-2 text-xs font-black ${order.status === key ? "bg-slate-950 text-white" : "bg-white text-slate-700 ring-1 ring-slate-200"}`}>{label}</button>)}</div></article>)}</Panel>;
}

function PlatformDrivers({ drivers, orders, withdrawals, platform, onUpdateDriver, onUpdateWithdrawal }) {
  return <Panel title="Κεντρική διαχείριση διανομέων">{drivers.length === 0 ? <InfoBox icon="🛵" title="Δεν υπάρχουν διανομείς" /> : drivers.map((driver) => { const wallet = driverWalletStats(driver.id, orders, withdrawals, platform); return <article key={driver.id} className="rounded-[1.25rem] bg-slate-50 p-4 ring-1 ring-slate-100"><div className="flex flex-wrap justify-between gap-3"><div><p className="text-lg font-black">{driver.name}</p><p className="text-sm font-bold text-slate-600">{driver.phone} · {vehicleLabel(driver.vehicleType)} · {driver.vehiclePlate}</p><p className="text-xs font-black text-emerald-700">{driverStatusLabel(driver.status)} · {driver.online ? "Online" : "Offline"}</p><p className="text-xs font-black text-amber-700">Wallet {formatEuro(wallet.available)} · earned {formatEuro(wallet.earned)} · pending {formatEuro(wallet.pending)}</p>{driver.lastLocation && <p className="text-xs font-black text-blue-700">📍 GPS {locationAgeText(driver.lastLocation)} · {driver.lastLocation.lat}, {driver.lastLocation.lng}</p>}</div><div className="flex flex-wrap gap-2"><button onClick={() => onUpdateDriver(driver.id, { status: "approved" })} className="rounded-full bg-emerald-100 px-3 py-2 text-xs font-black text-emerald-800">Approve</button><button onClick={() => onUpdateDriver(driver.id, { status: "suspended", online: false })} className="rounded-full bg-rose-100 px-3 py-2 text-xs font-black text-rose-800">Suspend</button><button onClick={() => onUpdateDriver(driver.id, { online: !driver.online })} disabled={driver.status !== "approved"} className="rounded-full bg-white px-3 py-2 text-xs font-black text-slate-700 ring-1 ring-slate-200 disabled:opacity-40">{driver.online ? "Offline" : "Online"}</button></div></div></article>; })}<div className="mt-5"><h4 className="text-lg font-black">Withdraw requests</h4><div className="mt-3 grid gap-3">{withdrawals.length === 0 ? <p className="text-sm font-bold text-slate-500">Δεν υπάρχουν requests.</p> : withdrawals.map((request) => <article key={request.id} className="rounded-[1.25rem] bg-white p-4 ring-1 ring-slate-200"><div className="flex flex-wrap justify-between gap-3"><div><p className="font-black">{request.driverName} · {request.driverPhone}</p><p className="text-sm font-bold text-slate-600">IBAN: {request.iban || "-"} · {request.status}</p></div><p className="text-xl font-black">{formatEuro(request.amount)}</p></div><div className="mt-3 flex gap-2"><button onClick={() => onUpdateWithdrawal(request.id, "approved")} className="rounded-full bg-emerald-100 px-3 py-2 text-xs font-black text-emerald-800">Mark paid</button><button onClick={() => onUpdateWithdrawal(request.id, "pending")} className="rounded-full bg-amber-100 px-3 py-2 text-xs font-black text-amber-800">Pending</button><button onClick={() => onUpdateWithdrawal(request.id, "rejected")} className="rounded-full bg-rose-100 px-3 py-2 text-xs font-black text-rose-800">Reject</button></div></article>)}</div></div></Panel>;
}

function ProductEditor({ draft, setDraft, categories, products = [], editingId, onSubmit, onCancel }) {
  return <form onSubmit={onSubmit} className="rounded-[1.5rem] bg-slate-50 p-4 ring-1 ring-slate-200"><div className="flex items-center justify-between gap-3"><div><h3 className="text-xl font-black">{editingId ? "Επεξεργασία προϊόντος" : "Νέο προϊόν"}</h3><p className="mt-1 text-sm font-semibold text-slate-500">Ο Merchant ελέγχει προϊόντα, κατηγορίες, τιμές, 1+1 και συνδυαστικές προσφορές.</p></div>{editingId && <button type="button" onClick={onCancel} className="rounded-xl bg-white px-3 py-2 text-xs font-black ring-1 ring-slate-200">Νέο</button>}</div><div className="mt-5 grid gap-4 sm:grid-cols-2"><Input label="Όνομα προϊόντος" value={draft.title} onChange={(v) => setDraft({ ...draft, title: v })} required /><ImageUpload label="Φωτογραφία προϊόντος" value={draft.image || ""} onChange={(image) => setDraft({ ...draft, image })} fallback={draft.emoji || "🍽️"} /><Input label="Fallback emoji" value={draft.emoji} onChange={(v) => setDraft({ ...draft, emoji: v })} /><label className="block"><span className="mb-2 block text-sm font-black text-slate-700">Κατηγορία</span><select value={draft.category} onChange={(e) => setDraft({ ...draft, category: e.target.value })} className="h-14 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm font-semibold">{categories.map((category) => <option key={category} value={category}>{category}</option>)}</select></label><Input label="Νέα κατηγορία" value={draft.category} onChange={(v) => setDraft({ ...draft, category: v })} /><Input label="Τιμή" type="number" step="0.01" value={draft.price} onChange={(v) => setDraft({ ...draft, price: v })} required /><Input label="Παλιά τιμή" type="number" step="0.01" value={draft.oldPrice} onChange={(v) => setDraft({ ...draft, oldPrice: v })} /><Input label="Badge" value={draft.badge} onChange={(v) => setDraft({ ...draft, badge: v })} /><Input label="Χρόνος" value={draft.time} onChange={(v) => setDraft({ ...draft, time: v })} /></div><div className="mt-4 grid gap-4 sm:grid-cols-3"><label className="block"><span className="mb-2 block text-sm font-black text-slate-700">Τύπος προσφοράς</span><select value={draft.offerType || "standard"} onChange={(e) => setDraft({ ...draft, offerType: e.target.value, promo: e.target.value !== "standard" || draft.promo })} className="h-14 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm font-semibold"><option value="standard">Κανονικό προϊόν</option><option value="bogo">1+1 δώρο</option><option value="bundle">Συνδυαστική προσφορά</option></select></label><label className="block"><span className="mb-2 block text-sm font-black text-slate-700">Συνδυαστικό προϊόν</span><select value={draft.bundleProductId || ""} onChange={(e) => setDraft({ ...draft, bundleProductId: e.target.value })} disabled={(draft.offerType || "standard") !== "bundle"} className="h-14 w-full rounded-2xl border border-slate-200 bg-white px-4 text-sm font-semibold disabled:bg-slate-100"><option value="">Επιλογή προϊόντος</option>{products.filter((product) => product.id !== editingId).map((product) => <option key={product.id} value={product.id}>{product.title}</option>)}</select></label><Input label="Κείμενο combo" value={draft.bundleLabel || ""} onChange={(v) => setDraft({ ...draft, bundleLabel: v })} placeholder="π.χ. Με φυσικό χυμό δώρο" /></div><TextArea label="Περιγραφή" value={draft.description} onChange={(v) => setDraft({ ...draft, description: v })} /><div className="grid gap-4 sm:grid-cols-3"><Input label="Γλυκύτητα" value={draft.options.sweetness} onChange={(v) => setDraft({ ...draft, options: { ...draft.options, sweetness: v } })} /><Input label="Επιλογές" value={draft.options.milk} onChange={(v) => setDraft({ ...draft, options: { ...draft.options, milk: v } })} /><Input label="Extras" value={draft.options.extras} onChange={(v) => setDraft({ ...draft, options: { ...draft.options, extras: v } })} /></div><div className="mt-4 grid gap-3 sm:grid-cols-2"><Toggle label="Ενεργό" checked={draft.active !== false} onChange={(checked) => setDraft({ ...draft, active: checked })} /><Toggle label="Προσφορά" checked={Boolean(draft.promo || draft.offerType === "bogo" || draft.offerType === "bundle")} onChange={(checked) => setDraft({ ...draft, promo: checked })} /></div><button className="mt-5 w-full rounded-2xl bg-slate-950 py-4 font-black text-white">{editingId ? "Αποθήκευση" : "Προσθήκη"}</button></form>;
}

function ProductsList({ products, onEdit, onUpdate, onDelete }) {
  return <div className="rounded-[1.5rem] bg-white p-4 ring-1 ring-slate-200"><h3 className="text-xl font-black">Προϊόντα καταστήματος</h3><div className="mt-4 space-y-3">{products.map((product) => <article key={product.id} className="rounded-2xl bg-slate-50 p-3 ring-1 ring-slate-100"><div className="flex flex-wrap items-center justify-between gap-3"><div className="flex items-center gap-3"><span className="grid h-12 w-12 overflow-hidden place-items-center rounded-2xl bg-white text-2xl"><MediaBox src={product.image} fallback={product.emoji || "🍽️"} /></span><div><p className="font-black">{product.title}</p><p className="text-xs font-bold text-slate-500">{product.category} · {formatEuro(product.price)}{product.offerType === "bogo" ? " · 1+1 δώρο" : product.offerType === "bundle" ? ` · ${offerLabel(product, products)}` : ""}</p></div></div><div className="flex gap-2"><button onClick={() => onUpdate(product.id, { active: !(product.active !== false) })} className={`rounded-full px-3 py-2 text-xs font-black ${product.active !== false ? "bg-emerald-100 text-emerald-800" : "bg-slate-200 text-slate-600"}`}>{product.active !== false ? "Active" : "Hidden"}</button><button onClick={() => onEdit(product)} className="rounded-full bg-white px-3 py-2 text-xs font-black ring-1 ring-slate-200">Edit</button><button onClick={() => onDelete(product.id)} className="rounded-full bg-rose-50 px-3 py-2 text-xs font-black text-rose-700">Delete</button></div></div></article>)}</div></div>;
}

function OrderTracking({ order }) {
  const currentIndex = Math.max(0, statusSteps.findIndex((step) => step.key === order.status));
  return <div className="p-6 sm:p-8"><div className="text-center"><div className="mx-auto grid h-20 w-20 place-items-center rounded-full bg-emerald-100 text-4xl">✅</div><h2 className="mt-5 text-3xl font-black">Παραγγελία #{order.id}</h2><p className="mt-2 flex items-center justify-center gap-2 text-slate-600"><span className="grid h-7 w-7 overflow-hidden place-items-center rounded-lg bg-slate-50"><MediaBox src={order.storeSnapshot.logo} fallback={order.storeSnapshot.logoEmoji || "🏪"} className="text-sm" /></span>{order.storeSnapshot.name} · {statusLabels[order.status]}</p>{order.driverSnapshot && (
          <>
            <p className="mt-3 rounded-2xl bg-amber-50 p-3 text-sm font-black text-amber-800 ring-1 ring-amber-100">🛵 {order.driverSnapshot.name} · {order.driverSnapshot.phone} · {vehicleLabel(order.driverSnapshot.vehicleType)}</p>
            <DriverLiveMap location={order.driverLastLocation || order.deliveryAssignment?.lastLocation || order.driverSnapshot?.lastLocation} title="Live θέση διανομέα" compact />
          </>
        )}</div><div className="mt-7 grid gap-4 sm:grid-cols-7">{statusSteps.map((step, index) => <div key={step.key} className="rounded-2xl bg-slate-50 p-4 text-center ring-1 ring-slate-200"><div className={`mx-auto grid h-10 w-10 place-items-center rounded-full ${index <= currentIndex ? "bg-emerald-100 text-emerald-700" : "bg-slate-100 text-slate-400"}`}>{step.icon}</div><p className="mt-3 font-black">{step.label}</p><p className="mt-1 text-xs font-semibold text-slate-500">{step.text}</p></div>)}</div><Panel title="Στοιχεία παραγγελίας"><InfoLine label="Πελάτης" value={`${order.customer.name} · ${order.customer.phone}`} /><InfoLine label="Κατάστημα" value={`${order.storeSnapshot.name} · ${order.storeSnapshot.phone}`} /><InfoLine label="Διεύθυνση" value={order.deliveryType === "pickup" ? order.storeSnapshot.address : `${order.customer.address} ${order.customer.floor}`} /><InfoLine label="Σύνολο" value={formatEuro(order.totals.total)} />{(order.driverLastLocation || order.deliveryAssignment?.lastLocation) && <InfoLine label="GPS διανομέα" value={locationAgeText(order.driverLastLocation || order.deliveryAssignment?.lastLocation)} />}{order.items.map((item) => <InfoLine key={item.key} label={`${item.qty}x ${item.title}`} value={formatEuro(item.lineTotal)} />)}</Panel></div>;
}

function DriverLiveMap({ location, title = "Live GPS", compact = false }) {
  const loc = normalizeLocation(location);
  if (!loc) return <div className={`rounded-2xl bg-slate-50 p-3 text-sm font-bold text-slate-500 ring-1 ring-slate-200 ${compact ? "mt-2" : ""}`}>📍 {title}: Δεν υπάρχει ακόμα ζωντανή θέση.</div>;
  return <div className={`overflow-hidden rounded-2xl bg-white ring-1 ring-blue-100 ${compact ? "mt-2" : ""}`}><div className="flex flex-wrap items-center justify-between gap-2 bg-blue-50 px-4 py-3"><div><p className="text-sm font-black text-blue-950">📍 {title}</p><p className="text-xs font-bold text-blue-800">{loc.lat}, {loc.lng} · ακρίβεια {loc.accuracy ? `${loc.accuracy}m` : "-"} · {locationAgeText(loc)}</p></div><a href={mapsUrl(loc)} target="_blank" rel="noreferrer" className="rounded-full bg-blue-600 px-3 py-2 text-xs font-black text-white">Άνοιγμα χάρτη</a></div><div className={`${compact ? "h-24" : "h-40"} relative bg-[radial-gradient(circle_at_center,_#dbeafe_0,_#eff6ff_36%,_#f8fafc_70%)]`}><div className="absolute inset-0 opacity-60" style={{ backgroundImage: "linear-gradient(to right, rgba(15,23,42,.08) 1px, transparent 1px), linear-gradient(to bottom, rgba(15,23,42,.08) 1px, transparent 1px)", backgroundSize: "28px 28px" }} /><div className="absolute left-1/2 top-1/2 grid h-12 w-12 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-blue-600 text-xl text-white shadow-2xl ring-8 ring-blue-200">🛵</div><div className="absolute bottom-3 left-3 rounded-full bg-white/90 px-3 py-1 text-xs font-black text-slate-700 ring-1 ring-slate-200">Live browser GPS</div></div></div>;
}

function ChoiceGroup({ title, options, value, onChange }) {
  return <div><p className="mb-2 text-sm font-black text-slate-800">{title}</p><div className="grid gap-2">{options.map((option) => <button type="button" key={option} onClick={() => onChange(option)} className={`flex w-full items-center justify-between rounded-2xl border p-4 text-left text-sm font-bold transition ${value === option ? "border-emerald-500 bg-emerald-50 text-emerald-800" : "border-slate-200 bg-white text-slate-700 hover:bg-slate-50"}`}><span>{option === "delivery" ? "Delivery στην πόρτα" : option === "pickup" ? "Παραλαβή από κατάστημα" : option === "cash" ? "Μετρητά" : option === "card_on_delivery" ? "Κάρτα στον διανομέα" : option === "store_card" ? "Κάρτα στο κατάστημα" : option}</span><span>{value === option ? "✅" : ""}</span></button>)}</div></div>;
}

function MultiChoiceGroup({ title, options, value, onChange }) {
  function toggle(option) { onChange(value.includes(option) ? value.filter((item) => item !== option) : [...value, option]); }
  return <div><p className="mb-2 text-sm font-black text-slate-800">{title}</p><div className="grid gap-2">{options.map((option) => <button type="button" key={option} onClick={() => toggle(option)} className={`flex w-full items-center justify-between rounded-2xl border p-4 text-left text-sm font-bold ${value.includes(option) ? "border-emerald-500 bg-emerald-50 text-emerald-800" : "border-slate-200 bg-white text-slate-700"}`}><span>{option}</span><span>{value.includes(option) ? "✅" : ""}</span></button>)}</div></div>;
}

function Input({ label, icon, value, onChange, required, placeholder, type = "text", step }) {
  return <label className="block"><span className="mb-2 block text-sm font-black text-slate-700">{label}</span><div className="relative">{icon && <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">{icon}</span>}<input type={type} value={value ?? ""} onChange={(e) => onChange(e.target.value)} required={required} placeholder={placeholder || ""} step={step} className={`h-14 w-full rounded-2xl border border-slate-200 bg-white ${icon ? "pl-12" : "pl-4"} pr-4 text-sm font-semibold outline-none transition focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100`} /></div></label>;
}

function TextArea({ label, value, onChange, placeholder }) {
  return <label className="block"><span className="mb-2 block text-sm font-black text-slate-700">{label}</span><textarea value={value ?? ""} onChange={(e) => onChange(e.target.value)} placeholder={placeholder || ""} className="min-h-28 w-full rounded-2xl border border-slate-200 bg-white p-4 text-sm font-semibold outline-none transition focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100" /></label>;
}

function Toggle({ label, checked, onChange }) {
  return <button type="button" onClick={() => onChange(!checked)} className={`flex items-center justify-between rounded-2xl p-4 text-sm font-black ring-1 ${checked ? "bg-emerald-50 text-emerald-800 ring-emerald-100" : "bg-slate-100 text-slate-600 ring-slate-200"}`}><span>{label}</span><span>{checked ? "✅" : "⚪"}</span></button>;
}

function Line({ label, value }) {
  return <div className="flex items-center justify-between"><span>{label}</span><span className="text-slate-900">{value}</span></div>;
}

function Panel({ title, children }) {
  return <div className="mt-5 rounded-[1.5rem] bg-white p-5 ring-1 ring-slate-200"><h3 className="text-xl font-black">{title}</h3><div className="mt-4 grid gap-3">{children}</div></div>;
}

function InfoBox({ icon, title, text, tone = "slate" }) {
  const cls = tone === "amber" ? "bg-amber-50 text-amber-950 ring-amber-100" : "bg-white text-slate-950 ring-slate-200";
  return <div className={`mt-5 rounded-[1.5rem] p-6 text-center ring-1 ${cls}`}><div className="text-5xl">{icon}</div><h3 className="mt-4 text-xl font-black">{title}</h3>{text && <p className="mx-auto mt-2 max-w-2xl text-sm font-bold leading-6 opacity-80">{text}</p>}</div>;
}

function EmptyState({ icon, title }) {
  return <div className="col-span-full rounded-[1.5rem] bg-white p-8 text-center ring-1 ring-slate-200"><div className="text-5xl">{icon}</div><p className="mt-4 font-black">{title}</p></div>;
}

function Stat({ label, value, icon }) {
  return <div className="rounded-[1.35rem] bg-slate-50 p-4 ring-1 ring-slate-200"><div className="text-2xl">{icon}</div><p className="mt-3 text-2xl font-black">{value}</p><p className="text-sm font-bold text-slate-500">{label}</p></div>;
}

function MiniMetric({ label, value, dark }) {
  return <div className={`rounded-2xl p-3 ring-1 ${dark ? "bg-white/10 ring-white/15" : "bg-slate-50 ring-slate-100"}`}><p className="text-sm font-black">{value}</p><p className={`text-xs font-bold ${dark ? "text-slate-300" : "text-slate-500"}`}>{label}</p></div>;
}

function InfoPill({ icon, label, value }) {
  return <div className="rounded-2xl bg-white/10 p-3 ring-1 ring-white/15 backdrop-blur"><div className="mb-2 text-xl">{icon}</div><p className="text-lg font-black">{label}</p><p className="text-xs font-bold text-slate-300">{value}</p></div>;
}

function InfoLine({ label, value }) {
  return <div className="flex items-start justify-between gap-4 rounded-2xl bg-slate-50 p-3 text-sm ring-1 ring-slate-100"><span className="font-black text-slate-500">{label}</span><span className="max-w-[65%] text-right font-bold text-slate-950">{value}</span></div>;
}

function DashboardCard({ icon, label, value, hint, dark = false }) {
  return <div className={`${dark ? "bg-white/10 text-white ring-white/15" : "bg-white text-slate-950 ring-slate-200"} rounded-[1.25rem] p-4 ring-1`}><div className="text-2xl">{icon}</div><p className="mt-3 text-2xl font-black">{value}</p><p className={`text-sm font-black ${dark ? "text-slate-200" : "text-slate-500"}`}>{label}</p>{hint && <p className="mt-1 text-xs font-bold text-slate-400">{hint}</p>}</div>;
}

function BrandLogo({ src, fallback = "🛵", size = "normal" }) {
  const cls = size === "hero" ? "h-32 w-full object-contain drop-shadow-xl sm:h-36" : "h-full w-full object-contain drop-shadow-md";
  return src ? <img src={src} alt="Road Runner Company logo" className={cls} /> : <span className={size === "hero" ? "text-8xl" : "text-5xl"}>{fallback}</span>;
}

function SiteFooter({ platform, onPage }) {
  const links = [["contact", "Επικοινωνία"], ["terms", "Όροι χρήσης"], ["privacy", "Πολιτική απορρήτου"], ["refunds", "Ακυρώσεις / Επιστροφές"], ["merchant", "Όροι καταστημάτων"], ["drivers", "Κανόνες διανομέων"]];
  return <footer className="border-t border-slate-200 bg-white px-4 py-8 pb-28 lg:pb-8"><div className="mx-auto grid max-w-7xl gap-6 md:grid-cols-[1fr_auto]"><div className="flex items-start gap-3"><span className="grid h-20 w-24 place-items-center"><BrandLogo src={platform.brandLogo} fallback="🛵" /></span><div><p className="text-lg font-black">{platform.brandName}</p><p className="mt-1 text-sm font-bold text-slate-500">{platform.companyName} · {platform.legalAddress}</p><p className="mt-1 text-sm font-bold text-slate-500">{platform.supportEmail} · {platform.supportPhone}</p></div></div><div className="flex flex-wrap gap-2">{links.map(([key, label]) => <button key={key} onClick={() => onPage(key)} className="rounded-full bg-slate-100 px-4 py-2 text-sm font-black text-slate-700 hover:bg-slate-200">{label}</button>)}</div></div></footer>;
}

function StaticPage({ page, platform }) {
  const content = {
    contact: { title: "Επικοινωνία", text: platform.contactText },
    terms: { title: "Όροι χρήσης", text: platform.termsText },
    privacy: { title: "Πολιτική απορρήτου", text: platform.privacyText },
    refunds: { title: "Ακυρώσεις / Επιστροφές", text: platform.refundText },
    merchant: { title: "Όροι καταστημάτων", text: platform.merchantTermsText },
    drivers: { title: "Κανόνες διανομέων", text: `${platform.driverRulesText}

${platform.cashHandlingText}

${platform.deliveryFlowText}` },
  }[page] || { title: "Πληροφορίες", text: "" };
  return <div className="p-6 sm:p-8"><div className="flex items-center gap-3"><span className="grid h-20 w-24 place-items-center"><BrandLogo src={platform.brandLogo} fallback="🛵" /></span><div><p className="text-sm font-black uppercase tracking-widest text-emerald-600">{platform.companyName}</p><h2 className="text-3xl font-black">{content.title}</h2></div></div><div className="mt-6 rounded-[1.5rem] bg-slate-50 p-5 text-sm font-bold leading-7 text-slate-700 ring-1 ring-slate-200 whitespace-pre-line">{content.text}</div><Panel title="Στοιχεία πλατφόρμας"><InfoLine label="Brand" value={platform.brandName} /><InfoLine label="Email" value={platform.supportEmail} /><InfoLine label="Τηλέφωνο" value={platform.supportPhone} /><InfoLine label="Έδρα" value={platform.legalAddress} /></Panel></div>;
}

function LanguageToggle({ lang, setLang }) {
  return <div className="flex rounded-full bg-slate-100 p-1 ring-1 ring-slate-200"><button onClick={() => setLang("el")} className={`rounded-full px-3 py-1.5 text-xs font-black ${lang === "el" ? "bg-slate-950 text-white" : "text-slate-600"}`}>EL</button><button onClick={() => setLang("en")} className={`rounded-full px-3 py-1.5 text-xs font-black ${lang === "en" ? "bg-slate-950 text-white" : "text-slate-600"}`}>EN</button></div>;
}

function AccessMenu({ open, setOpen, currentUser, lang = "el", onCustomer, onMerchant, onMerchantApply, onDriver, onPlatform }) {
  const mainLabel = currentUser ? `👤 ${currentUser.name}` : `👤 ${t(lang, "login")}`;
  return <div className="relative"><button onClick={() => setOpen(!open)} className="flex items-center gap-2 rounded-full bg-emerald-500 px-4 py-2.5 text-sm font-black text-white shadow-sm hover:bg-emerald-600"><span className="max-w-[130px] truncate">{mainLabel}</span><span>⌄</span></button>{open && <div className="absolute right-0 top-12 z-50 w-72 overflow-hidden rounded-[1.25rem] bg-white p-2 text-left shadow-2xl ring-1 ring-slate-200"><button onClick={onCustomer} className="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-sm font-black text-slate-800 hover:bg-emerald-50"><span>👤</span><span>{currentUser ? tx("Προφίλ πελάτη", lang) : tx("Είσοδος πελάτη", lang)}</span></button><button onClick={onMerchantApply} className="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-sm font-black text-slate-800 hover:bg-emerald-50"><span>🏪</span><span>{tx("Αίτηση συνεργασίας καταστήματος", lang)}</span></button><button onClick={onMerchant} className="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-sm font-black text-slate-800 hover:bg-slate-50"><span>🧾</span><span>Merchant portal</span></button><button onClick={onDriver} className="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-sm font-black text-slate-800 hover:bg-amber-50"><span>🛵</span><span>Driver portal</span></button><div className="my-2 border-t border-slate-100" /><button onClick={onPlatform} className="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left text-xs font-black text-slate-500 hover:bg-slate-50"><span>🔐</span><span>{tx("Διαχείριση πλατφόρμας", lang)}</span></button></div>}</div>;
}

function MobileBar({ total, items, onCart, onMenu, onAuth, onAccount, currentUser, lang = "el" }) {
  return <div className="fixed inset-x-0 bottom-0 z-40 border-t border-slate-200 bg-white/95 p-3 backdrop-blur lg:hidden"><div className="mx-auto flex max-w-xl gap-2"><button onClick={currentUser ? onAccount : onAuth} className="rounded-2xl bg-emerald-50 px-4 py-3 text-xs font-black text-emerald-800 ring-1 ring-emerald-100">{currentUser ? "👤" : t(lang, "login")}</button><button onClick={onMenu} className="rounded-2xl bg-slate-100 px-4 py-3 text-xs font-black text-slate-700">Menu</button><button onClick={onCart} className="flex flex-1 items-center justify-between rounded-2xl bg-slate-950 px-4 py-3 text-sm font-black text-white"><span>🛒 ({items})</span><span>{formatEuro(total, lang)}</span></button></div></div>;
}

function Modal({ children, onClose, size = "normal" }) {
  return <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/60 p-2 backdrop-blur-sm sm:p-4" onClick={onClose}><div onClick={(e) => e.stopPropagation()} className={`relative max-h-[calc(100vh-1rem)] w-[calc(100vw-1rem)] max-w-full overflow-y-auto overscroll-contain rounded-[1.25rem] bg-white shadow-2xl sm:max-h-[calc(100vh-2rem)] sm:rounded-[2rem] ${size === "large" ? "sm:max-w-7xl" : "sm:max-w-lg"}`}><button onClick={onClose} className="absolute right-4 top-4 z-10 grid h-10 w-10 place-items-center rounded-full bg-white/90 text-slate-600 shadow-sm ring-1 ring-slate-200 hover:bg-slate-100">✕</button>{children}</div></div>;
}


ReactDOM.createRoot(document.getElementById("root")).render(<App />);
