// ═══════════════════════════════════════════════════════════════════════════
// SERENYS - MAISON DE BEAUTÉ
// Application de prise de rendez-vous par praticienne
// ═══════════════════════════════════════════════════════════════════════════

const { useState, useEffect, useCallback } = React;

// ──────────────────────────────────────────────────────────────────────────
// CONFIGURATION API
// ──────────────────────────────────────────────────────────────────────────
const API_CONFIG = {
    mailsApiUrl: 'https://api.mails.swissapp.net/send',
    apiKey: 'ak-aa773140-a328-4a40-82ad-0160281363c9',
    fromEmail: 'noreply@serenys.ch',
    fromName: 'Serenys - Maison de Beauté',
    toEmail: 'info@serenys.ch'
};

// ──────────────────────────────────────────────────────────────────────────
// DONNÉES - Catalogue des praticiennes (chargé depuis JSON)
// ──────────────────────────────────────────────────────────────────────────
const CATALOGUE = {
  "praticiennes": [
    {
      "id": "didier",
      "name": "Didier",
      "subtitle": "Coiffure",
      "description": "Coiffure homme et femme",
      "avatar": "✂️",
      "color": "#5D7B93",
      "categories": [
        {
          "id": "coiffure",
          "name": "Coiffure",
          "services": [
            { "id": "coupe-femme", "name": "Coupe femme", "duration": 45, "price": 0, "options": [] },
            { "id": "coupe-homme", "name": "Coupe homme", "duration": 30, "price": 0, "options": [] }
          ]
        }
      ]
    },
    {
      "id": "aresky",
      "name": "Aresky",
      "subtitle": "Beauté des Mains & Pieds",
      "description": "Manucure, pédicure et soins",
      "avatar": "💅",
      "color": "#E8A5B3",
      "categories": [
        {
          "id": "beaute-mains",
          "name": "Beauté des Mains",
          "services": [
            { "id": "manucure-simple", "name": "Manucure simple", "duration": 30, "price": 35, "options": [] },
            { "id": "manucure-semi", "name": "Manucure semi-permanent", "duration": 45, "price": 55, "options": [{ "id": "couleur", "name": "Couleur", "price": 0 }, { "id": "french", "name": "French", "price": 10 }] },
            { "id": "pose-gel", "name": "Pose gel", "duration": 60, "price": 75, "options": [{ "id": "couleur", "name": "Couleur", "price": 0 }, { "id": "french", "name": "French", "price": 10 }] },
            { "id": "remplissage-gel", "name": "Remplissage gel", "duration": 45, "price": 60, "options": [{ "id": "couleur", "name": "Couleur", "price": 0 }, { "id": "french", "name": "French", "price": 10 }] },
            { "id": "capsules-americaines", "name": "Capsules américaines", "duration": 90, "price": 95, "options": [] },
            { "id": "depose-mains", "name": "Dépose", "duration": 20, "price": 15, "options": [] },
            { "id": "reparation-ongle", "name": "Réparation ongle", "duration": 15, "price": 10, "options": [] }
          ]
        },
        {
          "id": "beaute-pieds",
          "name": "Beauté des Pieds",
          "services": [
            { "id": "pedicure-simple", "name": "Pédicure simple (sans vernis)", "duration": 45, "price": 45, "options": [] },
            { "id": "pedicure-vernis", "name": "Pédicure avec vernis", "duration": 60, "price": 55, "options": [{ "id": "couleur", "name": "Couleur", "price": 0 }, { "id": "french", "name": "French", "price": 10 }] },
            { "id": "pedicure-semi", "name": "Pédicure semi-permanent", "duration": 75, "price": 70, "options": [{ "id": "couleur", "name": "Couleur", "price": 0 }, { "id": "french", "name": "French", "price": 10 }] },
            { "id": "depose-pieds", "name": "Dépose", "duration": 20, "price": 15, "options": [] }
          ]
        },
        {
          "id": "duo-mains-pieds",
          "name": "Duo Mains & Pieds",
          "services": [
            { "id": "duo-simple", "name": "Mani + Pédi vernis simple", "duration": 75, "price": 75, "options": [] },
            { "id": "duo-semi", "name": "Mani + Pédi semi-permanent", "duration": 105, "price": 110, "options": [] },
            { "id": "duo-depose", "name": "Mani + Pédi avec dépose", "duration": 120, "price": 130, "options": [] }
          ]
        }
      ]
    },
    {
      "id": "virginie",
      "name": "Virginie",
      "subtitle": "Épilation",
      "description": "Épilation orientale et traditionnelle",
      "avatar": "✨",
      "color": "#D4A574",
      "categories": [
        {
          "id": "epil-orientale",
          "name": "Épilation Orientale",
          "services": [
            { "id": "orientale-visage", "name": "Visage complet", "duration": 30, "price": 35, "options": [] },
            { "id": "orientale-sourcils", "name": "Sourcils", "duration": 15, "price": 18, "options": [] },
            { "id": "orientale-levre", "name": "Lèvre supérieure", "duration": 10, "price": 12, "options": [] },
            { "id": "orientale-aisselles", "name": "Aisselles", "duration": 15, "price": 20, "options": [] },
            { "id": "orientale-bras", "name": "Bras complets", "duration": 30, "price": 35, "options": [] },
            { "id": "orientale-demi-jambes", "name": "Demi-jambes", "duration": 30, "price": 40, "options": [] },
            { "id": "orientale-jambes", "name": "Jambes complètes", "duration": 45, "price": 60, "options": [] },
            { "id": "orientale-maillot-simple", "name": "Maillot simple", "duration": 20, "price": 25, "options": [] },
            { "id": "orientale-maillot-semi", "name": "Maillot semi-intégral", "duration": 25, "price": 35, "options": [] },
            { "id": "orientale-maillot-integral", "name": "Maillot intégral", "duration": 30, "price": 45, "options": [] }
          ]
        },
        {
          "id": "epil-traditionnelle",
          "name": "Épilation Traditionnelle",
          "services": [
            { "id": "trad-sourcils", "name": "Sourcils", "duration": 15, "price": 15, "options": [] },
            { "id": "trad-levre", "name": "Lèvre supérieure", "duration": 10, "price": 10, "options": [] },
            { "id": "trad-aisselles", "name": "Aisselles", "duration": 15, "price": 18, "options": [] },
            { "id": "trad-demi-jambes", "name": "Demi-jambes", "duration": 25, "price": 35, "options": [] },
            { "id": "trad-jambes", "name": "Jambes complètes", "duration": 40, "price": 55, "options": [] },
            { "id": "trad-maillot-simple", "name": "Maillot simple", "duration": 15, "price": 22, "options": [] },
            { "id": "trad-maillot-integral", "name": "Maillot intégral", "duration": 25, "price": 42, "options": [] }
          ]
        },
        {
          "id": "forfaits-epil",
          "name": "Forfaits Épilation",
          "services": [
            { "id": "forfait-demi-jambes-maillot", "name": "Demi-jambes + Maillot simple", "duration": 45, "price": 55, "options": [] },
            { "id": "forfait-jambes-maillot-simple", "name": "Jambes complètes + Maillot simple", "duration": 60, "price": 75, "options": [] },
            { "id": "forfait-jambes-maillot-integral", "name": "Jambes complètes + Maillot intégral", "duration": 70, "price": 95, "options": [] },
            { "id": "forfait-jambes-aisselles-maillot", "name": "Jambes + Aisselles + Maillot simple", "duration": 75, "price": 90, "options": [] },
            { "id": "forfait-complet", "name": "Forfait complet (Jambes + Aisselles + Maillot intégral)", "duration": 90, "price": 120, "options": [] }
          ]
        }
      ]
    },
    {
      "id": "kerlys",
      "name": "Kerlys",
      "subtitle": "Regard & Maquillage permanent",
      "description": "Cils, sourcils, lèvres & épilation",
      "avatar": "👁️",
      "color": "#9B7BB8",
      "categories": [
        {
          "id": "cils",
          "name": "Cils",
          "services": [
            { "id": "pose-cils-classique", "name": "Pose cils à cils (classique)", "duration": 120, "price": 140, "options": [] },
            { "id": "pose-mix-volume", "name": "Pose mix volume", "duration": 150, "price": 170, "options": [] },
            { "id": "pose-volume-russe", "name": "Pose volume russe", "duration": 180, "price": 200, "options": [] },
            { "id": "remplissage-3sem", "name": "Remplissage 3 semaines", "duration": 60, "price": 65, "options": [] },
            { "id": "remplissage-4sem", "name": "Remplissage 4 semaines", "duration": 90, "price": 85, "options": [] },
            { "id": "depose-cils", "name": "Dépose", "duration": 30, "price": 30, "options": [] }
          ]
        },
        {
          "id": "sourcils",
          "name": "Sourcils",
          "services": [
            { "id": "epil-sourcils", "name": "Épilation sourcils", "duration": 15, "price": 18, "options": [] },
            { "id": "epil-henna", "name": "Épilation + Henné", "duration": 30, "price": 38, "options": [] },
            { "id": "brow-lift", "name": "Brow Lift + Épilation + Teinture", "duration": 60, "price": 75, "options": [] },
            { "id": "microblading", "name": "Microblading", "duration": 120, "price": 350, "description": "Maquillage permanent poil à poil", "options": [] },
            { "id": "brow-shadow", "name": "Brow Shadow (ombré)", "duration": 90, "price": 320, "description": "Effet poudré naturel", "options": [] },
            { "id": "magic-shading", "name": "Magic Shading", "duration": 90, "price": 300, "options": [] },
            { "id": "technique-hybride", "name": "Technique Hybride", "duration": 120, "price": 380, "description": "Microblading + Ombré", "options": [] },
            { "id": "retouche-sourcils", "name": "Retouche (dans les 6 semaines)", "duration": 60, "price": 80, "options": [] }
          ]
        },
        {
          "id": "levres",
          "name": "Lèvres",
          "services": [
            { "id": "full-lips", "name": "Micropigmentation Full Lips", "duration": 120, "price": 380, "description": "Lèvres entièrement colorées", "options": [] },
            { "id": "aquarella-lips", "name": "Aquarella Lips", "duration": 120, "price": 350, "description": "Effet naturel dégradé", "options": [] },
            { "id": "retouche-levres", "name": "Retouche (dans les 6 semaines)", "duration": 60, "price": 100, "options": [] }
          ]
        },
        {
          "id": "epil-kerlys",
          "name": "Épilation",
          "services": [
            { "id": "epil-visage", "name": "Visage complet", "duration": 30, "price": 35, "options": [] },
            { "id": "epil-levre", "name": "Lèvre supérieure", "duration": 10, "price": 12, "options": [] },
            { "id": "epil-aisselles", "name": "Aisselles", "duration": 15, "price": 20, "options": [] },
            { "id": "forfait-3-zones", "name": "Forfait 3 zones", "duration": 30, "price": 40, "description": "Choisissez 3 zones au choix", "options": [] }
          ]
        }
      ]
    },
    {
      "id": "diane",
      "name": "Diane",
      "subtitle": "Massages & Corps",
      "description": "Maderothérapie, drainage et massages",
      "avatar": "🧘",
      "color": "#7BA38F",
      "categories": [
        {
          "id": "maderotherapie-corps",
          "name": "Maderothérapie Corps",
          "services": [
            { "id": "madero-corps-60", "name": "Maderothérapie corps (60 min)", "duration": 60, "price": 120, "options": [] },
            { "id": "madero-corps-90", "name": "Maderothérapie corps (90 min)", "duration": 90, "price": 160, "options": [] },
            { "id": "madero-decouverte", "name": "Séance découverte", "duration": 45, "price": 80, "promo": true, "promoLabel": "Offre découverte", "options": [] }
          ]
        },
        {
          "id": "maderotherapie-zone",
          "name": "Maderothérapie par Zone",
          "services": [
            { "id": "madero-ventre", "name": "Ventre / Abdomen", "duration": 30, "price": 55, "options": [] },
            { "id": "madero-cuisses", "name": "Cuisses", "duration": 30, "price": 55, "options": [] },
            { "id": "madero-fessiers", "name": "Fessiers", "duration": 30, "price": 55, "options": [] },
            { "id": "madero-bras", "name": "Bras", "duration": 20, "price": 40, "options": [] }
          ]
        },
        {
          "id": "drainage",
          "name": "Drainage Lymphatique",
          "services": [
            { "id": "drainage-60", "name": "Drainage lymphatique (60 min)", "duration": 60, "price": 110, "options": [] },
            { "id": "drainage-90", "name": "Drainage lymphatique (90 min)", "duration": 90, "price": 150, "options": [] }
          ]
        },
        {
          "id": "massages",
          "name": "Massages",
          "services": [
            { "id": "massage-relaxant-60", "name": "Massage relaxant (60 min)", "duration": 60, "price": 100, "options": [] },
            { "id": "massage-relaxant-90", "name": "Massage relaxant (90 min)", "duration": 90, "price": 140, "options": [] },
            { "id": "massage-prenatal", "name": "Massage prénatal", "duration": 60, "price": 110, "description": "Adapté aux femmes enceintes", "options": [] }
          ]
        },
        {
          "id": "forfaits-diane",
          "name": "Forfaits Multi-Séances",
          "services": [
            { "id": "forfait-madero-4", "name": "Forfait 4 séances Maderothérapie", "duration": 60, "price": 420, "description": "4 x 60 min - Économisez 60 CHF", "isForfait": true, "sessions": 4, "options": [] },
            { "id": "forfait-madero-8", "name": "Forfait 8 séances Maderothérapie", "duration": 60, "price": 780, "description": "8 x 60 min - Économisez 180 CHF", "isForfait": true, "sessions": 8, "options": [] },
            { "id": "forfait-drainage-4", "name": "Forfait 4 séances Drainage", "duration": 60, "price": 380, "description": "4 x 60 min - Économisez 60 CHF", "isForfait": true, "sessions": 4, "options": [] },
            { "id": "forfait-drainage-8", "name": "Forfait 8 séances Drainage", "duration": 60, "price": 700, "description": "8 x 60 min - Économisez 180 CHF", "isForfait": true, "sessions": 8, "options": [] }
          ]
        }
      ]
    }
  ]
};

