// === Seven Yachts — Overlays (drawer, modal, FAB) ===

function FavouritesDrawer({ open, onClose, favs, toggleFav, onSelect, openBooking }) {
  if (!open) return null;
  const items = favs.map(findYacht).filter(Boolean);

  const enquireAll = () => {
    if (items.length === 0) return;
    const list = items.map(y => `• ${y.name} — ${y.builder} ${y.length}ft`).join('%0A');
    const msg = `Hello Seven Yachts, I have a shortlist:%0A${list}%0A%0APlease share availability for ...`;
    window.open(`https://wa.me/971521217833?text=${msg}`, '_blank');
  };

  return (
    <>
      <div className="drawer-backdrop" onClick={onClose}></div>
      <aside className="drawer" role="dialog" aria-label="Favourites">
        <div className="drawer-head">
          <div>
            <div className="eyebrow">Shortlist</div>
            <h3>Favourites {items.length > 0 && <span style={{ fontFamily: 'var(--mono)', fontSize: 14, color: 'var(--muted)', marginLeft: 6 }}>· {items.length}</span>}</h3>
          </div>
          <button className="drawer-close" onClick={onClose} aria-label="Close">
            <Icon name="x" size={20} />
          </button>
        </div>
        <div className="drawer-body">
          {items.length === 0 ? (
            <div className="fav-empty">
              <Icon name="heart" size={48} />
              <h4 style={{ fontFamily: 'var(--display)', fontSize: 24, margin: 0, fontWeight: 400 }}>No yachts saved yet.</h4>
              <p style={{ color: 'var(--muted)', fontSize: 14, maxWidth: '30ch' }}>
                Tap the heart on any yacht to build a shortlist — then enquire about all of them in one WhatsApp message.
              </p>
              <button className="btn btn-ghost-dark" onClick={() => { onClose(); }} style={{ marginTop: 12 }}>Browse the fleet</button>
            </div>
          ) : (
            items.map(y => (
              <div className="fav-row" key={y.slug}>
                <img src={y.hero} alt={y.name} />
                <div onClick={() => { onClose(); onSelect(y.slug); }} style={{ cursor: 'pointer' }}>
                  <div className="fav-name">{y.name}</div>
                  <div className="fav-meta">{y.builder.toUpperCase()} · {y.length}FT {y.cruisingGuests ? `· UP TO ${y.cruisingGuests}` : ''}</div>
                </div>
                <button className="fav-remove" onClick={() => toggleFav(y.slug)} aria-label="Remove">
                  <Icon name="x" size={16} />
                </button>
              </div>
            ))
          )}
        </div>
        {items.length > 0 && (
          <div className="drawer-foot">
            <button className="btn btn-wa" style={{ flex: 1 }} onClick={enquireAll}>
              <Icon name="whatsapp" size={16} /> Enquire about all
            </button>
            <button className="btn btn-ghost-dark" onClick={() => { onClose(); openBooking({ shortlist: favs }); }}>Send brief</button>
          </div>
        )}
      </aside>
    </>
  );
}
window.FavouritesDrawer = FavouritesDrawer;


