// Multi-step booking flow
const SERVICES = [
  { id: 'masazas60', name: 'Veido masažas', meta: '60 min', price: '70 €' },
  { id: 'masazas90', name: 'Veido masažas', meta: '90 min', price: '100 €' },
  { id: 'osteo', name: 'OsteoEstetika seansas', meta: '60 min · pilna diagnostika + korekcija', price: '100 €' },
  { id: 'osteo_pratimai', name: 'OsteoEstetika + pratimai', meta: '60 min · su individualiu pratimų rinkiniu', price: '130 €' }
];

const DAYS = ['Pr','An','Tr','Kt','Pn','Št','Sk'];
const MONTH_NAME = 'Gegužė 2026';

const buildCalendar = () => {
  const startOffset = 4; // Pr=0
  const daysInMonth = 31;
  const cells = [];
  for (let i = 0; i < startOffset; i++) cells.push({ disabled: true, key: `e${i}` });
  const today = 5;
  for (let d = 1; d <= daysInMonth; d++) {
    const dayOfWeek = (startOffset + d - 1) % 7; // 0=Pr
    const isSunday = dayOfWeek === 6;
    const past = d < today;
    cells.push({
      day: d,
      disabled: past || isSunday,
      available: !past && !isSunday,
      key: `d${d}`
    });
  }
  return cells;
};

const SLOTS = ['10:00', '11:30', '13:00', '14:30', '16:00', '17:30'];