// ──────────────────────────────────────────────────────────────────────────
// UTILITAIRES
// ──────────────────────────────────────────────────────────────────────────
const formatDuration = (minutes) => {
    if (minutes >= 60) {
        const hours = Math.floor(minutes / 60);
        const mins = minutes % 60;
        return mins > 0 ? `${hours}h${mins}` : `${hours}h`;
    }
    return `${minutes} min`;
};

const formatPrice = (price) => price > 0 ? `CHF ${price}.-` : 'Sur devis';

const formatDate = (date) => {
    const options = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' };
    return date.toLocaleDateString('fr-CH', options);
};

const formatDateShort = (date) => {
    const options = { weekday: 'short', day: 'numeric', month: 'short' };
    return date.toLocaleDateString('fr-CH', options);
};

const getMonthDays = (year, month) => {
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDay = firstDay.getDay() === 0 ? 6 : firstDay.getDay() - 1;
    
    const days = [];
    for (let i = 0; i < startingDay; i++) {
        days.push(null);
    }
    for (let i = 1; i <= daysInMonth; i++) {
        days.push(new Date(year, month, i));
    }
    return days;
};

const MONTHS = ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 
                'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];
const DAYS = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];

const generateTimeSlots = (date) => {
    const dayOfWeek = date.getDay();
    if (dayOfWeek === 0) return [];
    
    const slots = [];
    const startHour = 9;
    const endHour = dayOfWeek === 6 ? 17 : 19;
    
    for (let hour = startHour; hour < endHour; hour++) {
        slots.push(`${hour.toString().padStart(2, '0')}:00`);
        if (hour < endHour - 1 || (hour === endHour - 1 && dayOfWeek !== 6)) {
            slots.push(`${hour.toString().padStart(2, '0')}:30`);
        }
    }
    
    return slots.filter(() => Math.random() > 0.2);
};