function BookingModal({ open, onClose, prefill }) {
  if (!open) return null;
  const [step, setStep] = useState('form'); // form | success
  const [data, setData] = useState({
    yacht: prefill?.yacht || 'any',
    date: prefill?.date || new Date(Date.now() + 7 * 86400000).toISOString().slice(0, 10),
    guests: prefill?.guests || 8,
    duration: prefill?.duration || '4hr',
    name: '',
    phone: '',
    email: '',
    occasion: 'general',
    message: '',
  });

  const yacht = data.yacht === 'any' ? null : findYacht(data.yacht);
  const heroImg = yacht ? yacht.hero : 'media/lucien-exterior.webp';

  const handle = (e) => {
    e.preventDefault();
    setStep('success');
  };

  const waNow = () => {
    const yLine = yacht ? `${yacht.name} (${yacht.builder} ${yacht.length}ft)` : 'recommendation';
    const occ = data.occasion !== 'general' ? `Occasion: ${data.occasion}.` : '';
    const msg = `Hello Seven Yachts, I'd like to enquire about ${yLine} on ${data.date} for ${data.guests} guests (${data.duration}). ${occ} ${data.message || ''}`.trim();
    window.open(waLink(msg), '_blank');
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <Icon name="x" size={18} />
        </button>
        {step === 'form' ? (
          <>
            <div className="modal-img">
              <img src={heroImg} alt={yacht ? yacht.name : 'Seven Yachts'} />
              <div className="modal-img-text">
                <div className="eyebrow">Check Availability</div>
                <h3>{yacht ? yacht.name : 'Tell us the date.'}</h3>
                <p style={{ fontStyle: 'italic', fontFamily: 'var(--display)', fontSize: 16, color: 'var(--gold)', margin: 0 }}>
                  {yacht ? `${yacht.builder} · ${yacht.length}ft` : "We'll suggest the right vessel."}
                </p>
                <p style={{ marginTop: 20, fontSize: 13, opacity: 0.9, maxWidth: '32ch' }}>
                  Every enquiry is hand-replied by the concierge desk — usually within the hour, in your preferred language.
                </p>
              </div>
            </div>
            <form className="modal-form" onSubmit={handle}>
              <div className="eyebrow">Concierge Enquiry</div>
              <div className="form-row">
                <label>Yacht</label>
                <select value={data.yacht} onChange={e => setData({ ...data, yacht: e.target.value })}>
                  <option value="any">Any yacht — recommend me</option>
                  {FLEET.map(y => <option key={y.slug} value={y.slug}>{y.name} · {y.builder} {y.length}ft</option>)}
                </select>
              </div>
              <div className="form-grid2">
                <div className="form-row">
                  <label>Date</label>
                  <input type="date" value={data.date} onChange={e => setData({ ...data, date: e.target.value })} />
                </div>
                <div className="form-row">
                  <label>Duration</label>
                  <select value={data.duration} onChange={e => setData({ ...data, duration: e.target.value })}>
                    <option value="3hr">3 hours</option>
                    <option value="4hr">4 hours</option>
                    <option value="6hr">6 hours</option>
                    <option value="day">Full day</option>
                    <option value="overnight">Overnight</option>
                    <option value="multi">Multi-day</option>
                  </select>
                </div>
              </div>
              <div className="form-grid2">
                <div className="form-row">
                  <label>Guests</label>
                  <select value={data.guests} onChange={e => setData({ ...data, guests: +e.target.value })}>
                    {[2,4,6,8,10,12,15,20,25,30,40].map(n => <option key={n} value={n}>{n} guests</option>)}
                  </select>
                </div>
                <div className="form-row">
                  <label>Occasion</label>
                  <select value={data.occasion} onChange={e => setData({ ...data, occasion: e.target.value })}>
                    <option value="general">General charter</option>
                    <option value="celebration">Celebration / birthday</option>
                    <option value="dining">Gourmet dining</option>
                    <option value="cinema">Floating cinema</option>
                    <option value="corporate">Corporate / events</option>
                    <option value="wellness">Wellness</option>
                    <option value="proposal">Proposal</option>
                  </select>
                </div>
              </div>
              <div className="form-row">
                <label>Your name</label>
                <input type="text" required value={data.name} onChange={e => setData({ ...data, name: e.target.value })} placeholder="Full name" />
              </div>
              <div className="form-grid2">
                <div className="form-row">
                  <label>Phone / WhatsApp</label>
                  <input type="tel" required value={data.phone} onChange={e => setData({ ...data, phone: e.target.value })} placeholder="+971 ..." />
                </div>
                <div className="form-row">
                  <label>Email</label>
                  <input type="email" value={data.email} onChange={e => setData({ ...data, email: e.target.value })} placeholder="optional" />
                </div>
              </div>
              <div className="form-row">
                <label>Anything else?</label>
                <textarea value={data.message} onChange={e => setData({ ...data, message: e.target.value })} placeholder="Allergies, languages, music, route preferences..." />
              </div>
              <div className="modal-foot">
                <button type="submit" className="btn btn-primary" style={{ flex: 1 }}>Send Enquiry</button>
                <button type="button" className="btn btn-wa" onClick={waNow}>
                  <Icon name="whatsapp" size={14} /> Send on WhatsApp
                </button>
              </div>
              <p style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--muted)', letterSpacing: '0.1em', marginTop: 4 }}>
                BY SUBMITTING YOU AGREE TO OUR PRIVACY NOTICE · NO INVENTORY HOLD UNTIL CONCIERGE CONFIRMATION
              </p>
            </form>
          </>
        ) : (
          <div className="success" style={{ gridColumn: '1 / -1' }}>
            <Icon name="check" size={56} />
            <div className="eyebrow">Sent</div>
            <h3>Enquiry received.</h3>
            <p style={{ color: 'var(--muted)', maxWidth: '40ch' }}>
              {data.name && `Thank you, ${data.name.split(' ')[0]}. `}
              Our concierge will respond within the hour by your preferred channel. For an immediate answer, message us on WhatsApp.
            </p>
            <div style={{ display: 'flex', gap: 10, marginTop: 16, flexWrap: 'wrap', justifyContent: 'center' }}>
              <button className="btn btn-wa" onClick={waNow}>
                <Icon name="whatsapp" size={14} /> Open WhatsApp
              </button>
              <button className="btn btn-ghost-dark" onClick={onClose}>Close</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
window.BookingModal = BookingModal;


function WhatsAppFab() {
  return (
    <a className="fab" href={waLink()} target="_blank" rel="noopener" aria-label="WhatsApp">
      <Icon name="whatsapp" size={28} />
    </a>
  );
}
window.WhatsAppFab = WhatsAppFab;


function FavouritesFab({ count, onClick }) {
  if (count === 0) return null;
  return (
    <button className="fav-fab" onClick={onClick} aria-label={`${count} favourites`}>
      <Icon name="heart-fill" size={20} />
      <span className="count">{count}</span>
    </button>
  );
}
window.FavouritesFab = FavouritesFab;
