// Päikeseraja talu — Booking modal

function BookingModal({ t, lang, onClose, range, nights, accomTotal }) {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    barrel: false,
    name: '', email: '', phone: '',
    people: 8,
    contactLang: lang,
    notes: '',
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const barrelTotal = form.barrel ? 50 * nights : 0;
  const total = accomTotal + barrelTotal;
  const deposit = 50;
  const remainder = total - deposit;

  const canStep2 = form.name.trim() && form.email.trim() && form.phone.trim();

  // Until Swedbank LinkPay is wired up, the "Pay" button creates the
  // calendar event directly. Move this call to the payment-success webhook
  // once LinkPay exists.
  const submit = async () => {
    setSubmitting(true);
    setSubmitError(null);
    try {
      const res = await fetch('/api/booking', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          from: range.from,
          to: range.to,
          name: form.name,
          email: form.email,
          phone: form.phone,
          people: form.people,
          contactLang: form.contactLang,
          notes: form.notes,
          barrel: form.barrel,
        }),
      });
      if (!res.ok) {
        const detail = await res.text();
        throw new Error(`${res.status} ${detail}`);
      }
      setStep(4);
    } catch (e) {
      setSubmitError(String(e.message || e));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="close">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" width="14" height="14"><path d="M5 5 L19 19 M19 5 L5 19" /></svg>
        </button>

        {step < 4 && (
          <div className="modal-header">
            <div className="eyebrow">{t.booking.eyebrow}</div>
            <h2 className="serif">
              {step === 3 ? <>{t.pay.title[0]} <em>{t.pay.title[1]}</em></> : <>{t.form.title[0]} <em>{t.form.title[1]}</em></>}
            </h2>
            <div className="modal-steps">
              <div className={`modal-step ${step >= 1 ? (step > 1 ? 'done' : 'active') : ''}`}>
                <span className="num">1</span>{t.form.step1}
              </div>
              <div className={`modal-step ${step >= 2 ? (step > 2 ? 'done' : 'active') : ''}`}>
                <span className="num">2</span>{t.form.step2}
              </div>
              <div className={`modal-step ${step >= 3 ? 'active' : ''}`}>
                <span className="num">3</span>{t.form.step3}
              </div>
            </div>
          </div>
        )}

        <div className="modal-body">
          {step === 1 && (
            <>
              <div className="field-row" style={{ marginBottom: 18 }}>
                <div className="field">
                  <label>{t.form.datesFrom}</label>
                  <input type="text" value={range.from || ''} readOnly />
                </div>
                <div className="field">
                  <label>{t.form.datesTo}</label>
                  <input type="text" value={range.to || ''} readOnly />
                </div>
              </div>

              <label className={`checkbox-card ${form.barrel ? 'checked' : ''}`}>
                <input type="checkbox" checked={form.barrel} onChange={(e) => set('barrel', e.target.checked)} />
                <div className="cc-body">
                  <h5>{t.form.addBarrel.h}</h5>
                  <p>{t.form.addBarrel.p}</p>
                </div>
                <div className="cc-price">{t.form.addBarrel.price}</div>
              </label>

              <div className="field">
                <label>{t.form.people}</label>
                <select value={form.people} onChange={(e) => set('people', +e.target.value)}>
                  {[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20].map((n) => (
                    <option key={n} value={n}>{n}</option>
                  ))}
                </select>
              </div>

              <div className="modal-actions">
                <button className="btn-back" onClick={onClose}>{t.form.back}</button>
                <button className="btn-next" onClick={() => setStep(2)}>{t.form.next.replace(/payment|makseni|оплате/i, '→')}</button>
              </div>
            </>
          )}

          {step === 2 && (
            <>
              <div className="field-row">
                <div className="field">
                  <label>{t.form.name}</label>
                  <input type="text" value={form.name} onChange={(e) => set('name', e.target.value)} />
                </div>
                <div className="field">
                  <label>{t.form.phone}</label>
                  <input type="tel" value={form.phone} onChange={(e) => set('phone', e.target.value)} />
                </div>
              </div>
              <div className="field">
                <label>{t.form.email}</label>
                <input type="email" value={form.email} onChange={(e) => set('email', e.target.value)} />
              </div>

              <div className="field">
                <label>{t.form.lang} <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ink-soft)', fontSize: 11, fontWeight: 400 }}>{t.form.langHint}</span></label>
                <div className="lang-pills">
                  {t.form.langs.map((L) => (
                    <button
                      key={L.code}
                      className={`lang-pill ${form.contactLang === L.code ? 'active' : ''}`}
                      onClick={() => set('contactLang', L.code)}
                      type="button"
                    >
                      {L.label}<span className="note">{L.note}</span>
                    </button>
                  ))}
                </div>
              </div>

              <div className="field">
                <label>{t.form.notes}</label>
                <textarea rows="3" value={form.notes} onChange={(e) => set('notes', e.target.value)} placeholder={t.form.notesPh}></textarea>
              </div>

              <div className="modal-actions">
                <button className="btn-back" onClick={() => setStep(1)}>← {t.form.back}</button>
                <button className="btn-next" disabled={!canStep2} onClick={() => setStep(3)}>{t.form.next}</button>
              </div>
            </>
          )}

          {step === 3 && (
            <>
              <p style={{ color: 'var(--ink-soft)', marginTop: 0, fontSize: 14 }}>{t.pay.sub}</p>
              <div className="pay-summary">
                <div className="pay-row"><span>{t.pay.rowAccom} ({nights} {t.booking.sideNights})</span><span>{accomTotal} €</span></div>
                {form.barrel && <div className="pay-row"><span>{t.pay.rowBarrel} ({nights} × 50)</span><span>{barrelTotal} €</span></div>}
                <div className="pay-row"><span>{t.pay.rowPeople}</span><span>{form.people}</span></div>
                <div className="pay-row total"><span>{t.pay.rowTotal}</span><span>{deposit} €</span></div>
                <div className="pay-row" style={{ color: 'var(--ink-soft)', fontSize: 12 }}><span>{t.pay.rowRest}</span><span>{remainder} €</span></div>
              </div>

              <div className="swed">
                <div className="swed-logo">S</div>
                <div>
                  <h5>{t.pay.swedTitle}</h5>
                  <p>{t.pay.swedSub}</p>
                </div>
              </div>

              <button className="btn-pay" onClick={submit} disabled={submitting}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 12 H19 M13 6 L19 12 L13 18" /></svg>
                {submitting ? '…' : t.pay.payCta}
              </button>
              {submitError && (
                <div style={{ color: '#b54040', fontSize: 13, marginTop: 10 }}>
                  {submitError}
                </div>
              )}

              <div className="modal-actions">
                <button className="btn-back" onClick={() => setStep(2)}>← {t.form.back}</button>
              </div>
            </>
          )}

          {step === 4 && (
            <div className="success-body">
              <div className="success-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12 L10 17 L19 7" /></svg>
              </div>
              <h3>{t.success.title}</h3>
              <p>{t.success.sub}</p>
              <button className="btn-next" onClick={onClose}>{t.success.close}</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
