/* ============ CONTACT & BOOKING ============ */
function Field({ label, children }) {
  return (
    <label className="field">
      <span className="field-l">{label}</span>
      {children}
    </label>
  );
}

function Contact({ selectedRoom }) {
  const S = window.SITE;
  const roomNames = { garden: "Garden View Suite", skydeck: "Skydeck Lounge Access", cabin: "Work & Stay Cabin" };
  const [form, setForm] = useState({ name: "", email: "", phone: "", checkin: "", checkout: "", room: "Mixed Dormitory", guests: "1", message: "" });
  const [errors, setErrors] = useState({});
  const [toast, setToast] = useState(false);

  useEffect(() => {
    if (selectedRoom && roomNames[selectedRoom]) {
      setForm((f) => ({ ...f, room: roomNames[selectedRoom] }));
    }
  }, [selectedRoom]);


  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const validate = () => {
    const er = {};
    if (!form.name.trim()) er.name = "Tell us your name";
    if (!/^\S+@\S+\.\S+$/.test(form.email)) er.email = "Valid email please";
    if (!/^[\d+\s()-]{7,}$/.test(form.phone)) er.phone = "Valid phone please";
    if (!form.checkin) er.checkin = "Pick a date";
    if (!form.checkout) er.checkout = "Pick a date";
    setErrors(er);
    return Object.keys(er).length === 0;
  };

  const submit = (e) => {
    e.preventDefault();
    if (!validate()) return;
    const msg =
`Hello, I would like to book a stay at The Last Stop Backpackers Hostel & Skydeck Cafe.

Please share room availability and pricing.

Name: ${form.name}
Phone: ${form.phone}
Check-In: ${form.checkin}
Check-Out: ${form.checkout}
Room Type: ${form.room}
Guests: ${form.guests}${form.message ? `\nMessage: ${form.message}` : ""}`;
    window.open(`https://wa.me/${S.contact.whatsapp}?text=${encodeURIComponent(msg)}`, "_blank");
    setToast(true);
    setTimeout(() => setToast(false), 5000);
  };

  const mapSrc = "https://www.openstreetmap.org/export/embed.html?bbox=79.80%2C11.99%2C79.84%2C12.02&layer=mapnik&marker=12.003,79.822";

  return (
    <section id="contact" className="section bg-alt contact">
      <div className="container contact-grid">
        <div className="contact-info">
          <Eyebrow>Reserve your bunk</Eyebrow>
          <Reveal as="h2" className="display contact-title">Let&rsquo;s get you <em className="muted-em">to Auroville.</em></Reveal>
          <Reveal as="p" className="contact-lead" delay={100}>
            Fill in the form and we&rsquo;ll continue on WhatsApp with live availability and the best rate.
            Prefer to talk? Call or email — we&rsquo;re happy to help plan your Auroville stay.
          </Reveal>

          <div className="contact-rows">
            <a className="crow" href={`tel:${S.contact.phone.replace(/\s/g, "")}`}>
              <span className="crow-ic"><Icon name="phone" /></span>
              <div><strong>Call us</strong><span>{S.contact.phone}</span></div>
            </a>
            <a className="crow" href={`mailto:${S.contact.email}`}>
              <span className="crow-ic"><Icon name="envelope" /></span>
              <div><strong>Email</strong><span>{S.contact.email}</span></div>
            </a>
            <div className="crow">
              <span className="crow-ic"><Icon name="location-dot" /></span>
              <div><strong>Find us</strong><span>{S.contact.address}</span></div>
            </div>
          </div>

          <Reveal className="map-wrap" delay={120}>
            <iframe title="Map to The Last Stop, Auroville" src={mapSrc} loading="lazy" />
            <div className="map-pin glass"><Icon name="mountain-sun" /> {S.location}</div>
          </Reveal>
        </div>

        <Reveal className="booking glass" delay={120}>
          <h3 className="serif booking-title">Booking enquiry</h3>
          <form onSubmit={submit} noValidate>
            <div className="frow">
              <Field label="Full name">
                <input value={form.name} onChange={set("name")} placeholder="Jamie Rivers" className={errors.name ? "err" : ""} />
                {errors.name && <em className="ferr">{errors.name}</em>}
              </Field>
            </div>
            <div className="frow two">
              <Field label="Email">
                <input type="email" value={form.email} onChange={set("email")} placeholder="you@email.com" className={errors.email ? "err" : ""} />
                {errors.email && <em className="ferr">{errors.email}</em>}
              </Field>
              <Field label="Phone">
                <input value={form.phone} onChange={set("phone")} placeholder="+91 …" className={errors.phone ? "err" : ""} />
                {errors.phone && <em className="ferr">{errors.phone}</em>}
              </Field>
            </div>
            <div className="frow two">
              <Field label="Check-in">
                <input type="date" value={form.checkin} onChange={set("checkin")} className={errors.checkin ? "err" : ""} />
                {errors.checkin && <em className="ferr">{errors.checkin}</em>}
              </Field>
              <Field label="Check-out">
                <input type="date" value={form.checkout} onChange={set("checkout")} className={errors.checkout ? "err" : ""} />
                {errors.checkout && <em className="ferr">{errors.checkout}</em>}
              </Field>
            </div>
            <div className="frow two">
              <Field label="Room type">
                <select value={form.room} onChange={set("room")}>
                  <option>Garden View Suite</option>
                  <option>Skydeck Lounge Access</option>
                  <option>Work &amp; Stay Cabin</option>
                </select>
              </Field>
              <Field label="Guests">
                <select value={form.guests} onChange={set("guests")}>
                  {[1,2,3,4,5,6].map((n) => <option key={n}>{n}</option>)}
                </select>
              </Field>
            </div>
            <div className="frow">
              <Field label="Message (optional)">
                <textarea rows="3" value={form.message} onChange={set("message")} placeholder="Arriving late, travelling with friends, dietary needs…" />
              </Field>
            </div>
            <button type="submit" className="btn btn-wa booking-submit"><Icon name="whatsapp" /> Send on WhatsApp</button>
            <p className="booking-note">We reply within a few hours. WhatsApp is fastest.</p>
          </form>
        </Reveal>
      </div>

      <div className={`toast ${toast ? "show" : ""}`} role="status">
        <Icon name="circle-check" className="toast-ok" />
        <div><strong>Enquiry ready!</strong><span>We&rsquo;ve opened WhatsApp with your details prefilled.</span></div>
        <button onClick={() => setToast(false)} aria-label="Dismiss"><Icon name="xmark" /></button>
      </div>

      <style>{`
        .contact-grid { display: grid; grid-template-columns: 1fr 1.05fr; gap: clamp(36px, 5vw, 64px); align-items: start; }
        .contact-title { font-size: clamp(2rem, 4.4vw, 3.3rem); margin-top: 16px; }
        .contact-lead { color: var(--text-2); margin-top: 20px; max-width: 44ch; }
        .contact-rows { display: flex; flex-direction: column; gap: 14px; margin-top: 32px; }
        .crow { display: flex; align-items: center; gap: 16px; }
        .crow-ic { width: 46px; height: 46px; border-radius: 12px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: color-mix(in srgb, var(--primary) 13%, transparent); color: var(--primary); font-size: 16px; }
        html[data-theme="dark"] a.crow:hover .crow-ic { box-shadow: 0 0 20px -4px var(--glow); }
        .crow strong { display: block; font-size: 14px; color: var(--text); }
        .crow span { font-size: 13.5px; color: var(--text-2); }

        .map-wrap { position: relative; margin-top: 28px; border-radius: var(--r-md); overflow: hidden; border: 1px solid var(--border); height: 220px; }
        .map-wrap iframe { width: 100%; height: 100%; border: 0; filter: saturate(.95); }
        html[data-theme="dark"] .map-wrap iframe { filter: invert(.9) hue-rotate(180deg) saturate(.7) brightness(.95); }
        .map-pin { position: absolute; top: 12px; left: 12px; font-size: 12px; font-weight: 600; color: var(--text); padding: 8px 13px; border-radius: 99px; display: inline-flex; gap: 8px; align-items: center; }
        .map-pin .ic { color: var(--accent); }

        .booking { border-radius: var(--r-lg); padding: clamp(26px, 4vw, 40px); box-shadow: var(--shadow); }
        .booking-title { font-size: 1.8rem; margin-bottom: 22px; }
        .frow { margin-bottom: 16px; }
        .frow.two { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .field { display: flex; flex-direction: column; gap: 7px; }
        .field-l { font-size: 12.5px; font-weight: 600; color: var(--text-2); letter-spacing: .02em; }
        .field input, .field select, .field textarea {
          font-family: var(--sans); font-size: 14.5px; color: var(--text); background: var(--surface-2);
          border: 1px solid var(--border); border-radius: var(--r-sm); padding: 12px 14px; width: 100%; transition: border-color .25s, box-shadow .25s;
        }
        .field textarea { resize: vertical; }
        .field input:focus, .field select:focus, .field textarea:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px var(--glow); }
        .field input.err, .field select.err { border-color: #e0563f; }
        .ferr { font-size: 11.5px; color: #e0563f; font-style: normal; }
        .booking-submit { width: 100%; justify-content: center; margin-top: 6px; padding: 15px; }
        .booking-note { text-align: center; font-size: 12px; color: var(--text-3); margin-top: 12px; }

        .toast {
          position: fixed; bottom: 24px; left: 50%; transform: translate(-50%, 140%); z-index: 1200;
          display: flex; align-items: center; gap: 14px; background: var(--surface-2); border: 1px solid var(--border);
          padding: 14px 18px; border-radius: var(--r-md); box-shadow: var(--shadow); max-width: 92vw; transition: transform .5s var(--ease);
        }
        .toast.show { transform: translate(-50%, 0); }
        .toast > .toast-ok { font-size: 24px; color: #25D366; }
        .toast strong { display: block; font-size: 14px; color: var(--text); }
        .toast span { font-size: 13px; color: var(--text-2); }
        .toast button { color: var(--text-3); font-size: 16px; padding: 4px; }

        @media (max-width: 880px) { .contact-grid { grid-template-columns: 1fr; } }
        @media (max-width: 480px) { .frow.two { grid-template-columns: 1fr; } }
      `}</style>
    </section>
  );
}

Object.assign(window, { Contact });
