
// ABLY — Quiz Logic & Component
const YACHTS = [
  { id: 'yamaha28', name: 'Yamaha 28 ft', type: 'Small boat', cap: 8, baseGuests: [1,6], price: 300, extraHr: 85, extraGuest: 45 },
  { id: 'fsail42', name: 'French Sail Boat 42 ft', type: 'Sail boat', cap: 12, baseGuests: [1,6], price: 750, extraHr: 213, extraGuest: 80 },
  { id: 'bayliner35', name: 'Bayliner 35 ft', type: 'Yacht', cap: 8, baseGuests: [1,6], price: 950, extraHr: 269, extraGuest: 80 },
  { id: 'cruiser37', name: 'Cruiser 37 ft', type: 'Yacht', cap: 8, baseGuests: [1,6], price: 1050, extraHr: 298, extraGuest: 80 },
  { id: 'searay45', name: 'Sea Ray 45 ft', type: 'Yacht', cap: 14, baseGuests: [1,8], price: 1500, extraHr: 425, extraGuest: 80 },
  { id: 'azimut46', name: 'Azimut 46 ft', type: 'Luxury yacht', cap: 16, baseGuests: [1,10], price: 1850, extraHr: 524, extraGuest: 90 },
  { id: 'cat47', name: 'Catamaran 47 ft', type: 'Catamaran', cap: 40, baseGuests: [1,14], price: 1900, extraHr: 538, extraGuest: 80 },
  { id: 'leopard52', name: 'Catamaran Leopard 52 ft', type: 'Luxury catamaran', cap: 35, baseGuests: [1,14], price: 2200, extraHr: 623, extraGuest: 90 },
  { id: 'sunseeker60', name: 'Sunseeker 60 ft', type: 'Luxury yacht', cap: 22, baseGuests: [1,10], price: 2350, extraHr: 783, extraGuest: 90 },
  { id: 'azimut68', name: 'Azimut 68 ft', type: 'Luxury yacht', cap: 20, baseGuests: [1,10], price: 3350, extraHr: 1117, extraGuest: 90 },
  { id: 'sunseeker80', name: 'Sunseeker 80 ft', type: 'Ultra luxury yacht', cap: 30, baseGuests: [1,10], price: 5400, extraHr: 1800, extraGuest: 170 },
];

// Assumed number of hours covered by a yacht's base `price`. Change this if the
// base rate ever stops being a 3-hour charter.
const BASE_CHARTER_HOURS = 3;

const STEPS = [
  {
    key: 'occasion',
    label: 'Occasion',
    title: 'What kind of experience do you have in mind?',
    help: 'This helps us shape the vibe — from a quiet sunset to a full celebration.',
    options: ['Sunset & relaxation', 'Birthday or celebration', 'Bachelor / bachelorette party', 'Family day out', 'Romantic escape or proposal', 'Party with friends'],
  },
  {
    key: 'guests',
    label: 'Group',
    title: 'How many guests will be joining you?',
    help: "We'll size the right yacht for your group.",
    options: ['1–6 guests', '7–10 guests', '11–14 guests', '15–25 guests', '26+ guests'],
  },
  {
    key: 'timing',
    label: 'Date',
    title: 'When would you like to set sail?',
    help: 'Even an approximate date helps us check availability.',
    options: ['I have an exact date', 'Within the next 2 weeks', 'Later this month', 'In 1–3 months', 'Just exploring for now'],
    dateReveal: 'I have an exact date',
  },
  {
    key: 'duration',
    label: 'Duration',
    title: 'How long would you like to be on the water?',
    help: 'Most experiences run from 3 hours to a full day.',
    options: ['3 hours', '4–5 hours', '6+ hours / full day', "Not sure — I'd like a recommendation"],
  },
  {
    key: 'budget',
    label: 'Budget',
    title: 'What budget range feels right for you?',
    help: 'A ballpark is perfect — it helps us match the ideal yacht, not upsell you.',
    options: ['Under $750', '$750 – $1,500', '$1,500 – $2,500', '$2,500 – $4,000', '$4,000+', 'Show me options across ranges'],
  },
  {
    key: 'extras',
    label: 'Extras',
    title: "Anything you'd like to add?",
    help: 'Pick whatever appeals — you can adjust all of this later.',
    options: ['Private chef', 'Premium bar & champagne', 'Decorations', 'Drone & photo package', 'Water toys (snorkel, paddleboards)', 'Private hotel transport (round-trip)', 'Music / DJ', 'Not sure yet'],
    multi: true,
  },
];