const isAtLeast24hAhead = (date) => {
    const now = new Date();
    const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    tomorrow.setHours(0, 0, 0, 0);
    return date >= tomorrow;
};

// Calcul du prix total avec options
const calculateTotalPrice = (service, selectedOption) => {
    let total = service.price;
    if (selectedOption) {
        total += selectedOption.price || 0;
    }
    return total;
};

// ──────────────────────────────────────────────────────────────────────────
// ENVOI EMAIL
// ──────────────────────────────────────────────────────────────────────────
const sendBookingEmail = async (booking) => {
    const { praticienne, category, service, selectedOption, date, time, clientInfo } = booking;
    const dateFormatted = formatDate(date);
    const totalPrice = calculateTotalPrice(service, selectedOption);
    const optionText = selectedOption ? ` (${selectedOption.name})` : '';
    
    const htmlSalon = `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: #0A0908; padding: 30px; text-align: center;">
                <h1 style="color: #C9A872; font-size: 28px; letter-spacing: 0.3em; margin: 0;">SERENYS</h1>
                <p style="color: #C9A872; opacity: 0.6; font-size: 12px; letter-spacing: 0.2em; margin: 5px 0 0 0;">MAISON DE BEAUTÉ</p>
            </div>
            <div style="background: #FAF7F2; padding: 30px;">
                <h2 style="color: #2A2725; margin: 0 0 20px 0;">Nouvelle demande de rendez-vous</h2>
                
                <div style="background: white; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
                    <h3 style="color: #B8956B; margin: 0 0 15px 0; font-size: 14px; text-transform: uppercase;">Client</h3>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Nom:</strong> ${clientInfo.lastName}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Prénom:</strong> ${clientInfo.firstName}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Email:</strong> ${clientInfo.email}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Téléphone:</strong> ${clientInfo.phone}</p>
                </div>
                
                <div style="background: white; border-radius: 8px; padding: 20px;">
                    <h3 style="color: #B8956B; margin: 0 0 15px 0; font-size: 14px; text-transform: uppercase;">Rendez-vous</h3>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Praticien/ne:</strong> ${praticienne.name}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Catégorie:</strong> ${category.name}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Service:</strong> ${service.name}${optionText}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Durée:</strong> ${formatDuration(service.duration)}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Date:</strong> ${dateFormatted}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Heure:</strong> ${time}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Prix:</strong> ${formatPrice(totalPrice)}</p>
                </div>
            </div>
        </div>
    `;
    
    const htmlClient = `
        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <div style="background: #0A0908; padding: 30px; text-align: center;">
                <h1 style="color: #C9A872; font-size: 28px; letter-spacing: 0.3em; margin: 0;">SERENYS</h1>
                <p style="color: #C9A872; opacity: 0.6; font-size: 12px; letter-spacing: 0.2em; margin: 5px 0 0 0;">MAISON DE BEAUTÉ</p>
            </div>
            <div style="background: #FAF7F2; padding: 30px;">
                <h2 style="color: #2A2725; margin: 0 0 10px 0;">Bonjour ${clientInfo.firstName},</h2>
                <p style="color: #5A5550; margin: 0 0 25px 0;">Nous avons bien reçu votre demande de rendez-vous. Nous vous confirmerons la disponibilité rapidement.</p>
                
                <div style="background: white; border-radius: 8px; padding: 20px;">
                    <h3 style="color: #B8956B; margin: 0 0 15px 0; font-size: 14px; text-transform: uppercase;">Récapitulatif</h3>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Praticien/ne:</strong> ${praticienne.name}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Service:</strong> ${service.name}${optionText}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Date souhaitée:</strong> ${dateFormatted}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Heure souhaitée:</strong> ${time}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Durée:</strong> ${formatDuration(service.duration)}</p>
                    <p style="margin: 5px 0; color: #2A2725;"><strong>Prix:</strong> ${formatPrice(totalPrice)}</p>
                </div>
                
                <p style="color: #5A5550; margin: 25px 0 0 0; font-size: 14px;">À très bientôt chez Serenys !</p>
            </div>
            <div style="background: #2A2725; padding: 20px; text-align: center;">
                <p style="color: #C9A872; opacity: 0.8; font-size: 12px; margin: 0 0 5px 0;">Serenys - Maison de Beauté</p>
                <p style="color: #C9A872; opacity: 0.6; font-size: 11px; margin: 0;">Champel, Genève | info@serenys.ch</p>
            </div>
        </div>
    `;
    
    try {
        const response = await fetch(API_CONFIG.mailsApiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                apiKey: API_CONFIG.apiKey,
                from: API_CONFIG.fromEmail,
                from_name: API_CONFIG.fromName,
                to: API_CONFIG.toEmail,
                cc: clientInfo.email,
                subject: `Nouvelle demande - ${praticienne.name} - ${service.name} - ${clientInfo.firstName} ${clientInfo.lastName}`,
                html: htmlSalon
            })
        });
        
        if (!response.ok) throw new Error('Erreur envoi email');
        return { success: true };
    } catch (error) {
        console.error('Erreur email:', error);
        return { success: false, error: error.message };
    }
};

