// Booking / Agenda component — multi-step flow V2

const DEFAULT_AVAILABILITY = {
  days: {
    1: { enabled: true, hours: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'] },
    2: { enabled: true, hours: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'] },
    3: { enabled: true, hours: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'] },
    4: { enabled: true, hours: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'] },
    5: { enabled: true, hours: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'] },
    6: { enabled: true, hours: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'] },
    0: { enabled: false, hours: ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'] }
  },
  specialBlocksList: []
};

const migrateAvailability = (parsed) => {
  if (!parsed) return DEFAULT_AVAILABILITY;
  
  let migrated = { ...parsed };
  const standardHours = ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00'];
  
  if (migrated.days) {
    const newDays = {};
    const dayNums = [1, 2, 3, 4, 5, 6, 0];
    dayNums.forEach(num => {
      const val = migrated.days[num];
      if (val === undefined) {
        newDays[num] = { enabled: num !== 0, hours: [...(migrated.hours || standardHours)] };
      } else if (typeof val === 'boolean') {
        newDays[num] = { enabled: val, hours: [...(migrated.hours || standardHours)] };
      } else if (typeof val === 'object' && val !== null) {
        newDays[num] = {
          enabled: val.enabled !== undefined ? val.enabled : true,
          hours: Array.isArray(val.hours) ? val.hours : [...(migrated.hours || standardHours)]
        };
      } else {
        newDays[num] = { enabled: num !== 0, hours: [...(migrated.hours || standardHours)] };
      }
    });
    migrated.days = newDays;
  } else {
    migrated.days = { ...DEFAULT_AVAILABILITY.days };
  }

  if (!Array.isArray(migrated.specialBlocksList)) {
    migrated.specialBlocksList = [];
    if (migrated.specialBlocks && typeof migrated.specialBlocks === 'object' && !Array.isArray(migrated.specialBlocks)) {
      Object.keys(migrated.specialBlocks).forEach(dateStr => {
        const hours = migrated.specialBlocks[dateStr];
        if (Array.isArray(hours) && hours.length > 0) {
          migrated.specialBlocksList.push({
            id: `block-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`,
            date: dateStr,
            hours: hours,
            desc: 'Bloqueo administrativo'
          });
        }
      });
    }
  }

  return migrated;
};

const getStoredServices = () => {
  try {
    const stored = localStorage.getItem('eadq_services');
    if (stored) return JSON.parse(stored);
  } catch(e) {}
  return [
    { id: 'facial', name: 'Limpieza Facial Profunda', duration: '60 min', price: '$25.000', category: 'Cosmetología' },
    { id: 'relajacion', name: 'Masaje de Relajación', duration: '60 min', price: '$25.000', category: 'Masoterapia' },
    { id: 'descontracturante', name: 'Masaje Descontracturante', duration: '60 min', price: '$25.000', category: 'Masoterapia' },
    { id: 'lash', name: 'Lash Lifting', duration: '45 min', price: 'Consultar', category: 'Otros Servicios' },
    { id: 'reductor', name: 'Tratamiento Reductor', duration: '10 sesiones', price: '$220.000', category: 'Corporales' },
    { id: 'giftcard', name: 'Gift Card', duration: '—', price: 'A tu medida', category: 'Otros Servicios' },
  ];
};

const getLocalDateString = (d) => {
  if (!d) return '';
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const fmt = (d) => d.toLocaleDateString('es-CL', { weekday: 'short', day: 'numeric', month: 'short' });
const fmtFull = (d) => d.toLocaleDateString('es-CL', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

const IconWhatsApp = () => (
  <svg width="20" height="20" viewBox="0 0 28 28" fill="none" style={{ display: 'inline-block', verticalAlign: 'middle' }}>
    <path d="M14 2C7.37 2 2 7.37 2 14c0 2.12.56 4.1 1.52 5.82L2 26l6.35-1.5C9.9 25.45 11.9 26 14 26c6.63 0 12-5.37 12-12S20.63 2 14 2z" fill="#fff"/>
    <path d="M20 17.5c-.3-.15-1.77-.87-2.04-.97-.28-.1-.48-.15-.68.15-.2.3-.77.97-.94 1.17-.17.2-.35.22-.65.07-.3-.15-1.26-.46-2.4-1.48-.89-.79-1.49-1.77-1.66-2.07-.17-.3-.02-.46.13-.61.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.68-1.63-.93-2.24-.24-.58-.49-.5-.68-.5-.17 0-.37-.03-.57-.03-.2 0-.52.07-.8.37-.27.3-1.04 1.02-1.04 2.47 0 1.46 1.07 2.87 1.22 3.07.15.2 2.1 3.2 5.08 4.49.71.3 1.26.49 1.69.62.71.22 1.36.19 1.87.12.57-.08 1.77-.72 2.02-1.42.25-.7.25-1.3.17-1.42-.07-.12-.27-.2-.57-.35z" fill="#25D366"/>
  </svg>
);

const Agenda = () => {
  const [step, setStep] = React.useState(1);
  const [selected, setSelected] = React.useState({ service: null, date: null, time: null, name: '', email: '', phone: '' });
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [dayOffset, setDayOffset] = React.useState(0);

  const [servicesList, setServicesList] = React.useState([]);
  const [timesList, setTimesList] = React.useState([]);
  const [takenTimes, setTakenTimes] = React.useState([]);
  const [specialBlocksList, setSpecialBlocksList] = React.useState([]);
  const [availability, setAvailability] = React.useState(DEFAULT_AVAILABILITY);
  
  // State for collapsible categories
  const [expandedCategories, setExpandedCategories] = React.useState({});
  
  // Ref to automatically scroll to continue button when a service is selected
  const continueBtnRef = React.useRef(null);

  // 1. Cargar Disponibilidad de la API al montar
  React.useEffect(() => {
    Promise.all([
      fetch('/api/availability').then(r => r.json()).catch(() => []),
      fetch('/api/special-blocks').then(r => r.json()).catch(() => [])
    ]).then(([availDays, blocks]) => {
      if (availDays.length === 0) {
        throw new Error('Sin datos en servidor');
      }
      const daysObj = {};
      availDays.forEach(d => {
        daysObj[d.day_of_week] = {
          enabled: d.enabled,
          hours: Array.isArray(d.hours) ? d.hours : JSON.parse(d.hours || '[]')
        };
      });

      const blockList = blocks.map(b => ({
        id: b.id,
        date: b.date,
        description: b.description,
        hours: Array.isArray(b.hours) ? b.hours : JSON.parse(b.hours || '[]')
      }));

      setAvailability({
        days: daysObj,
        specialBlocksList: blockList
      });
    }).catch(err => {
      console.warn('⚠️ No se pudo cargar disponibilidad desde el servidor, usando respaldo local:', err.message);
      try {
        const stored = localStorage.getItem('eadq_availability');
        if (stored) {
          setAvailability(migrateAvailability(JSON.parse(stored)));
        }
      } catch (e) {}
    });
  }, []);

  // 2. Cargar servicios desde la API
  React.useEffect(() => {
    fetch('/api/services')
      .then(r => r.json())
      .then(svcs => {
        const mapped = svcs.map(s => ({
          ...s,
          id: String(s.id),
          needsCoordination: s.needs_coordination,
          desc: s.description,
          category: s.category || 'Otros Servicios',
          benefits: Array.isArray(s.benefits) ? s.benefits : JSON.parse(s.benefits || '[]')
        }));
        setServicesList(mapped.filter(s => !s.needsCoordination));
      })
      .catch(err => {
        console.warn('⚠️ Cargando servicios de respaldo local:', err.message);
        setServicesList(getStoredServices().filter(s => !s.needsCoordination));
      });
  }, [step]);

  // 4. Preseleccionar servicio desde redirección externa (Servicios)
  React.useEffect(() => {
    if (servicesList.length > 0) {
      const storedName = localStorage.getItem('eadq_selected_service_name');
      if (storedName) {
        const found = servicesList.find(s => s.name.trim().toLowerCase() === storedName.trim().toLowerCase());
        if (found) {
          setSelected(prev => ({ ...prev, service: found.id }));
          setStep(2);
        }
        localStorage.removeItem('eadq_selected_service_name');
      }
    }
  }, [servicesList]);

  // 3. Cargar horas tomadas cuando se selecciona una fecha
  React.useEffect(() => {
    if (!selected.date) return;
    const dateStr = getLocalDateString(selected.date);
    const dayOfWeek = selected.date.getDay();

    const dayConfig = availability.days[dayOfWeek] || { enabled: false, hours: [] };
    setTimesList(dayConfig.hours.length > 0 ? dayConfig.hours : ['09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00']);

    fetch(`/api/appointments/taken-slots?date=${dateStr}`)
      .then(r => r.json())
      .then(taken => {
        setTakenTimes(taken);
      })
      .catch(err => {
        console.warn('⚠️ No se pudo obtener horas tomadas del servidor, usando local storage:', err.message);
        let taken = [];
        try {
          const stored = localStorage.getItem('eadq_appointments');
          if (stored) {
            const appts = JSON.parse(stored);
            taken = appts
              .filter(a => a.date.startsWith(dateStr) && a.status !== 'cancelled')
              .map(a => a.time);
          }
        } catch(e) {}
        setTakenTimes(taken);
      });

    setSpecialBlocksList(availability.specialBlocksList || []);
  }, [selected.date, availability]);

  const getDaysFromAvail = (avail) => {
    const days = [];
    const today = new Date();
    for (let i = 1; i <= 28; i++) {
      const d = new Date(today);
      d.setDate(today.getDate() + i);
      const dayOfWeek = d.getDay();
      const dayConfig = avail.days[dayOfWeek];
      if (dayConfig && dayConfig.enabled) {
        days.push(d);
      }
    }
    return days;
  };

  const days = getDaysFromAvail(availability);
  const visibleDays = days.slice(dayOffset, dayOffset + 7);

  const svc = servicesList.find(s => s.id === selected.service);
  const priceFmt = (p) => {
    if (typeof p === 'number') {
      return p === 0 ? 'Consultar' : `$${p.toLocaleString('es-CL')} CLP`;
    }
    return p || 'Consultar';
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    try {
      const formattedPrice = priceFmt((svc && svc.price));
      const dateStr = getLocalDateString(selected.date);

      const payload = {
        service_name: (svc && svc.name),
        date: dateStr,
        time: selected.time,
        name: selected.name,
        email: selected.email,
        phone: selected.phone
      };

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

      if (!response.ok) {
        const errData = await response.json().catch(() => ({}));
        throw new Error(errData.error || `Error del servidor: ${response.status}`);
      }

      const data = await response.json();

      try {
        const stored = localStorage.getItem('eadq_appointments');
        const appts = stored ? JSON.parse(stored) : [];
        const newAppt = {
          id: (data.appointment && data.appointment.id) || `appt-${Date.now()}`,
          name: selected.name,
          email: selected.email,
          phone: selected.phone,
          service: (svc && svc.name),
          duration: (svc && svc.duration),
          price: formattedPrice,
          date: selected.date.toISOString(),
          time: selected.time,
          status: 'confirmed'
        };
        appts.push(newAppt);
        localStorage.setItem('eadq_appointments', JSON.stringify(appts));
      } catch(localErr) {
        console.error('Error saving local appointment:', localErr);
      }

      setSubmitted(true);
    } catch (err) {
      console.error(err);
      setError('Hubo un inconveniente al registrar tu cita en el servidor. Pero no te preocupes, puedes confirmar directamente por WhatsApp.');
    } finally {
      setSubmitting(false);
    }
  };

  // Group services by category
  const servicesByCategory = {};
  servicesList.forEach(s => {
    const cat = s.category || 'Otros Servicios';
    if (!servicesByCategory[cat]) {
      servicesByCategory[cat] = [];
    }
    servicesByCategory[cat].push(s);
  });

  const displayStep = submitted ? 6 : step;
  const stepLabels = ['Selecciona tu Servicio', 'Elige la Fecha', 'Selecciona la Hora', 'Tus Datos', 'Confirma tu Reserva'];

  const renderStep = (i) => {
    if (i === 1) {
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {Object.keys(servicesByCategory).map(categoryName => {
            const isOpen = !!expandedCategories[categoryName]; // Collapsed by default
            const servicesInCat = servicesByCategory[categoryName];
            
            return (
              <div key={categoryName} style={{ 
                marginBottom: 12, 
                borderRadius: 16, 
                background: '#fff', 
                border: '1px solid rgba(136,201,193,0.25)', 
                overflow: 'hidden', 
                boxShadow: '0 4px 20px rgba(0,0,0,0.02)' 
              }}>
                <div 
                  onClick={() => setExpandedCategories(prev => ({ ...prev, [categoryName]: !isOpen }))}
                  style={{
                    padding: '18px 24px',
                    background: isOpen ? 'linear-gradient(90deg, #E8F5F3, #FAFAF8)' : '#fff',
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    cursor: 'pointer',
                    userSelect: 'none',
                    transition: 'all 0.3s ease',
                    borderBottom: isOpen ? '1px solid rgba(136,201,193,0.15)' : 'none'
                  }}
                >
                  <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 600, color: '#1a1a1a', margin: 0, fontStyle: 'italic' }}>
                    {categoryName} <span style={{ fontFamily: "'Outfit', sans-serif", fontSize: 13, color: '#88C9C1', marginLeft: 8, fontWeight: 400, fontStyle: 'normal' }}>({servicesInCat.length})</span>
                  </h3>
                  <span style={{ 
                    transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)', 
                    transition: 'transform 0.3s cubic-bezier(0.22, 1, 0.36, 1)',
                    color: '#88C9C1',
                    fontSize: 14,
                    fontWeight: 'bold',
                    display: 'inline-block'
                  }}>
                    ▼
                  </span>
                </div>
                
                <div style={{
                  maxHeight: isOpen ? '2000px' : '0px',
                  overflow: 'hidden',
                  transition: 'max-height 0.4s cubic-bezier(0.25, 1, 0.5, 1)',
                  background: '#fff'
                }}>
                  <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {servicesInCat.map(s => {
                      const isSelected = selected.service === s.id;
                      return (
                        <div 
                          key={s.id} 
                          onClick={() => {
                            setSelected(p => ({ ...p, service: s.id }));
                            setTimeout(() => {
                              if (continueBtnRef.current) {
                                continueBtnRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                              }
                            }, 100);
                          }} 
                          style={{
                            padding: '20px', 
                            borderRadius: '12px',
                            border: isSelected ? '2px solid #88C9C1' : '1px solid rgba(0,0,0,0.06)',
                            background: isSelected ? '#E8F5F3' : '#fff',
                            boxShadow: isSelected ? '0 8px 20px rgba(136,201,193,0.12)' : '0 2px 8px rgba(0,0,0,0.01)',
                            cursor: 'pointer', 
                            display: 'flex', 
                            alignItems: 'center', 
                            justifyContent: 'space-between',
                            transition: 'all 0.3s cubic-bezier(0.22, 1, 0.36, 1)',
                            transform: isSelected ? 'scale(1.01)' : 'scale(1)',
                          }}
                        >
                          <div style={{ flex: 1, paddingRight: 16 }}>
                            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 20, fontWeight: 600, color: '#1a1a1a', marginBottom: 4 }}>
                              {s.name}
                            </div>
                            {s.desc && (
                              <p style={{ fontFamily: "'Outfit', sans-serif", fontSize: 13, color: '#666', marginBottom: 8, lineHeight: 1.4 }}>
                                {s.desc}
                              </p>
                            )}
                            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                              <span style={{ fontFamily: "'Outfit', sans-serif", fontSize: 12, color: '#88C9C1', fontWeight: 500 }}>
                                ⏱ {s.duration}
                              </span>
                              {s.benefits && s.benefits.length > 0 && (
                                <span style={{ fontFamily: "'Outfit', sans-serif", fontSize: 12, color: '#C9A96E', fontWeight: 500 }}>
                                  ✨ {s.benefits.slice(0, 2).join(' · ')}
                                </span>
                              )}
                            </div>
                          </div>
                          <div style={{ fontFamily: "'Outfit', sans-serif", fontSize: 16, fontWeight: 600, color: isSelected ? '#2d6a61' : '#C9A96E', whiteSpace: 'nowrap' }}>
                            {priceFmt(s.price)}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            );
          })}
          
          <div ref={continueBtnRef} style={{ marginTop: 24 }}>
            <button 
              onClick={() => selected.service && setStep(2)} 
              disabled={!selected.service} 
              className="btn-primary-mint"
            >
              Continuar
            </button>
          </div>
        </div>
      );
    }
    if (i === 2) {
      return (
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
            <button 
              onClick={() => setDayOffset(Math.max(0, dayOffset - 7))} 
              disabled={dayOffset === 0} 
              style={{ 
                background: 'none', 
                border: 'none', 
                cursor: dayOffset === 0 ? 'not-allowed' : 'pointer', 
                fontSize: 28, 
                color: dayOffset === 0 ? '#EAEAEA' : '#88C9C1', 
                padding: '0 8px', 
                fontFamily: "'Outfit', sans-serif", 
                transition: 'color 0.2s' 
              }}
            >
              ‹
            </button>
            <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8 }}>
              {visibleDays.map(d => {
                const isSat = d.getDay() === 6;
                const sel = selected.date && d.toDateString() === selected.date.toDateString();
                return (
                  <div 
                    key={d} 
                    onClick={() => setSelected(p => ({...p, date: d, time: null}))} 
                    style={{
                      padding: '16px 4px', 
                      borderRadius: 12,
                      border: sel ? '2px solid #88C9C1' : '1px solid rgba(136,201,193,0.15)',
                      background: sel ? '#E8F5F3' : '#fff',
                      boxShadow: sel ? '0 8px 20px rgba(136,201,193,0.2)' : '0 4px 12px rgba(0,0,0,0.01)',
                      cursor: 'pointer', 
                      textAlign: 'center', 
                      transition: 'all 0.3s cubic-bezier(0.22, 1, 0.36, 1)',
                      transform: sel ? 'translateY(-4px)' : 'none',
                    }}
                  >
                    <div style={{ 
                      fontFamily: "'Outfit', sans-serif", 
                      fontSize: 11, 
                      letterSpacing: 1, 
                      color: sel ? '#2d6a61' : '#88C9C1', 
                      textTransform: 'uppercase', 
                      marginBottom: 8, 
                      fontWeight: 500 
                    }}>
                      {d.toLocaleDateString('es-CL', {weekday: 'short'}).replace('.', '')}
                    </div>
                    <div style={{ 
                      fontFamily: "'Cormorant Garamond', serif", 
                      fontSize: 24, 
                      fontWeight: 500, 
                      color: sel ? '#2d6a61' : '#1a1a1a' 
                    }}>
                      {d.getDate()}
                    </div>
                    {isSat && (
                      <div style={{ 
                        width: 4, 
                        height: 4, 
                        borderRadius: '50%', 
                        background: sel ? '#2d6a61' : '#F4B8C1', 
                        margin: '6px auto 0' 
                      }}/>
                    )}
                  </div>
                );
              })}
            </div>
            <button 
              onClick={() => setDayOffset(Math.min(days.length - 7, dayOffset + 7))} 
              style={{ 
                background: 'none', 
                border: 'none', 
                cursor: 'pointer', 
                fontSize: 28, 
                color: '#88C9C1', 
                padding: '0 8px', 
                fontFamily: "'Outfit', sans-serif", 
                transition: 'color 0.2s' 
              }}
            >
              ›
            </button>
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 32 }}>
            <button onClick={() => setStep(1)} className="btn-secondary-mint" style={{ flex: 1 }}>Volver</button>
            <button 
              onClick={() => selected.date && setStep(3)} 
              disabled={!selected.date} 
              className="btn-primary-mint" 
              style={{ flex: 2 }}
            >
              Continuar
            </button>
          </div>
        </div>
      );
    }
    if (i === 3) {
      return (
        <div>
          <div style={{
            background: '#fff',
            border: '1px solid rgba(136, 201, 193, 0.3)',
            borderRadius: '16px',
            padding: '16px 24px',
            textAlign: 'center',
            marginBottom: '28px',
            boxShadow: '0 4px 12px rgba(136, 201, 193, 0.05)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: '12px'
          }}>
            <span style={{ fontSize: '20px' }}>📅</span>
            <div style={{ textAlign: 'left' }}>
              <span style={{ fontFamily: "'Outfit', sans-serif", fontSize: '11px', color: '#88C9C1', textTransform: 'uppercase', letterSpacing: '1.5px', display: 'block', fontWeight: 600, marginBottom: '2px' }}>Día Seleccionado</span>
              <span style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: '22px', color: '#1a1a1a', fontWeight: 600, fontStyle: 'italic', textTransform: 'capitalize' }}>
                {selected.date && fmtFull(selected.date)}
              </span>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(110px, 1fr))', gap: 12 }}>
            {timesList.map(t => {
              const dateStr = getLocalDateString(selected.date);
              const dateBlocks = specialBlocksList.filter(b => b.date === dateStr).reduce((acc, b) => [...acc, ...b.hours], []);
              const isBlocked = dateBlocks.includes(t);
              const taken = takenTimes.includes(t) || isBlocked;
              const sel = selected.time === t;
              return (
                <div 
                  key={t} 
                  onClick={() => !taken && setSelected(p => ({...p, time: t}))} 
                  style={{
                    padding: '16px 12px', 
                    borderRadius: 12, 
                    textAlign: 'center',
                    border: sel ? '2px solid #88C9C1' : taken ? '1px solid transparent' : '1px solid rgba(136,201,193,0.2)',
                    background: sel ? '#E8F5F3' : taken ? '#F9F9F9' : '#fff',
                    cursor: taken ? 'not-allowed' : 'pointer', 
                    opacity: taken ? 0.4 : 1, 
                    transition: 'all 0.3s cubic-bezier(0.22, 1, 0.36, 1)',
                    transform: sel ? 'scale(1.03)' : 'scale(1)',
                    boxShadow: sel ? '0 8px 24px rgba(136,201,193,0.2)' : 'none'
                  }}
                >
                  <div style={{ 
                    fontFamily: "'Outfit', sans-serif", 
                    fontSize: 18, 
                    fontWeight: 500, 
                    color: sel ? '#2d6a61' : taken ? '#A0A0A0' : '#1a1a1a' 
                  }}>
                    {t}
                  </div>
                  <div style={{ fontFamily: "'Outfit', sans-serif", fontSize: 11, color: sel ? '#2d6a61' : '#A0A0A0', marginTop: 4 }}>
                    {taken ? (isBlocked ? 'No disponible' : 'Ocupado') : 'Disponible'}
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 32 }}>
            <button onClick={() => setStep(2)} className="btn-secondary-mint" style={{ flex: 1 }}>Volver</button>
            <button 
              onClick={() => selected.time && setStep(4)} 
              disabled={!selected.time} 
              className="btn-primary-mint" 
              style={{ flex: 2 }}
            >
              Continuar
            </button>
          </div>
        </div>
      );
    }
    if (i === 4) {
      return (
        <form onSubmit={(e) => { e.preventDefault(); setStep(5); }}>
          <div style={{
            background: 'linear-gradient(135deg, #E8F5F3 0%, #FAFAF8 100%)',
            border: '1px solid rgba(136, 201, 193, 0.25)',
            borderRadius: '16px',
            padding: '20px',
            marginBottom: '28px',
            boxShadow: '0 4px 12px rgba(136, 201, 193, 0.05)'
          }}>
            <div style={{ fontFamily: "'Outfit', sans-serif", fontSize: '11px', color: '#88C9C1', textTransform: 'uppercase', letterSpacing: '1.5px', fontWeight: 600, marginBottom: '8px' }}>Tu cita programada</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
              <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: '20px', color: '#1a1a1a', fontWeight: 600 }}>
                {svc && svc.name}
              </div>
              <div style={{ fontFamily: "'Outfit', sans-serif", fontSize: '14px', color: '#555', display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' }}>
                <span>📅 {selected.date && fmtFull(selected.date)}</span>
                <span style={{ color: '#88C9C1' }}>•</span>
                <span>⏱ {selected.time} hrs</span>
              </div>
            </div>
          </div>
          {[
            ['name', 'Nombre completo', 'text', 'Ej: María González'],
            ['email', 'Correo electrónico', 'email', 'Ej: maria@gmail.com'],
            ['phone', 'Teléfono / WhatsApp', 'tel', 'Ej: +56 9 1234 5678']
          ].map(([field, label, type, ph]) => (
            <div key={field} style={{ marginBottom: 24 }}>
              <label style={{ 
                fontFamily: "'Outfit', sans-serif", 
                fontSize: 12, 
                letterSpacing: 1.5, 
                color: '#88C9C1', 
                textTransform: 'uppercase', 
                display: 'block', 
                marginBottom: 10, 
                fontWeight: 600 
              }}>
                {label}
              </label>
              <input 
                type={type} 
                placeholder={ph} 
                required 
                value={selected[field]}
                onChange={e => setSelected(p => ({...p, [field]: e.target.value}))}
                className="input-mint"
              />
            </div>
          ))}
          <div style={{ display: 'flex', gap: 16, marginTop: 32 }}>
            <button type="button" onClick={() => setStep(3)} className="btn-secondary-mint" style={{ flex: 1 }}>Volver</button>
            <button type="submit" className="btn-primary-mint" style={{ flex: 2 }}>Continuar</button>
          </div>
        </form>
      );
    }
    if (i === 5) {
      return (
        <form onSubmit={handleSubmit}>
          <div style={{ 
            background: '#fff', 
            borderRadius: 16, 
            padding: '32px', 
            boxShadow: '0 8px 32px rgba(0,0,0,0.03)', 
            marginBottom: 24, 
            border: '1px solid rgba(136,201,193,0.3)' 
          }}>
            <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 26, color: '#1a1a1a', marginBottom: 24, textAlign: 'center', fontStyle: 'italic' }}>
              Resumen de Reserva
            </h3>
            {[
              ['Servicio', (svc && svc.name)],
              ['Fecha', selected.date && fmtFull(selected.date)],
              ['Hora', selected.time ? `${selected.time} hrs` : null],
              ['Nombre', selected.name],
              ['Email', selected.email],
              ['Teléfono', selected.phone],
              ['Total', svc && priceFmt(svc.price)],
            ].map(([k, v]) => v && (
              <div key={k} style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                padding: '16px 0', 
                borderBottom: k === 'Total' ? 'none' : '1px solid rgba(136,201,193,0.12)', 
                marginTop: k === 'Total' ? 8 : 0 
              }}>
                <span style={{ fontFamily: "'Outfit', sans-serif", fontSize: 13, color: '#88C9C1', letterSpacing: 1, textTransform: 'uppercase', fontWeight: 500 }}>{k}</span>
                <span style={{ 
                  fontFamily: k === 'Total' ? "'Cormorant Garamond', serif" : "'Outfit', sans-serif", 
                  fontSize: k === 'Total' ? 24 : 15, 
                  color: k === 'Total' ? '#C9A96E' : '#1a1a1a', 
                  fontWeight: k === 'Total' ? 600 : 400 
                }}>{v}</span>
              </div>
            ))}
          </div>

          {error && (
            <div style={{ background: '#FFF5F6', border: '1px solid #F4B8C1', borderRadius: 12, padding: '20px', marginBottom: 24 }}>
              <div style={{ fontFamily: "'Outfit', sans-serif", fontSize: 14, fontWeight: 600, color: '#D64550', marginBottom: 8 }}>
                Error al agendar
              </div>
              <p style={{ fontFamily: "'Outfit', sans-serif", fontSize: 13, color: '#1a1a1a', margin: '0 0 16px', lineHeight: 1.6 }}>
                {error} Puedes agendar manualmente por WhatsApp:
              </p>
              <a 
                href={`https://wa.me/56983059044?text=${encodeURIComponent(
                  `¡Hola Fran! Me gustaría agendar una cita:\n\n🌿 *Servicio:* ${(svc && svc.name)}\n📅 *Fecha:* ${selected.date && selected.date.toLocaleDateString('es-CL', { weekday: 'long', day: 'numeric', month: 'long' })}\n⏱ *Hora:* ${selected.time} hrs\n\n*Mis Datos:*\n👤 *Nombre:* ${selected.name}\n📧 *Email:* ${selected.email}\n📞 *Teléfono:* ${selected.phone}`
                )}`} 
                target="_blank" 
                rel="noopener noreferrer" 
                style={{
                  display: 'inline-flex', 
                  alignItems: 'center', 
                  gap: 10, 
                  textDecoration: 'none',
                  background: '#25D366', 
                  color: '#fff', 
                  border: 'none', 
                  cursor: 'pointer',
                  fontFamily: "'Outfit', sans-serif", 
                  fontSize: 12, 
                  fontWeight: 600, 
                  letterSpacing: 1,
                  padding: '12px 24px', 
                  borderRadius: 40, 
                  boxShadow: '0 4px 20px rgba(37,211,102,0.3)',
                  transition: 'all 0.3s'
                }}
                onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 6px 24px rgba(37,211,102,0.5)'; }}
                onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 4px 20px rgba(37,211,102,0.3)'; }}
              >
                <IconWhatsApp />
                <span>Confirmar por WhatsApp</span>
              </a>
            </div>
          )}

          <div style={{ background: 'rgba(136,201,193,0.1)', borderRadius: 12, padding: '16px', marginBottom: 32, border: '1px solid rgba(136,201,193,0.2)' }}>
            <p style={{ fontFamily: "'Outfit', sans-serif", fontSize: 13, color: '#1a1a1a', margin: 0, lineHeight: 1.6, textAlign: 'center' }}>
              Recibirás una confirmación por email y un recordatorio por WhatsApp 24 horas antes de tu cita.
            </p>
          </div>

          <div style={{ display: 'flex', gap: 16 }}>
            <button type="button" onClick={() => setStep(4)} disabled={submitting} className="btn-secondary-mint" style={{ flex: 1, opacity: submitting ? 0.5 : 1 }}>Volver</button>
            <button 
              type="submit" 
              disabled={submitting} 
              className="btn-primary-mint"
              style={{ flex: 2 }}
            >
              {submitting ? 'Procesando...' : 'Confirmar Cita'}
            </button>
          </div>
        </form>
      );
    }
    if (i === 6) {
      return (
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <div style={{ 
            width: 80, 
            height: 80, 
            borderRadius: '50%', 
            background: '#88C9C1', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center', 
            margin: '0 auto 32px', 
            color: '#fff', 
            fontSize: 36, 
            boxShadow: '0 8px 32px rgba(136,201,193,0.3)' 
          }}>
            ✓
          </div>
          <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 42, fontWeight: 400, fontStyle: 'italic', color: '#1a1a1a', margin: '0 0 16px' }}>
            ¡Tu cita está confirmada!
          </h2>
          <p style={{ fontFamily: "'Outfit', sans-serif", fontSize: 15, color: '#666', lineHeight: 1.7, marginBottom: 8 }}>
            <strong style={{ color: '#1a1a1a', fontWeight: 500 }}>{(svc && svc.name)}</strong><br/>
            {selected.date && fmtFull(selected.date)} · {selected.time} hrs
          </p>
          <p style={{ fontFamily: "'Outfit', sans-serif", fontSize: 14, color: '#666', lineHeight: 1.6, marginBottom: 40, maxWidth: 400, margin: '0 auto 40px' }}>
            Te enviaremos la confirmación a <strong style={{ color: '#1a1a1a', fontWeight: 500 }}>{selected.email}</strong> y recibirás un recordatorio 24 horas antes. ¡Nos vemos pronto!
          </p>
          
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, alignItems: 'center' }}>
            <a 
              href={`https://wa.me/56983059044?text=${encodeURIComponent(
                `¡Hola Fran! Acabo de registrar una cita en la web:\n\n🌿 *Servicio:* ${(svc && svc.name)}\n📅 *Fecha:* ${selected.date && selected.date.toLocaleDateString('es-CL', { weekday: 'long', day: 'numeric', month: 'long' })}\n⏱ *Hora:* ${selected.time} hrs`
              )}`} 
              target="_blank" 
              rel="noopener noreferrer" 
              style={{
                display: 'inline-flex', 
                alignItems: 'center', 
                gap: 10, 
                textDecoration: 'none',
                background: '#25D366', 
                color: '#fff', 
                border: 'none', 
                cursor: 'pointer',
                fontFamily: "'Outfit', sans-serif", 
                fontSize: 13, 
                fontWeight: 600, 
                letterSpacing: 1.5,
                padding: '16px 36px', 
                borderRadius: 40, 
                boxShadow: '0 4px 20px rgba(37,211,102,0.3)',
                transition: 'all 0.3s'
              }}
              onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 24px rgba(37,211,102,0.5)'; }}
              onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '0 4px 20px rgba(37,211,102,0.3)'; }}
            >
              <IconWhatsApp />
              <span>Notificar por WhatsApp</span>
            </a>
            
            <button 
              onClick={() => { 
                setSubmitted(false); 
                setStep(1); 
                setSelected({ service: null, date: null, time: null, name: '', email: '', phone: '' }); 
              }}
              className="btn-secondary-mint"
              style={{ width: 'auto', padding: '14px 28px' }}
            >
              Agendar otra cita
            </button>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div style={{ minHeight: '100vh', background: '#FAFAF8', overflowX: 'hidden' }}>
      <style>{`
        .btn-primary-mint {
          background: linear-gradient(135deg, #88C9C1, #6bb5ac) !important;
          color: #fff !important;
          border: none !important;
          padding: 16px 32px !important;
          border-radius: 50px !important;
          font-family: 'Outfit', sans-serif !important;
          font-size: 14px !important;
          font-weight: 600 !important;
          letter-spacing: 2px !important;
          text-transform: uppercase !important;
          cursor: pointer !important;
          transition: all 0.3s cubic-bezier(0.22, 1, 0.36, 1) !important;
          box-shadow: 0 4px 15px rgba(136, 201, 193, 0.25) !important;
          display: inline-flex !important;
          align-items: center !important;
          justify-content: center !important;
          gap: 8px !important;
          width: 100% !important;
          text-decoration: none !important;
        }
        .btn-primary-mint:hover:not(:disabled) {
          transform: translateY(-3px) !important;
          box-shadow: 0 8px 24px rgba(136, 201, 193, 0.45) !important;
          filter: brightness(1.05) !important;
        }
        .btn-primary-mint:active:not(:disabled) {
          transform: translateY(-1px) !important;
          box-shadow: 0 4px 12px rgba(136, 201, 193, 0.3) !important;
        }
        .btn-primary-mint:disabled {
          background: #E5E5E5 !important;
          color: #A0A0A0 !important;
          cursor: not-allowed !important;
          box-shadow: none !important;
          transform: none !important;
        }

        .btn-secondary-mint {
          background: transparent !important;
          color: #88C9C1 !important;
          border: 2px solid #88C9C1 !important;
          padding: 14px 30px !important;
          border-radius: 50px !important;
          font-family: 'Outfit', sans-serif !important;
          font-size: 14px !important;
          font-weight: 600 !important;
          letter-spacing: 2px !important;
          text-transform: uppercase !important;
          cursor: pointer !important;
          transition: all 0.3s cubic-bezier(0.22, 1, 0.36, 1) !important;
          display: inline-flex !important;
          align-items: center !important;
          justify-content: center !important;
          width: 100% !important;
        }
        .btn-secondary-mint:hover {
          background: rgba(136, 201, 193, 0.08) !important;
          transform: translateY(-2px) !important;
        }
        .btn-secondary-mint:active {
          transform: translateY(0) !important;
        }

        .input-mint {
          width: 100% !important;
          padding: 16px 20px !important;
          border-radius: 12px !important;
          border: 1px solid rgba(136, 201, 193, 0.3) !important;
          font-family: 'Outfit', sans-serif !important;
          font-size: 15px !important;
          color: #1a1a1a !important;
          background: #fff !important;
          outline: none !important;
          box-sizing: border-box !important;
          transition: all 0.3s cubic-bezier(0.22, 1, 0.36, 1) !important;
        }
        .input-mint:focus {
          border-color: #88C9C1 !important;
          box-shadow: 0 0 0 4px rgba(136, 201, 193, 0.15) !important;
        }
      `}</style>
      
      {/* ─── Hero Header ───────────────────────────────────── */}
      <div style={{
        background: 'linear-gradient(135deg, #E8F5F3 0%, #FAFAF8 60%, #FCE8EC 100%)',
        padding: '80px 24px 48px',
        textAlign: 'center',
        borderBottom: '1px solid rgba(136,201,193,0.15)',
        position: 'relative',
        overflow: 'hidden'
      }}>
        {/* Background decorative elements */}
        <div style={{
          position: 'absolute',
          top: '-10%',
          right: '-5%',
          width: '200px',
          height: '200px',
          borderRadius: '50%',
          background: 'rgba(244,184,193,0.15)',
          filter: 'blur(40px)',
          pointerEvents: 'none'
        }} />
        <div style={{
          position: 'absolute',
          bottom: '-10%',
          left: '-5%',
          width: '250px',
          height: '250px',
          borderRadius: '50%',
          background: 'rgba(136,201,193,0.15)',
          filter: 'blur(50px)',
          pointerEvents: 'none'
        }} />
        
        <span style={{
          display: 'inline-block',
          background: 'rgba(136, 201, 193, 0.12)',
          color: '#2d6a61',
          padding: '6px 16px',
          borderRadius: '20px',
          fontFamily: "'Outfit', sans-serif",
          fontSize: '12px',
          fontWeight: 700,
          letterSpacing: '2px',
          textTransform: 'uppercase',
          marginBottom: '16px'
        }}>Reserva Online</span>
        
        <h1 style={{
          fontFamily: "'Cormorant Garamond', serif",
          fontSize: '48px',
          fontWeight: 400,
          fontStyle: 'italic',
          color: '#1a1a1a',
          margin: '0 0 12px',
          lineHeight: 1.2
        }}>Agenda tu Cita</h1>
        
        <p style={{
          fontFamily: "'Outfit', sans-serif",
          fontSize: '16px',
          color: '#666',
          margin: '0 auto',
          maxWidth: '480px',
          fontWeight: 300,
          lineHeight: 1.6
        }}>
          Regálate un momento de bienestar y desconexión. Selecciona tu tratamiento preferido y reserva de forma inmediata.
        </p>
      </div>

      {/* ─── Multi-step Container ────────────────────────────── */}
      <div style={{ maxWidth: 640, margin: '0 auto', padding: '40px 24px 80px' }}>
        {displayStep < 6 && (
          <div style={{ marginBottom: 48 }}>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 16 }}>
              {[1, 2, 3, 4, 5].map(i => (
                <div key={i} style={{ 
                  height: 3, 
                  flex: 1, 
                  maxWidth: 40,
                  background: i <= step ? '#88C9C1' : 'rgba(136,201,193,0.2)',
                  transition: 'background 0.4s ease',
                  borderRadius: 2
                }} />
              ))}
            </div>
            <div style={{ 
              textAlign: 'center', 
              fontFamily: "'Outfit', sans-serif", 
              fontSize: 12, 
              textTransform: 'uppercase', 
              letterSpacing: 2, 
              color: '#88C9C1', 
              fontWeight: 600 
            }}>
              Paso {step}: {stepLabels[step-1]}
            </div>
          </div>
        )}

        <div style={{ position: 'relative', width: '100%' }}>
          {[1, 2, 3, 4, 5, 6].map(i => {
            const isPast = i < displayStep;
            const isActive = i === displayStep;

            return (
              <div key={i} style={{
                position: isActive ? 'relative' : 'absolute',
                top: 0, left: 0, width: '100%',
                transform: `translateX(${isActive ? '0px' : isPast ? '-40px' : '40px'})`,
                opacity: isActive ? 1 : 0,
                pointerEvents: isActive ? 'auto' : 'none',
                visibility: isActive ? 'visible' : 'hidden',
                transition: 'transform 400ms cubic-bezier(0.25, 1, 0.5, 1), opacity 400ms cubic-bezier(0.25, 1, 0.5, 1), visibility 400ms',
                zIndex: isActive ? 2 : 1
              }}>
                {renderStep(i)}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Agenda });