// ---- Recommendation engine -------------------------------------------------
const GROUP_MIN_CAP = {
  '1–6 guests': 6,
  '7–10 guests': 10,
  '11–14 guests': 14,
  '15–25 guests': 25,
  '26+ guests': 26,
};

const BUDGET_CEILING = {
  'Under $750': 750,
  '$750 – $1,500': 1500,
  '$1,500 – $2,500': 2500,
  '$2,500 – $4,000': 4000,
  '$4,000+': Infinity,
  'Show me options across ranges': null,
};

const DURATION_EXTRA_HOURS = {
  '3 hours': 0,
  '4–5 hours': 2,
  '6+ hours / full day': 4,
  "Not sure — I'd like a recommendation": 0,
};

const isVipType = (type) => /luxury|ultra/i.test(type || '');

function estimateFrom(boat, duration) {
  const extraHours = DURATION_EXTRA_HOURS[duration] || 0;
  return boat.price + boat.extraHr * extraHours;
}

function recommend(answers) {
  const { guests, budget, duration } = answers;

  // a) capacity filter
  const minCap = GROUP_MIN_CAP[guests] || 1;
  const fitting = YACHTS
    .filter((y) => y.cap >= minCap)
    .sort((a, b) => a.price - b.price);

  if (fitting.length === 0) return { recommended: null, upgrade: null };

  // b) budget → recommended
  const ceiling = budget in BUDGET_CEILING ? BUDGET_CEILING[budget] : Infinity;
  let recommended;
  if (ceiling === null) {
    // no budget signal → mid-priced fitting boat
    recommended = fitting[Math.floor((fitting.length - 1) / 2)];
  } else {
    const underCeiling = fitting.filter((y) => y.price <= ceiling);
    recommended = underCeiling.length
      ? underCeiling[underCeiling.length - 1] // highest-priced that fits the ceiling
      : fitting[0]; // nothing fits → cheapest fitting boat (closest option)
  }

  // c) upgrade = next more premium fitting boat above the recommended
  const upgrade = fitting.find((y) => y.price > recommended.price) || null;

  const toCard = (boat) => boat && {
    name: boat.name,
    type: boat.type,
    price: estimateFrom(boat, duration),
    isVip: isVipType(boat.type),
  };

  return { recommended: toCard(recommended), upgrade: toCard(upgrade) };
}