// ──────────────────────────────────────────────────────────────────────────
// COMPOSANTS - Header
// ──────────────────────────────────────────────────────────────────────────
const Header = () => (
    <header className="bg-dark-header text-center py-6 px-4">
        <div className="mb-1">
            <span className="text-gold-500 text-xl sm:text-2xl tracking-[0.4em] font-serif font-light">
                SERENYS
            </span>
        </div>
        <p className="text-gold-600/60 text-[9px] sm:text-[10px] tracking-[0.25em] uppercase">
            Maison de Beauté
        </p>
    </header>
);

// ──────────────────────────────────────────────────────────────────────────
// COMPOSANTS - Stepper
// ──────────────────────────────────────────────────────────────────────────
const Stepper = ({ currentStep, steps, onStepClick }) => (
    <div className="bg-white/50 backdrop-blur-sm border-b border-gold-200/30 py-4">
        <div className="flex items-center justify-center gap-1 sm:gap-2 px-2 max-w-2xl mx-auto">
            {steps.map((step, index) => (
                <React.Fragment key={step.id}>
                    <div 
                        className={`flex flex-col items-center ${index < currentStep ? 'cursor-pointer' : ''}`}
                        onClick={() => index < currentStep && onStepClick(index)}
                    >
                        <div className={`step-indicator-sm ${
                            index < currentStep ? 'completed' : 
                            index === currentStep ? 'active' : 'pending'
                        }`}>
                            {index < currentStep ? '✓' : index + 1}
                        </div>
                        <span className={`text-[7px] sm:text-[9px] mt-1 font-medium text-center leading-tight ${
                            index <= currentStep ? 'text-dark-100' : 'text-dark-50/50'
                        }`}>
                            {step.label}
                        </span>
                    </div>
                    {index < steps.length - 1 && (
                        <div className={`step-line-sm ${index < currentStep ? 'completed' : ''}`} />
                    )}
                </React.Fragment>
            ))}
        </div>
    </div>
);

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 1 - Choix de la praticienne
// ──────────────────────────────────────────────────────────────────────────
const StepPraticienne = ({ selectedPraticienne, onSelect }) => (
    <div className="animate-fade-in-up py-6">
        <div className="text-center mb-6 px-4">
            <h2 className="font-serif text-2xl sm:text-3xl text-dark-100 mb-2">
                Bienvenue chez Serenys
            </h2>
            <p className="text-dark-50/70 text-sm sm:text-base">
                Choisissez votre praticien/ne
            </p>
        </div>
        
        <div className="space-y-3 px-4 max-w-lg mx-auto">
            {CATALOGUE.praticiennes.map((prat, index) => (
                <div
                    key={prat.id}
                    onClick={() => onSelect(prat)}
                    className={`card-praticienne ${selectedPraticienne?.id === prat.id ? 'selected' : ''}`}
                    style={{ 
                        animationDelay: `${index * 0.08}s`,
                        '--prat-color': prat.color 
                    }}
                >
                    <div className="flex items-center gap-4">
                        <div 
                            className="w-14 h-14 rounded-full flex items-center justify-center text-2xl"
                            style={{ background: `${prat.color}20` }}
                        >
                            {prat.avatar}
                        </div>
                        <div className="flex-1">
                            <h3 className="text-dark-100 font-medium text-base sm:text-lg">
                                {prat.name}
                            </h3>
                            {prat.subtitle && (
                                <p className="text-gold-700 text-sm font-medium">{prat.subtitle}</p>
                            )}
                            <p className="text-dark-50/60 text-xs sm:text-sm mt-0.5">
                                {prat.description}
                            </p>
                        </div>
                        <div className="text-gold-500 text-xl">›</div>
                    </div>
                </div>
            ))}
        </div>
    </div>
);

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 2 - Choix de la catégorie
// ──────────────────────────────────────────────────────────────────────────
const StepCategory = ({ praticienne, selectedCategory, onSelect, onBack }) => (
    <div className="animate-fade-in-up py-6">
        <div className="text-center mb-6 px-4">
            <button 
                onClick={onBack}
                className="text-dark-50 text-sm mb-3 hover:text-dark-100 transition-colors flex items-center gap-1 mx-auto"
            >
                <span>‹</span> Retour
            </button>
            <div 
                className="w-12 h-12 rounded-full flex items-center justify-center text-xl mx-auto mb-2"
                style={{ background: `${praticienne.color}20` }}
            >
                {praticienne.avatar}
            </div>
            <h2 className="font-serif text-xl sm:text-2xl text-dark-100 mb-1">
                {praticienne.name}
            </h2>
            <p className="text-dark-50/70 text-sm">
                Choisissez une catégorie
            </p>
        </div>
        
        <div className="grid grid-cols-2 gap-3 px-4 max-w-lg mx-auto">
            {praticienne.categories.map((cat, index) => (
                <div
                    key={cat.id}
                    onClick={() => onSelect(cat)}
                    className={`card-category-sm ${selectedCategory?.id === cat.id ? 'selected' : ''}`}
                    style={{ animationDelay: `${index * 0.05}s` }}
                >
                    <h3 className="text-dark-100 font-medium text-sm sm:text-base text-center">
                        {cat.name}
                    </h3>
                    <p className="text-dark-50/60 text-xs text-center mt-1">
                        {cat.services.length} service{cat.services.length > 1 ? 's' : ''}
                    </p>
                </div>
            ))}
        </div>
    </div>
);

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 3 - Choix du service
// ──────────────────────────────────────────────────────────────────────────
const StepService = ({ praticienne, category, selectedService, onSelect, onBack }) => (
    <div className="animate-fade-in-up py-6">
        <div className="text-center mb-6 px-4">
            <button 
                onClick={onBack}
                className="text-dark-50 text-sm mb-3 hover:text-dark-100 transition-colors flex items-center gap-1 mx-auto"
            >
                <span>‹</span> Retour
            </button>
            <h2 className="font-serif text-xl sm:text-2xl text-dark-100 mb-1">
                {category.name}
            </h2>
            <p className="text-dark-50/70 text-sm">
                {praticienne.name}
            </p>
        </div>
        
        <div className="space-y-2 px-4 max-w-lg mx-auto pb-24">
            {category.services.map((service, index) => (
                <div
                    key={service.id}
                    onClick={() => onSelect(service)}
                    className={`card-service-sm ${selectedService?.id === service.id ? 'selected' : ''}`}
                    style={{ animationDelay: `${index * 0.04}s` }}
                >
                    <div className="flex justify-between items-start">
                        <div className="flex-1 pr-3">
                            <div className="flex items-center gap-2">
                                <h3 className="text-dark-100 font-medium text-sm sm:text-base">
                                    {service.name}
                                </h3>
                                {service.promo && (
                                    <span className="bg-gold-500/20 text-gold-700 text-[10px] px-2 py-0.5 rounded-full">
                                        {service.promoLabel || 'Promo'}
                                    </span>
                                )}
                                {service.isForfait && (
                                    <span className="bg-green-500/20 text-green-700 text-[10px] px-2 py-0.5 rounded-full">
                                        Forfait
                                    </span>
                                )}
                            </div>
                            {service.description && (
                                <p className="text-dark-50/60 text-xs mt-1">{service.description}</p>
                            )}
                            <div className="flex items-center gap-3 mt-2 text-dark-50/60 text-xs">
                                <span className="flex items-center gap-1">
                                    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    {formatDuration(service.duration)}
                                </span>
                                {service.options && service.options.length > 0 && (
                                    <span className="text-gold-600">+ options</span>
                                )}
                            </div>
                        </div>
                        <div className="text-right">
                            <span className="text-gold-700 font-serif text-base sm:text-lg">
                                {formatPrice(service.price)}
                            </span>
                        </div>
                    </div>
                </div>
            ))}
        </div>
    </div>
);

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 4 - Options (si applicable)
// ──────────────────────────────────────────────────────────────────────────
const StepOptions = ({ service, selectedOption, onSelect, onSkip, onBack }) => {
    if (!service.options || service.options.length === 0) {
        // Pas d'options, passer à l'étape suivante automatiquement
        useEffect(() => {
            onSkip();
        }, []);
        return null;
    }
    
    return (
        <div className="animate-fade-in-up py-6">
            <div className="text-center mb-6 px-4">
                <button 
                    onClick={onBack}
                    className="text-dark-50 text-sm mb-3 hover:text-dark-100 transition-colors flex items-center gap-1 mx-auto"
                >
                    <span>‹</span> Retour
                </button>
                <h2 className="font-serif text-xl sm:text-2xl text-dark-100 mb-1">
                    {service.name}
                </h2>
                <p className="text-dark-50/70 text-sm">
                    Choisissez une option
                </p>
            </div>
            
            <div className="space-y-3 px-4 max-w-lg mx-auto pb-24">
                {service.options.map((option, index) => (
                    <div
                        key={option.id}
                        onClick={() => onSelect(option)}
                        className={`card-option ${selectedOption?.id === option.id ? 'selected' : ''}`}
                        style={{ animationDelay: `${index * 0.05}s` }}
                    >
                        <div className="flex justify-between items-center">
                            <span className="text-dark-100 font-medium">{option.name}</span>
                            <span className="text-gold-700 font-serif">
                                {option.price > 0 ? `+${formatPrice(option.price)}` : 'Inclus'}
                            </span>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 5 - Choix de la date
// ──────────────────────────────────────────────────────────────────────────
const StepDate = ({ selectedDate, onSelect, onBack }) => {
    const today = new Date();
    const [currentMonth, setCurrentMonth] = useState(today.getMonth());
    const [currentYear, setCurrentYear] = useState(today.getFullYear());
    
    const days = getMonthDays(currentYear, currentMonth);
    
    const goToPrevMonth = () => {
        if (currentMonth === 0) {
            setCurrentMonth(11);
            setCurrentYear(currentYear - 1);
        } else {
            setCurrentMonth(currentMonth - 1);
        }
    };
    
    const goToNextMonth = () => {
        if (currentMonth === 11) {
            setCurrentMonth(0);
            setCurrentYear(currentYear + 1);
        } else {
            setCurrentMonth(currentMonth + 1);
        }
    };
    
    const isDateAvailable = (date) => {
        if (!date) return false;
        return isAtLeast24hAhead(date) && date.getDay() !== 0;
    };
    
    const isSelected = (date) => {
        if (!date || !selectedDate) return false;
        return date.toDateString() === selectedDate.toDateString();
    };
    
    const canGoPrev = currentYear > today.getFullYear() || 
                      (currentYear === today.getFullYear() && currentMonth > today.getMonth());
    
    return (
        <div className="animate-fade-in-up py-6">
            <div className="text-center mb-6 px-4">
                <button 
                    onClick={onBack}
                    className="text-dark-50 text-sm mb-3 hover:text-dark-100 transition-colors flex items-center gap-1 mx-auto"
                >
                    <span>‹</span> Retour
                </button>
                <h2 className="font-serif text-xl sm:text-2xl text-dark-100 mb-1">
                    Choisissez une date
                </h2>
                <p className="text-dark-50/70 text-sm">
                    Minimum 24h à l'avance
                </p>
            </div>
            
            <div className="flex justify-center px-4">
                <div className="glass-gold-light rounded-xl p-4 sm:p-5 w-full max-w-sm">
                    <div className="flex items-center justify-between mb-4">
                        <button 
                            onClick={goToPrevMonth}
                            disabled={!canGoPrev}
                            className={`text-dark-50 p-1 text-xl ${!canGoPrev ? 'opacity-30' : 'hover:text-dark-100'}`}
                        >
                            ‹
                        </button>
                        <span className="text-dark-100 font-serif text-lg">
                            {MONTHS[currentMonth]} {currentYear}
                        </span>
                        <button 
                            onClick={goToNextMonth}
                            className="text-dark-50 p-1 text-xl hover:text-dark-100"
                        >
                            ›
                        </button>
                    </div>
                    
                    <div className="grid grid-cols-7 gap-0.5 mb-2">
                        {DAYS.map(day => (
                            <div key={day} className="text-center text-dark-50/70 text-xs font-medium py-1">
                                {day}
                            </div>
                        ))}
                    </div>
                    
                    <div className="grid grid-cols-7 gap-0.5">
                        {days.map((date, index) => (
                            <div
                                key={index}
                                onClick={() => isDateAvailable(date) && onSelect(date)}
                                className={`calendar-day-sm ${
                                    !date ? '' :
                                    !isDateAvailable(date) ? 'disabled' :
                                    isSelected(date) ? 'selected' : ''
                                }`}
                            >
                                {date ? date.getDate() : ''}
                            </div>
                        ))}
                    </div>
                    
                    <p className="text-center text-dark-50/60 text-xs mt-4">
                        Fermé le dimanche
                    </p>
                </div>
            </div>
        </div>
    );
};

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 6 - Choix de l'heure
// ──────────────────────────────────────────────────────────────────────────
const StepTime = ({ selectedDate, selectedTime, onSelect, onBack }) => {
    const [slots, setSlots] = useState([]);
    
    useEffect(() => {
        if (selectedDate) {
            setSlots(generateTimeSlots(selectedDate));
        }
    }, [selectedDate]);
    
    return (
        <div className="animate-fade-in-up py-6">
            <div className="text-center mb-6 px-4">
                <button 
                    onClick={onBack}
                    className="text-dark-50 text-sm mb-3 hover:text-dark-100 transition-colors flex items-center gap-1 mx-auto"
                >
                    <span>‹</span> Retour
                </button>
                <h2 className="font-serif text-xl sm:text-2xl text-dark-100 mb-1">
                    Choisissez l'heure
                </h2>
                <p className="text-dark-50/70 text-sm capitalize">
                    {formatDateShort(selectedDate)}
                </p>
            </div>
            
            <div className="flex justify-center px-4 pb-24">
                <div className="w-full max-w-lg">
                    {slots.length > 0 ? (
                        <>
                            <p className="text-dark-50/70 text-sm mb-4 text-center">
                                {slots.length} créneaux disponibles
                            </p>
                            <div className="grid grid-cols-4 sm:grid-cols-5 gap-2">
                                {slots.map((slot, index) => (
                                    <div
                                        key={slot}
                                        onClick={() => onSelect(slot)}
                                        className={`time-slot-sm ${selectedTime === slot ? 'selected' : ''}`}
                                        style={{ animationDelay: `${index * 0.02}s` }}
                                    >
                                        {slot}
                                    </div>
                                ))}
                            </div>
                        </>
                    ) : (
                        <div className="text-center py-6">
                            <p className="text-dark-50/70 mb-4">Aucun créneau disponible</p>
                            <button onClick={onBack} className="btn-outline-sm">
                                Choisir une autre date
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 7 - Infos client
// ──────────────────────────────────────────────────────────────────────────
const StepInfos = ({ clientInfo, onChange, onBack, errors }) => (
    <div className="animate-fade-in-up py-6">
        <div className="text-center mb-6 px-4">
            <button 
                onClick={onBack}
                className="text-dark-50 text-sm mb-3 hover:text-dark-100 transition-colors flex items-center gap-1 mx-auto"
            >
                <span>‹</span> Retour
            </button>
            <h2 className="font-serif text-xl sm:text-2xl text-dark-100 mb-1">
                Vos coordonnées
            </h2>
            <p className="text-dark-50/70 text-sm">
                Pour confirmer votre rendez-vous
            </p>
        </div>
        
        <div className="flex justify-center px-4 pb-24">
            <div className="w-full max-w-md space-y-3">
                <div>
                    <label className="block text-dark-100 text-sm font-medium mb-1.5">Nom *</label>
                    <input
                        type="text"
                        value={clientInfo.lastName}
                        onChange={(e) => onChange('lastName', e.target.value)}
                        placeholder="Votre nom"
                        className={`input-field ${errors.lastName ? 'border-red-400' : ''}`}
                    />
                    {errors.lastName && <p className="text-red-500 text-xs mt-1">{errors.lastName}</p>}
                </div>
                
                <div>
                    <label className="block text-dark-100 text-sm font-medium mb-1.5">Prénom *</label>
                    <input
                        type="text"
                        value={clientInfo.firstName}
                        onChange={(e) => onChange('firstName', e.target.value)}
                        placeholder="Votre prénom"
                        className={`input-field ${errors.firstName ? 'border-red-400' : ''}`}
                    />
                    {errors.firstName && <p className="text-red-500 text-xs mt-1">{errors.firstName}</p>}
                </div>
                
                <div>
                    <label className="block text-dark-100 text-sm font-medium mb-1.5">Email *</label>
                    <input
                        type="email"
                        value={clientInfo.email}
                        onChange={(e) => onChange('email', e.target.value)}
                        placeholder="votre@email.com"
                        className={`input-field ${errors.email ? 'border-red-400' : ''}`}
                    />
                    {errors.email && <p className="text-red-500 text-xs mt-1">{errors.email}</p>}
                </div>
                
                <div>
                    <label className="block text-dark-100 text-sm font-medium mb-1.5">Téléphone *</label>
                    <input
                        type="tel"
                        value={clientInfo.phone}
                        onChange={(e) => onChange('phone', e.target.value)}
                        placeholder="+41 79 123 45 67"
                        className={`input-field ${errors.phone ? 'border-red-400' : ''}`}
                    />
                    {errors.phone && <p className="text-red-500 text-xs mt-1">{errors.phone}</p>}
                </div>
            </div>
        </div>
    </div>
);

// ──────────────────────────────────────────────────────────────────────────
// ÉTAPE 8 - Résumé & Confirmation
// ──────────────────────────────────────────────────────────────────────────
const StepSummary = ({ booking, onConfirm, onBack, isSubmitting }) => {
    const totalPrice = calculateTotalPrice(booking.service, booking.selectedOption);
    const optionText = booking.selectedOption ? ` (${booking.selectedOption.name})` : '';
    
    return (
        <div className="animate-fade-in-up py-6">
            <div className="text-center mb-6 px-4">
                <button 
                    onClick={onBack}
                    className="text-dark-50 text-sm mb-3 hover:text-dark-100 transition-colors flex items-center gap-1 mx-auto"
                >
                    <span>‹</span> Modifier
                </button>
                <h2 className="font-serif text-xl sm:text-2xl text-dark-100 mb-1">
                    Récapitulatif
                </h2>
            </div>
            
            <div className="flex justify-center px-4 mb-6">
                <div className="summary-card p-5 w-full max-w-md">
                    <div className="mb-4">
                        <p className="text-dark-50/70 text-xs uppercase tracking-wider mb-1">Client</p>
                        <p className="text-dark-100 font-medium">{booking.clientInfo.firstName} {booking.clientInfo.lastName}</p>
                        <p className="text-dark-50/70 text-sm">{booking.clientInfo.email}</p>
                        <p className="text-dark-50/70 text-sm">{booking.clientInfo.phone}</p>
                    </div>
                    
                    <div className="divider-gold mb-4" />
                    
                    <div className="mb-4">
                        <p className="text-dark-50/70 text-xs uppercase tracking-wider mb-1">Praticien/ne</p>
                        <p className="text-dark-100 font-medium">{booking.praticienne.name}</p>
                    </div>
                    
                    <div className="mb-4">
                        <p className="text-dark-50/70 text-xs uppercase tracking-wider mb-1">Service</p>
                        <p className="text-dark-100 font-medium">{booking.service.name}{optionText}</p>
                        <p className="text-dark-50/70 text-sm">{booking.category.name}</p>
                    </div>
                    
                    <div className="divider-gold mb-4" />
                    
                    <div className="grid grid-cols-2 gap-4 mb-4">
                        <div>
                            <p className="text-dark-50/70 text-xs uppercase tracking-wider mb-1">Date</p>
                            <p className="text-dark-100 capitalize">{formatDateShort(booking.date)}</p>
                        </div>
                        <div>
                            <p className="text-dark-50/70 text-xs uppercase tracking-wider mb-1">Heure</p>
                            <p className="text-dark-100">{booking.time}</p>
                        </div>
                    </div>
                    
                    <div className="divider-gold mb-4" />
                    
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <p className="text-dark-50/70 text-xs uppercase tracking-wider mb-1">Durée</p>
                            <p className="text-dark-100">{formatDuration(booking.service.duration)}</p>
                        </div>
                        <div>
                            <p className="text-dark-50/70 text-xs uppercase tracking-wider mb-1">Prix</p>
                            <p className="text-gold-700 font-serif text-lg">{formatPrice(totalPrice)}</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div className="flex justify-center px-4 pb-6">
                <div className="w-full max-w-md space-y-3">
                    <button 
                        onClick={onConfirm}
                        disabled={isSubmitting}
                        className="btn-gold w-full flex items-center justify-center gap-2"
                    >
                        {isSubmitting ? (
                            <>
                                <span className="animate-spin">◌</span>
                                Envoi en cours...
                            </>
                        ) : (
                            'Envoyer ma demande'
                        )}
                    </button>
                    <p className="text-dark-50/60 text-xs text-center">
                        Vous recevrez un email de confirmation
                    </p>
                </div>
            </div>
        </div>
    );
};

// ──────────────────────────────────────────────────────────────────────────
// ÉCRAN DE CONFIRMATION
// ──────────────────────────────────────────────────────────────────────────
const ConfirmationScreen = ({ booking, onNewBooking }) => {
    const totalPrice = calculateTotalPrice(booking.service, booking.selectedOption);
    
    return (
        <div className="animate-scale-in text-center px-4 py-10">
            <div className="confirmation-icon">
                <svg className="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
                </svg>
            </div>
            
            <h2 className="font-serif text-2xl sm:text-3xl text-dark-100 mb-3">
                Demande envoyée !
            </h2>
            <p className="text-dark-50/70 text-sm sm:text-base mb-6 max-w-sm mx-auto">
                Merci {booking.clientInfo.firstName} ! Nous vous confirmerons rapidement votre rendez-vous avec <span className="text-dark-100 font-medium">{booking.praticienne.name}</span>.
            </p>
            
            <div className="flex justify-center mb-6">
                <div className="summary-card p-5 w-full max-w-sm text-left">
                    <div className="flex justify-between text-sm mb-2">
                        <span className="text-dark-50/70">Service</span>
                        <span className="text-dark-100">{booking.service.name}</span>
                    </div>
                    <div className="flex justify-between text-sm mb-2">
                        <span className="text-dark-50/70">Date</span>
                        <span className="text-dark-100 capitalize">{formatDateShort(booking.date)}</span>
                    </div>
                    <div className="flex justify-between text-sm mb-2">
                        <span className="text-dark-50/70">Heure</span>
                        <span className="text-dark-100">{booking.time}</span>
                    </div>
                    <div className="divider-gold my-3" />
                    <div className="flex justify-between">
                        <span className="text-dark-50/70">Total</span>
                        <span className="text-gold-700 font-serif text-lg">{formatPrice(totalPrice)}</span>
                    </div>
                </div>
            </div>
            
            <p className="text-dark-50/60 text-sm mb-4">
                Confirmation envoyée à<br/>
                <span className="text-dark-100">{booking.clientInfo.email}</span>
            </p>
            
            <button onClick={onNewBooking} className="btn-outline-sm">
                Nouvelle demande
            </button>
        </div>
    );
};

// ──────────────────────────────────────────────────────────────────────────
// APPLICATION PRINCIPALE
// ──────────────────────────────────────────────────────────────────────────
const App = () => {
    const [step, setStep] = useState(0);
    const [booking, setBooking] = useState({
        praticienne: null,
        category: null,
        service: null,
        selectedOption: null,
        date: null,
        time: null,
        clientInfo: {
            firstName: '',
            lastName: '',
            email: '',
            phone: ''
        }
    });
    const [formErrors, setFormErrors] = useState({});
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isConfirmed, setIsConfirmed] = useState(false);
    
    // Définir les étapes dynamiquement selon si le service a des options
    const hasOptions = booking.service?.options?.length > 0;
    
    const steps = [
        { id: 'praticienne', label: 'Praticien/ne' },
        { id: 'category', label: 'Catégorie' },
        { id: 'service', label: 'Service' },
        ...(hasOptions ? [{ id: 'options', label: 'Options' }] : []),
        { id: 'date', label: 'Date' },
        { id: 'time', label: 'Heure' },
        { id: 'infos', label: 'Infos' },
        { id: 'summary', label: 'Confirmer' }
    ];
    
    // Mapping des étapes
    const getStepIndex = (stepName) => {
        if (!hasOptions && stepName === 'options') return -1;
        return steps.findIndex(s => s.id === stepName);
    };
    
    const getCurrentStepId = () => steps[step]?.id;
    
    const handleSelectPraticienne = (prat) => {
        setBooking(prev => ({ ...prev, praticienne: prat, category: null, service: null, selectedOption: null }));
        setStep(1);
    };
    
    const handleSelectCategory = (cat) => {
        setBooking(prev => ({ ...prev, category: cat, service: null, selectedOption: null }));
        setStep(2);
    };
    
    const handleSelectService = (service) => {
        setBooking(prev => ({ ...prev, service, selectedOption: null }));
        // Si le service a des options, aller à l'étape options, sinon passer directement à la date
        if (service.options && service.options.length > 0) {
            setStep(3);
        } else {
            // Pas d'options, passer à la date (qui sera à l'index 3 sans options)
            setStep(3);
        }
    };
    
    const handleSelectOption = (option) => {
        setBooking(prev => ({ ...prev, selectedOption: option }));
        setStep(step + 1);
    };
    
    const handleSkipOptions = () => {
        setStep(step + 1);
    };
    
    const handleSelectDate = (date) => {
        setBooking(prev => ({ ...prev, date, time: null }));
        setStep(step + 1);
    };
    
    const handleSelectTime = (time) => {
        setBooking(prev => ({ ...prev, time }));
        setStep(step + 1);
    };
    
    const handleClientInfoChange = (field, value) => {
        setBooking(prev => ({
            ...prev,
            clientInfo: { ...prev.clientInfo, [field]: value }
        }));
        if (formErrors[field]) {
            setFormErrors(prev => ({ ...prev, [field]: null }));
        }
    };
    
    const validateClientInfo = () => {
        const errors = {};
        const { clientInfo } = booking;
        
        if (!clientInfo.lastName.trim()) errors.lastName = 'Le nom est requis';
        if (!clientInfo.firstName.trim()) errors.firstName = 'Le prénom est requis';
        if (!clientInfo.email.trim()) {
            errors.email = 'L\'email est requis';
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(clientInfo.email)) {
            errors.email = 'Email invalide';
        }
        if (!clientInfo.phone.trim()) errors.phone = 'Le téléphone est requis';
        
        setFormErrors(errors);
        return Object.keys(errors).length === 0;
    };
    
    const handleContinue = () => {
        const currentId = getCurrentStepId();
        if (currentId === 'infos') {
            if (validateClientInfo()) {
                setStep(step + 1);
            }
        } else {
            setStep(step + 1);
        }
    };
    
    const handleConfirm = async () => {
        setIsSubmitting(true);
        const result = await sendBookingEmail(booking);
        setIsSubmitting(false);
        
        if (result.success) {
            setIsConfirmed(true);
        } else {
            alert('Une erreur est survenue. Veuillez réessayer.');
        }
    };
    
    const handleNewBooking = () => {
        setBooking({
            praticienne: null,
            category: null,
            service: null,
            selectedOption: null,
            date: null,
            time: null,
            clientInfo: { firstName: '', lastName: '', email: '', phone: '' }
        });
        setFormErrors({});
        setStep(0);
        setIsConfirmed(false);
    };
    
    const handleStepClick = (targetStep) => {
        if (targetStep < step) {
            setStep(targetStep);
        }
    };
    
    if (isConfirmed) {
        return (
            <div className="min-h-screen bg-cream flex flex-col">
                <Header />
                <div className="flex-1 flex items-center justify-center">
                    <ConfirmationScreen booking={booking} onNewBooking={handleNewBooking} />
                </div>
            </div>
        );
    }
    
    const currentId = getCurrentStepId();
    
    // Déterminer si on peut continuer (pour le bouton flottant)
    const canContinue = () => {
        switch (currentId) {
            case 'service': return !!booking.service;
            case 'options': return !!booking.selectedOption;
            case 'date': return !!booking.date;
            case 'time': return !!booking.time;
            case 'infos': return true; // Validation au clic
            default: return false;
        }
    };
    
    // Afficher le bouton continuer ?
    const showContinueButton = ['service', 'date', 'time', 'infos'].includes(currentId) ||
                               (currentId === 'options' && hasOptions);
    
    return (
        <div className="min-h-screen bg-cream flex flex-col">
            <Header />
            <Stepper currentStep={step} steps={steps} onStepClick={handleStepClick} />
            
            <div className="flex-1">
                {currentId === 'praticienne' && (
                    <StepPraticienne 
                        selectedPraticienne={booking.praticienne}
                        onSelect={handleSelectPraticienne}
                    />
                )}
                
                {currentId === 'category' && (
                    <StepCategory 
                        praticienne={booking.praticienne}
                        selectedCategory={booking.category}
                        onSelect={handleSelectCategory}
                        onBack={() => setStep(0)}
                    />
                )}
                
                {currentId === 'service' && (
                    <StepService 
                        praticienne={booking.praticienne}
                        category={booking.category}
                        selectedService={booking.service}
                        onSelect={handleSelectService}
                        onBack={() => setStep(1)}
                    />
                )}
                
                {currentId === 'options' && hasOptions && (
                    <StepOptions 
                        service={booking.service}
                        selectedOption={booking.selectedOption}
                        onSelect={handleSelectOption}
                        onSkip={handleSkipOptions}
                        onBack={() => setStep(2)}
                    />
                )}
                
                {currentId === 'date' && (
                    <StepDate 
                        selectedDate={booking.date}
                        onSelect={handleSelectDate}
                        onBack={() => setStep(hasOptions ? 3 : 2)}
                    />
                )}
                
                {currentId === 'time' && (
                    <StepTime 
                        selectedDate={booking.date}
                        selectedTime={booking.time}
                        onSelect={handleSelectTime}
                        onBack={() => setStep(step - 1)}
                    />
                )}
                
                {currentId === 'infos' && (
                    <StepInfos 
                        clientInfo={booking.clientInfo}
                        onChange={handleClientInfoChange}
                        onBack={() => setStep(step - 1)}
                        errors={formErrors}
                    />
                )}
                
                {currentId === 'summary' && (
                    <StepSummary 
                        booking={booking}
                        onConfirm={handleConfirm}
                        onBack={() => setStep(step - 1)}
                        isSubmitting={isSubmitting}
                    />
                )}
            </div>
            
            {/* Bouton Continuer flottant */}
            {showContinueButton && currentId !== 'summary' && (
                <div className="fixed bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-gold-100 via-gold-50/95 to-transparent">
                    <button 
                        onClick={handleContinue}
                        disabled={!canContinue()}
                        className="btn-gold w-full max-w-md mx-auto block text-sm"
                    >
                        Continuer
                    </button>
                </div>
            )}
        </div>
    );
};

// Rendu de l'application
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