const Booking = ({ open, onClose, prefill = 'masazas60' }) => {
  const [step, setStep] = useState(0);
  const [service, setService] = useState(prefill);
  const [date, setDate] = useState(null);
  const [slot, setSlot] = useState(null);
  const [form, setForm] = useState({ name: '', email: '', phone: '', notes: '' });
  const calendar = useMemo(buildCalendar, []);
  const takenSlots = useMemo(() => {
    const t = [];
    if (!date) return t;
    const seed = date % 6;
    if (seed === 0) t.push('10:00', '14:30');
    if (seed === 1) t.push('11:30');
    if (seed === 2) t.push('13:00', '17:30');
    if (seed === 3) t.push('16:00');
    if (seed === 4) t.push('10:00', '11:30', '16:00');
    if (seed === 5) t.push('14:30');
    return t;
  }, [date]);

  useEffect(() => { if (open) { setStep(0); setService(prefill); setDate(null); setSlot(null); } }, [open, prefill]);

  if (!open) return null;

  const selectedService = SERVICES.find(s => s.id === service);
  const canAdvance = {
    0: !!service,
    1: !!date && !!slot,
    2: form.name && form.email
  };

  const next = () => { if (canAdvance[step]) setStep(step + 1); };
  const back = () => setStep(Math.max(0, step - 1));

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(46,52,36,.85)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
      padding: '40px 20px', overflowY: 'auto',
      backdropFilter: 'blur(4px)'
    }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        background: 'var(--apricot)', color: 'var(--forest)',
        width: '100%', maxWidth: 880,
        padding: 0, position: 'relative'
      }}>
        <button onClick={onClose} style={{
          position:'absolute', top: 16, right: 16, zIndex: 2,
          width: 40, height: 40, fontSize: 22, color: 'var(--forest-60)'
        }}>×</button>

        <div style={{padding: '56px 56px 40px'}}>
          {step < 3 && (
            <>
              <div className="booking-steps">
                <div className={`step ${step === 0 ? 'active' : step > 0 ? 'done' : ''}`}></div>
                <div className={`step ${step === 1 ? 'active' : step > 1 ? 'done' : ''}`}></div>
                <div className={`step ${step === 2 ? 'active' : step > 2 ? 'done' : ''}`}></div>
              </div>
              <div className="booking-step-title">
                <div>
                  <div className="label" style={{color:'var(--forest-60)', marginBottom: 8}}>
                    {step + 1} žingsnis iš 3
                  </div>
                  <h3>
                    {step === 0 && 'Pasirinkite paslaugą'}
                    {step === 1 && 'Pasirinkite laiką'}
                    {step === 2 && 'Jūsų duomenys'}
                  </h3>
                </div>
              </div>
            </>
          )}

          {step === 0 && (
            <div className="service-grid">
              {SERVICES.map(s => (
                <button key={s.id}
                  className={`service-opt ${service === s.id ? 'active' : ''}`}
                  onClick={()=>setService(s.id)}>
                  <div className="s-meta">{s.meta}</div>
                  <div className="s-name">{s.name}</div>
                  <div className="s-price">{s.price}</div>
                </button>
              ))}
            </div>
          )}

          {step === 1 && (
            <div>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 20}}>
                <div className="heading" style={{fontSize: 22}}>{MONTH_NAME}</div>
                <div className="label" style={{color:'var(--forest-60)'}}>Pr–Št · 10—19</div>
              </div>
              <div className="cal-label-row">
                {DAYS.map(d => <div key={d}>{d}</div>)}
              </div>
              <div className="cal-grid">
                {calendar.map(c => (
                  c.disabled
                    ? <div key={c.key} className="cal-day disabled">{c.day || ''}</div>
                    : <button key={c.key}
                        className={`cal-day available ${date === c.day ? 'selected' : ''}`}
                        onClick={()=>{ setDate(c.day); setSlot(null); }}>{c.day}</button>
                ))}
              </div>
              {date && (
                <>
                  <div className="label" style={{marginTop: 28, color:'var(--forest-60)'}}>
                    Laisvi laikai · gegužės {date} d.
                  </div>
                  <div className="slot-grid">
                    {SLOTS.map(s => {
                      const taken = takenSlots.includes(s);
                      return (
                        <button key={s}
                          className={`slot ${slot === s ? 'selected' : ''} ${taken ? 'taken' : ''}`}
                          disabled={taken}
                          onClick={()=>!taken && setSlot(s)}>{s}</button>
                      );
                    })}
                  </div>
                </>
              )}
            </div>
          )}

          {step === 2 && (
            <div>
              <div className="form-field">
                <label>Vardas ir pavardė</label>
                <input value={form.name} onChange={e=>setForm({...form, name:e.target.value})} placeholder="Vardas Pavardė" />
              </div>
              <div className="form-field">
                <label>El. paštas</label>
                <input type="email" value={form.email} onChange={e=>setForm({...form, email:e.target.value})} placeholder="jusu@paštas.lt" />
              </div>
              <div className="form-field">
                <label>Telefonas (nebūtina)</label>
                <input value={form.phone} onChange={e=>setForm({...form, phone:e.target.value})} placeholder="+370" />
              </div>
              <div className="form-field">
                <label>Ką norėtumėte, kad žinočiau iš anksto</label>
                <textarea value={form.notes} onChange={e=>setForm({...form, notes:e.target.value})} placeholder="Įtampa žandikaulyje, skausmai, neseniai atliktos procedūros…" />
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="booking-confirm">
              <div className="check"><Icon name="check" size={28} /></div>
              <h3>Užregistruota.</h3>
              <p>Patvirtinimas keliauja el. paštu adresu <strong style={{color:'var(--forest)'}}>{form.email}</strong>. Prieš seansą atsiųsiu trumpą anketą.</p>
              <div className="details">
                <div><strong>{selectedService.name}</strong></div>
                <div>Gegužės {date} d. · {slot} · Kęstučio g. 51, Kaunas</div>
              </div>
              <div>
                <button className="btn btn-ghost-light" onClick={onClose}>Uždaryti</button>
              </div>
            </div>
          )}

          {step < 3 && (
            <div className="booking-nav">
              <div className="summary">
                {service && <span>{selectedService.name}</span>}
                {date && <span> · gegužės {date} d.</span>}
                {slot && <span> · <strong>{slot}</strong></span>}
              </div>
              <div style={{display:'flex', gap: 10}}>
                {step > 0 && <button className="btn btn-ghost-light" onClick={back}>Atgal</button>}
                <button className="btn btn-sage"
                  onClick={next}
                  disabled={!canAdvance[step]}
                  style={{opacity: canAdvance[step] ? 1 : .4, cursor: canAdvance[step] ? 'pointer' : 'not-allowed'}}>
                  {step === 2 ? 'Patvirtinti registraciją' : 'Toliau'} <Icon name="arrow" size={14} />
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const BookingCta = ({ onBook }) => (
  <section className="section booking" id="book">
    <div className="container">
      <Reveal>
        <div style={{textAlign: 'center', maxWidth: 780, margin: '0 auto'}}>
          <div className="label" style={{color:'var(--warm-peach)', marginBottom: 24, display:'flex', justifyContent:'center', alignItems:'center', gap:14}}>
            <span style={{width:28, height:1, background:'var(--warm-peach)', display:'inline-block'}}></span>
            <span>Registracija</span>
            <span style={{width:28, height:1, background:'var(--warm-peach)', display:'inline-block'}}></span>
          </div>
          <h2 className="display" style={{fontSize: 'clamp(44px, 6vw, 84px)', color:'var(--apricot)', margin: '0 0 28px'}}>
            Tikras grožis <em style={{fontStyle:'italic', color:'var(--warm-peach)'}}>prasideda čia.</em>
          </h2>
          <p style={{color:'var(--soft-peach)', opacity:.82, fontSize: 18, maxWidth: 540, margin: '0 auto 40px'}}>
            Ten, kur prasideda sveikai funkcionuojantis kūnas. Užsiregistruokite seansui — susisieksiu ir padėsiu išsirinkti tinkamiausią paslaugą.
          </p>
          <div style={{display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap'}}>
            <button className="btn btn-sage" onClick={()=>onBook('osteo')}>Registruotis seansui <Icon name="arrow" size={14}/></button>
            <a className="btn btn-ghost-dark" href="https://wa.me/37067253955" target="_blank" rel="noopener noreferrer">Rašyti per WhatsApp</a>
          </div>
          <div style={{marginTop: 40, display:'flex', gap: 24, justifyContent:'center', flexWrap:'wrap', fontSize: 11, letterSpacing: '.2em', textTransform:'uppercase', color:'var(--soft-peach)', opacity:.6}}>
            <span>Kęstučio g. 51, Kaunas</span>
            <span>·</span>
            <span>10:00 — 19:00</span>
            <span>·</span>
            <span>+370 672 53955</span>
          </div>
        </div>
      </Reveal>
    </div>
  </section>
);

Object.assign(window, { Booking, BookingCta });