// ---- Component -------------------------------------------------------------
const QuizModal = ({ open, onClose }) => {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({ occasion: null, guests: null, timing: null, duration: null, budget: null, extras: [] });
  const [exactDate, setExactDate] = React.useState('');
  const [phase, setPhase] = React.useState('question'); // question | result | contact | done
  const [contact, setContact] = React.useState({ name: '', whatsapp: '', email: '', staying: '', date: '', notes: '' });
  // Privacy consent — legally required to start unchecked; gates the contact submit
  const [consent, setConsent] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setStep(0);
      setAnswers({ occasion: null, guests: null, timing: null, duration: null, budget: null, extras: [] });
      setExactDate('');
      setPhase('question');
      setContact({ name: '', whatsapp: '', email: '', staying: '', date: '', notes: '' });
      setConsent(false);
    }
  }, [open]);

  if (!open) return null;

  const current = STEPS[step];
  const totalSteps = STEPS.length + 1; // 6 questions + contact (result is not counted)
  const currentIndex = phase === 'question' ? step : phase === 'contact' ? STEPS.length : STEPS.length - 1;

  const advance = () => {
    if (step < STEPS.length - 1) setStep(step + 1);
    else setPhase('result');
  };

  const selectAnswer = (val) => {
    if (current.multi) {
      const arr = answers[current.key] || [];
      const next = arr.includes(val) ? arr.filter((v) => v !== val) : [...arr, val];
      setAnswers({ ...answers, [current.key]: next });
    } else if (current.dateReveal) {
      // single-select but no auto-advance: user may need to pick a date
      setAnswers({ ...answers, [current.key]: val });
      if (val !== current.dateReveal) setExactDate('');
    } else {
      setAnswers({ ...answers, [current.key]: val });
      setTimeout(advance, 220);
    }
  };

  let canNext;
  if (current?.multi) {
    canNext = (answers[current.key] || []).length > 0;
  } else if (current?.dateReveal) {
    const picked = answers[current.key];
    canNext = !!picked && (picked !== current.dateReveal || !!exactDate);
  } else {
    canNext = !!answers[current?.key];
  }

  const rec = recommend(answers);

  const formatDate = (iso) => {
    if (!iso) return '';
    const d = new Date(iso + 'T00:00:00');
    if (isNaN(d)) return iso;
    return d.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });
  };

  // Build a fully prefilled WhatsApp message from all collected state.
  const buildQuizMessage = () => {
    const dateLine = exactDate ? formatDate(exactDate) : answers.timing;
    const recLine = rec.recommended
      ? `${rec.recommended.name} (from $${rec.recommended.price.toLocaleString()})`
      : '';
    const lines = [
      'Hi ABLY! I just completed the quiz — here\'s my request:',
      contact.name && `• Name: ${contact.name}`,
      answers.occasion && `• Occasion: ${answers.occasion}`,
      answers.guests && `• Group: ${answers.guests}`,
      dateLine && `• Date: ${dateLine}`,
      answers.duration && `• Duration: ${answers.duration}`,
      answers.budget && `• Budget: ${answers.budget}`,
      (answers.extras && answers.extras.length) && `• Extras: ${answers.extras.join(', ')}`,
      contact.staying && `• Staying at: ${contact.staying}`,
      contact.notes && `• Notes: ${contact.notes}`,
      recLine && `• Recommended: ${recLine}`,
    ].filter(Boolean);
    return lines.join('\n');
  };

  const sendWhatsApp = () => {
    const msg = buildQuizMessage();
    window.openWhatsApp(msg && msg.trim() ? msg : window.WA_MESSAGES.quiz);
  };

  // Envía el lead al backend (D1 + email) sin bloquear el flujo de WhatsApp.
  // Si el backend falla, el quiz continúa igual (fire-and-forget con catch).
  const submitLead = () => {
    const payload = {
      contact,
      answers: { ...answers, ...(exactDate ? { timing: exactDate } : {}) },
      recommended: rec.recommended
        ? `${rec.recommended.name} (from $${rec.recommended.price.toLocaleString()})`
        : null,
    };
    fetch('/api/lead', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }).catch(() => {});
    if (typeof gtag === 'function') {
      gtag('event', 'generate_lead', { recommended_package: payload.recommended || 'none' });
    }
  };

  const handleNext = () => {
    if (phase === 'question') {
      advance();
    } else if (phase === 'result') {
      // carry the Q3 exact date into the contact form if present
      if (exactDate && !contact.date) setContact((c) => ({ ...c, date: exactDate }));
      setPhase('contact');
    } else if (phase === 'contact') {
      submitLead();   // guarda en D1 + email al operador
      sendWhatsApp(); // se mantiene el flujo de WhatsApp existente
      setPhase('done');
    }
  };

  const handleBack = () => {
    if (phase === 'contact') setPhase('result');
    else if (phase === 'result') { setPhase('question'); setStep(STEPS.length - 1); }
    else if (step > 0) setStep(step - 1);
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="quiz-modal-header">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div>
              <div style={{ fontFamily: 'Manrope', fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>
                Find your perfect yacht
              </div>
              <div style={{ fontSize: 12, color: 'var(--graphite-soft)', marginTop: 2 }}>
                No pressure — just a quick recommendation.
              </div>
            </div>
            <button onClick={onClose} style={{ color: 'var(--graphite-soft)', padding: 4 }} aria-label="Close">
              <Icon name="close" size={20} />
            </button>
          </div>
          <div className="quiz-progress">
            {Array.from({ length: totalSteps }).map((_, i) => (
              <div key={i} className={i === currentIndex ? 'active' : i < currentIndex ? 'done' : ''} />
            ))}
          </div>
          <div className="quiz-step-label">
            <span>{phase === 'result' ? 'Your recommendation' : `Step ${currentIndex + 1} of ${totalSteps}`}</span>
            <span>{phase === 'question' ? current.label : phase === 'result' ? 'Recommendation' : phase === 'contact' ? 'Contact' : 'Done'}</span>
          </div>
        </div>

        <div className="quiz-body">
          {phase === 'question' && (
            <>
              <h3>{current.title}</h3>
              <p className="quiz-help">{current.help}</p>
              <div className="quiz-options">
                {current.options.map((opt) => {
                  const sel = current.multi ? (answers[current.key] || []).includes(opt) : answers[current.key] === opt;
                  return (
                    <React.Fragment key={opt}>
                      <button className={`quiz-option ${sel ? 'selected' : ''}`} onClick={() => selectAnswer(opt)}>
                        <span>{opt}</span>
                        <span className="check">
                          {sel && <Icon name="check" size={14} stroke={2.5} />}
                        </span>
                      </button>
                      {current.dateReveal && sel && opt === current.dateReveal && (
                        <div className="quiz-input-row" style={{ marginTop: 2, marginBottom: 4 }}>
                          <label>Pick your date</label>
                          <input
                            className="quiz-input"
                            type="date"
                            value={exactDate}
                            onChange={(e) => setExactDate(e.target.value)}
                          />
                        </div>
                      )}
                    </React.Fragment>
                  );
                })}
              </div>
            </>
          )}

          {phase === 'result' && (
            <>
              <div style={{ fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--marine)', fontWeight: 600 }}>
                Your recommended experience
              </div>
              <h3 style={{ marginTop: 6 }}>Here's the perfect match for your day</h3>
              <p className="quiz-help">Based on your answers, we'd suggest:</p>

              {rec.recommended && (
                <div className="result-card recommended">
                  <div className={`result-img ${rec.recommended.isVip ? 'vip' : ''}`} />
                  <div className="result-info">
                    <div className={`rec-tag ${rec.recommended.isVip ? 'vip-tag' : ''}`}>Recommended</div>
                    <h4>{rec.recommended.name}</h4>
                    <div style={{ fontSize: 13, color: 'var(--graphite-soft)', marginTop: 2 }}>{rec.recommended.type}</div>
                    <div className="rec-price">From ${rec.recommended.price.toLocaleString()}</div>
                  </div>
                </div>
              )}

              {rec.upgrade && (
                <div style={{ marginTop: 12 }}>
                  <div className="result-card">
                    <div className={`result-img ${rec.upgrade.isVip ? 'vip' : ''}`} />
                    <div className="result-info">
                      <div className={`rec-tag ${rec.upgrade.isVip ? 'vip-tag' : ''}`}>Worth the upgrade</div>
                      <h4>{rec.upgrade.name}</h4>
                      <div style={{ fontSize: 13, color: 'var(--graphite-soft)', marginTop: 2 }}>{rec.upgrade.type}</div>
                      <div className="rec-price">From ${rec.upgrade.price.toLocaleString()}</div>
                    </div>
                  </div>
                </div>
              )}

              <div style={{ marginTop: 20, padding: 16, background: 'rgba(14,116,144,0.06)', borderRadius: 12, fontSize: 13, color: 'var(--graphite-soft)' }}>
                Share your details and your concierge will confirm availability, exact pricing, and the best yacht options for your date.
              </div>
            </>
          )}

          {phase === 'contact' && (
            <>
              <h3>Where should we send your quote?</h3>
              <p className="quiz-help">Your concierge will reach out personally with availability and a tailored proposal.</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div className="quiz-input-row">
                  <label>Name</label>
                  <input className="quiz-input" placeholder="Your name" value={contact.name} onChange={(e) => setContact({ ...contact, name: e.target.value })} />
                </div>
                <div className="quiz-input-row">
                  <label>WhatsApp number</label>
                  <input className="quiz-input" placeholder="+52 …" value={contact.whatsapp} onChange={(e) => setContact({ ...contact, whatsapp: e.target.value })} />
                </div>
                <div className="quiz-input-row">
                  <label>Email <span className="opt">(optional)</span></label>
                  <input className="quiz-input" placeholder="you@email.com" value={contact.email} onChange={(e) => setContact({ ...contact, email: e.target.value })} />
                </div>
                <div className="quiz-input-row">
                  <label>Where are you staying? <span className="opt">(optional)</span></label>
                  <input className="quiz-input" placeholder="Hotel or area in Cabo" value={contact.staying} onChange={(e) => setContact({ ...contact, staying: e.target.value })} />
                  <div style={{ fontSize: 11, color: 'var(--graphite-soft)', marginTop: -2 }}>So we can arrange transport if you'd like.</div>
                </div>
                <div className="quiz-input-row">
                  <label>Preferred date <span className="opt">(optional)</span></label>
                  <input className="quiz-input" type="date" value={contact.date} onChange={(e) => setContact({ ...contact, date: e.target.value })} />
                </div>
                <div className="quiz-input-row">
                  <label>Anything special about your day? <span className="opt">(optional)</span></label>
                  <textarea className="quiz-input" rows={3} placeholder="Tell us how to make it perfect" value={contact.notes} onChange={(e) => setContact({ ...contact, notes: e.target.value })} />
                </div>
                <label className="quiz-consent">
                  <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} />
                  <span>I have read and accept the <a href="privacy.html" target="_blank" rel="noopener">Privacy Notice</a> for handling my reservation details.</span>
                </label>
              </div>
            </>
          )}

          {phase === 'done' && (
            <div style={{ textAlign: 'center', padding: '20px 0 10px' }}>
              <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(14,116,144,0.1)', color: 'var(--marine)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
                <Icon name="check" size={28} stroke={2.5} />
              </div>
              <h3 style={{ marginBottom: 6 }}>Your concierge is on it.</h3>
              <p style={{ fontSize: 14, color: 'var(--graphite-soft)', maxWidth: 380, margin: '0 auto' }}>
                We've got everything we need. Expect a personalized quote on WhatsApp shortly — usually within a couple of hours.
              </p>
              <div style={{ display: 'flex', justifyContent: 'center', gap: 10, marginTop: 24 }}>
                <button className="btn btn-wa" onClick={sendWhatsApp}>
                  <Icon name="wa" size={16} />
                  Continue on WhatsApp
                </button>
              </div>
            </div>
          )}
        </div>

        {phase !== 'done' && (
          <div className="quiz-footer">
            <button className="quiz-back" onClick={handleBack} disabled={phase === 'question' && step === 0} style={{ opacity: (phase === 'question' && step === 0) ? 0.4 : 1 }}>
              <Icon name="arrowLeft" size={14} /> Back
            </button>
            {phase === 'result' ? (
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
                <button className="btn btn-secondary btn-sm" onClick={handleNext}>
                  Get my full quote
                </button>
                <button className="btn btn-wa btn-sm" onClick={sendWhatsApp}>
                  <Icon name="wa" size={14} />
                  Check availability on WhatsApp
                </button>
              </div>
            ) : phase === 'contact' ? (
              <div style={{ display: 'flex', gap: 8 }}>
                <button className="btn btn-wa btn-sm" onClick={sendWhatsApp} disabled={!consent} style={{ opacity: consent ? 1 : 0.5 }}>
                  <Icon name="wa" size={14} />
                  WhatsApp
                </button>
                <button className="btn btn-primary" onClick={handleNext} disabled={!contact.name || !contact.whatsapp || !consent}>
                  Send my request
                </button>
              </div>
            ) : (
              <button className="btn btn-primary btn-sm" onClick={handleNext} disabled={!canNext} style={{ opacity: canNext ? 1 : 0.5 }}>
                Continue <Icon name="arrowRight" size={14} />
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

window.QuizModal = QuizModal;
