/* global React */
const { useState: useStateI, useEffect: useEffectI } = React;

// ===== FAQ =====
function FAQ() {
  const [open, setOpen] = useStateI(0);
  const items = [
  ['Can I bring a plus-one?',
  "We'd love to keep things intimate. If your invitation lists a plus-one, you'll see their name on the RSVP. Please ask us if you're unsure!"],
  ['What time should I arrive?',
  "Please arrive by 1:30 PM for seating. The ceremony begins at 2:00 PM, and we'd hate for you to miss the procession."],
  ['Will it be outdoors?',
  "Yes and no — the ceremony will be held indoors at the Kidapawan City Seventh-day Adventist Church, while the reception will be held outdoors at The Cascades by Amador."],
  ['What about parking?',
  "Parking is available at both the church and the reception venue."],
  ['Is there a gift registry?',
  "Your presence is the only present we need. If you'd like to give a gift, an envelope at the reception is most welcome — we're saving for a home of our own."]];


  return (
    <section className="snap" id="faq" data-screen-label="09 FAQ">
      <div className="section-head">
        <span className="num">VIII.</span>
        <span className="label">Questions</span>
        <span className="rule" />
      </div>
      <h2 className="section-title">A few things <em>worth knowing</em> in advance.</h2>
      <div className="faq-list">
        {items.map(([q, a], i) =>
        <div key={i} className={`faq-item ${open === i ? 'open' : ''}`}>
            <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
              <span>{q}</span><span className="plus">+</span>
            </button>
            <div className="faq-a">{a}</div>
          </div>
        )}
      </div>
    </section>);

}

// ===== RSVP (multi-step) =====
function RSVP() {
  const [step, setStep] = useStateI(0);
  const [data, setData] = useStateI({
    name: '', email: '',
    attending: null,
    guests: [{ name: '' }]
  });
  const [errors, setErrors] = useStateI({});
  const [submitting, setSubmitting] = useStateI(false);
  const [submitError, setSubmitError] = useStateI('');

  const RSVP_ENDPOINT = 'https://script.google.com/macros/s/AKfycbw9tRkrQ1ExPl2mwl_GgRAXcvjw9V53uKnn9ABQzwEd9AqsyekITomv1f1hF3ptyZuUkw/exec';

  async function submitRSVP() {
    setSubmitError('');
    setSubmitting(true);
    const guestNames = data.attending === 'yes' ?
    data.guests.map((g) => g.name.trim()).filter(Boolean) : [];
    const payload = {
      name: data.name.trim(),
      email: data.email.trim(),
      attendance: data.attending === 'yes' ? 'Attending' : 'Not attending',
      // First companion goes in guestName; any beyond that go in additionalGuests.
      guestName: guestNames[0] || '',
      additionalGuests: guestNames.slice(1)
    };
    try {
      const res = await fetch(RSVP_ENDPOINT, {
        method: 'POST',
        // text/plain keeps this a "simple" request so the browser skips the
        // CORS preflight that Apps Script web apps don't answer; the body is
        // still JSON for the script to parse server-side.
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify(payload),
        redirect: 'follow'
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setSubmitting(false);
      setStep(3);
    } catch (err) {
      setSubmitting(false);
      setSubmitError("We couldn't send your reply just now. Please check your connection and try again.");
    }
  }

  function set(k, v) {setData((d) => ({ ...d, [k]: v }));}
  function setGuest(i, k, v) {
    setData((d) => ({
      ...d,
      guests: d.guests.map((g, gi) => gi === i ? { ...g, [k]: v } : g)
    }));
  }
  function addGuest() {setData((d) => ({ ...d, guests: [...d.guests, { name: '' }] }));}
  function removeGuest(i) {setData((d) => ({ ...d, guests: d.guests.filter((_, gi) => gi !== i) }));}

  function next() {
    const e = {};
    if (step === 0) {
      if (!data.name.trim()) e.name = 'Required';
      if (!data.email.includes('@')) e.email = 'Valid email';
    }
    if (step === 1 && data.attending === null) e.attending = 'Pick one';
    if (step === 2 && data.attending === 'yes') {
      data.guests.forEach((g, i) => {
        if (!g.name.trim()) e[`g${i}`] = 'Name required';
      });
    }
    setErrors(e);
    if (Object.keys(e).length === 0) {
      setSubmitError('');
      // A decline submits straight from step 1; an acceptance submits from
      // step 2 (after collecting guests). Both paths POST before showing "Done".
      if (data.attending === 'no' && step === 1) {
        submitRSVP();
      } else if (step === 2) {
        submitRSVP();
      } else {
        setStep((s) => s + 1);
      }
    }
  }
  function back() {setStep((s) => Math.max(0, s - 1));}

  const steps = ['You', 'Attending', 'Guests', 'Done'];

  return (
    <section className="snap" id="rsvp" data-screen-label="10 RSVP">
      <div className="section-head">
        <span className="num">IX.</span>
        <span className="label">Kindly Reply</span>
        <span className="rule" />
      </div>
      <h2 className="section-title">Please let us know <em>by June 12, 2026</em>.</h2>
      <div className="rsvp-card">
        <div className="steps-rail">
          {steps.map((s, i) =>
          <div key={s} className={`step-pip ${i < step ? 'done' : ''} ${i === step ? 'active' : ''}`}>
              <span><b className="pip-n">{String(i + 1).padStart(2, '0')}</b><i className="pip-l"> · {s}</i></span>
            </div>
          )}
        </div>

        {step === 0 &&
        <div>
            <div className={`field ${errors.name ? 'error' : ''}`}>
              <label className="field-label">Your name</label>
              <input value={data.name} onChange={(e) => set('name', e.target.value)} placeholder="Maria Santos" />
              {errors.name && <div className="err">{errors.name}</div>}
            </div>
            <div className={`field ${errors.email ? 'error' : ''}`}>
              <label className="field-label">Email — for any updates</label>
              <input type="email" value={data.email} onChange={(e) => set('email', e.target.value)} placeholder="maria@example.com" />
              {errors.email && <div className="err">{errors.email}</div>}
            </div>
            <div className="btn-row">
              <span />
              <button className="btn-primary" onClick={next}>Continue →</button>
            </div>
          </div>
        }

        {step === 1 &&
        <div>
            <label className="field-label" style={{ marginBottom: 12 }}>Will you be joining us?</label>
            <div className="radio-row">
              <div className={`radio-tile ${data.attending === 'yes' ? 'selected' : ''}`} onClick={() => set('attending', 'yes')}>
                <div className="rt-title">Joyfully accept</div>
                <div className="rt-sub">I wouldn't miss it</div>
              </div>
              <div className={`radio-tile ${data.attending === 'no' ? 'selected' : ''}`} onClick={() => set('attending', 'no')}>
                <div className="rt-title">Regretfully decline</div>
                <div className="rt-sub">Sending love from afar</div>
              </div>
            </div>
            {errors.attending && <div className="err" style={{ marginTop: 8 }}>{errors.attending}</div>}
            {submitError && <div className="err" style={{ marginTop: 8 }}>{submitError}</div>}
            <div className="btn-row">
              <button className="btn-ghost" onClick={back} disabled={submitting}>← Back</button>
              <button className="btn-primary" onClick={next} disabled={submitting}>
                {submitting && data.attending === 'no' ? 'Sending…' : 'Continue →'}
              </button>
            </div>
          </div>
        }

        {step === 2 && data.attending === 'yes' &&
        <div>
            <label className="field-label" style={{ marginBottom: 12 }}>Who's coming with you?</label>
            {data.guests.map((g, i) =>
          <div key={i} className="guest-row">
                <div className={`field ${errors[`g${i}`] ? 'error' : ''}`} style={{ margin: 0 }}>
                  <label className="field-label">Guest {i + 1} name</label>
                  <input value={g.name} onChange={(e) => setGuest(i, 'name', e.target.value)} placeholder="Full name" />
                </div>
                {data.guests.length > 1 &&
            <button className="remove" onClick={() => removeGuest(i)}>Remove</button>
            }
              </div>
          )}
            <button className="add-guest" onClick={addGuest}>+ Add another guest</button>
            {submitError && <div className="err" style={{ marginTop: 16 }}>{submitError}</div>}
            <div className="btn-row" style={{ marginTop: 24 }}>
              <button className="btn-ghost" onClick={back} disabled={submitting}>← Back</button>
              <button className="btn-primary" onClick={next} disabled={submitting}>
                {submitting ? 'Sending…' : 'Send reply →'}
              </button>
            </div>
          </div>
        }

        {step === 3 &&
        <div className="success-card">
            <div className="seal">{data.attending === 'yes' ? '♥' : '✦'}</div>
            <h3>{data.attending === 'yes' ? 'See you in June.' : 'You will be missed.'}</h3>
            <p style={{ fontStyle: 'italic', fontSize: 19 }}>
              Thank you, {data.name.split(' ')[0]}. {data.attending === 'yes' ?
            `We've saved a seat for ${data.guests.length} — and noted everything.` :
            "Thank you for letting us know. We'll raise a glass for you."}
            </p>
            <p style={{ marginTop: 18 }}>A confirmation will follow with the final details.</p>
            <button className="btn-ghost" style={{ marginTop: 24 }} onClick={() => {setStep(0);setSubmitError('');setData({ name: '', email: '', attending: null, guests: [{ name: '' }] });}}>
              Reply for someone else
            </button>
          </div>
        }
      </div>
    </section>);

}

// ===== PLAYLIST =====
function Playlist() {
  const [title, setTitle] = useStateI('');
  const [artist, setArtist] = useStateI('');
  const [name, setName] = useStateI('');
  const [list, setList] = useStateI(() => {
    try {return JSON.parse(localStorage.getItem('jc-dj-playlist') || '[]') || seed;}
    catch {return seed;}
  });
  const seed = [
  { t: 'At Last', a: 'Etta James', by: 'Mom' },
  { t: "Can't Help Falling in Love", a: 'Elvis Presley', by: 'Tito Bong' },
  { t: 'September', a: 'Earth, Wind & Fire', by: 'Aira' },
  { t: 'Pag-ibig na Kaya', a: 'Ben&Ben', by: 'Mika' }];

  useEffectI(() => {
    if (list.length === 0) setList(seed);
  }, []);
  useEffectI(() => {
    try {localStorage.setItem('jc-dj-playlist', JSON.stringify(list));} catch {}
  }, [list]);

  function add() {
    if (!title.trim() || !artist.trim()) return;
    setList((l) => [{ t: title, a: artist, by: name || 'Anonymous' }, ...l]);
    setTitle('');setArtist('');
  }

  return (
    <section className="snap" id="playlist" data-screen-label="11 Playlist">
      <div className="section-head">
        <span className="num">X.</span>
        <span className="label">For the DJ</span>
        <span className="rule" />
      </div>
      <h2 className="section-title">Help us <em>fill the dance floor.</em></h2>
      <div className="pl-wrap">
        <div className="pl-form">
          <div className="field">
            <label className="field-label">Song title</label>
            <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="At Last" />
          </div>
          <div className="field">
            <label className="field-label">Artist</label>
            <input value={artist} onChange={(e) => setArtist(e.target.value)} placeholder="Etta James" />
          </div>
          <div className="field">
            <label className="field-label">Your name</label>
            <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Optional" />
          </div>
          <button className="btn-primary" onClick={add}>Add to the queue</button>
        </div>
        <div className="pl-list">
          {list.map((s, i) =>
          <div key={i} className="pl-row">
              <div className="pn">{String(i + 1).padStart(2, '0')}</div>
              <div>
                <div className="pt">{s.t}</div>
                <div className="pa">{s.a}</div>
              </div>
              <div className="pby">— {s.by}</div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ===== GIFTS + WELL-WISHES (merged) =====
function Gifts() {
  const seed = [];

  const [list, setList] = useStateI(() => {
    try {
      const stored = JSON.parse(localStorage.getItem('jc-dj-guestbook-v2') || 'null');
      return Array.isArray(stored) ? stored : seed;
    } catch {return seed;}
  });
  const [m, setM] = useStateI('');
  const [by, setBy] = useStateI('');
  const [qrZoom, setQrZoom] = useStateI(false);

  useEffectI(() => {
    if (!qrZoom) return;
    const onKey = (e) => { if (e.key === 'Escape') setQrZoom(false); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [qrZoom]);

  useEffectI(() => {
    try {localStorage.setItem('jc-dj-guestbook-v2', JSON.stringify(list));} catch {}
  }, [list]);

  function post() {
    if (!m.trim() || !by.trim()) return;
    setList((l) => [{ m, by }, ...l]);
    setM('');setBy('');
  }

  const RES_I = typeof window !== 'undefined' && window.__resources || {};
  const qrSrc = RES_I.gcashQr || 'images/gcash-qr-enhanced.png';

  return (
    <section className="snap" id="gifts" data-screen-label="09 Gifts & Well-Wishes">
      <div className="section-head">
        <span className="num">X.</span>
        <span className="label">Gifts &amp; Well-Wishes</span>
        <span className="rule" />
      </div>
      <h2 className="section-title">The gift of your presence is <em>more than enough.</em></h2>

      <div className="give-layout">
        <aside className="gift-card">
          <div className="give-eyebrow">A Gift, If You Wish</div>
          <p className="gift-note">
            Your presence on our day is the only gift we truly need. But should you
            wish to help us begin our life together — as we save toward a home of our
            own — a little something through <em>GCash</em> would be received with the
            deepest gratitude.
          </p>
          <figure className="gift-qr">
            <button type="button" className="gift-qr-btn" onClick={() => setQrZoom(true)} aria-label="Enlarge the GCash QR code">
              <img src={qrSrc} alt="GCash QR code for sending a monetary gift to Jhon Carlo & Diane Joy" loading="lazy" />
              <span className="gift-qr-zoom" aria-hidden="true">⤢ Tap to enlarge</span>
            </button>
          </figure>
          <div className="gift-hint">Tap the code to enlarge · scan with the GCash app · transfer fees may apply</div>
        </aside>

        <div className="wish-col">
          <div className="give-eyebrow">Leave a Blessing</div>
          <p className="wish-intro">No gift expected — a few warm words are the loveliest thing you could leave us with.</p>
          <div className="gb-form">
            <div className="field">
              <label className="field-label">A note for the newlyweds</label>
              <textarea value={m} onChange={(e) => setM(e.target.value)} placeholder="May your love be the kind that…" />
            </div>
            <div className="field">
              <label className="field-label">Signed</label>
              <input value={by} onChange={(e) => setBy(e.target.value)} placeholder="Your name" />
            </div>
            <button className="btn-primary" onClick={post}>Pin to the wall</button>
          </div>
        </div>
      </div>

      {qrZoom && (
        <div className="qr-modal" onClick={() => setQrZoom(false)} role="dialog" aria-modal="true" aria-label="GCash QR code">
          <button type="button" className="qr-modal-close" onClick={() => setQrZoom(false)} aria-label="Close">Close ✕</button>
          <figure className="qr-modal-card" onClick={(e) => e.stopPropagation()}>
            <img src={qrSrc} alt="GCash QR code for sending a monetary gift to Jhon Carlo & Diane Joy" />
            <figcaption>Scan with the GCash app to send your gift</figcaption>
          </figure>
        </div>
      )}

      <div className="gb-wall" id="wishes">
        {list.length === 0 &&
        <div className="gb-empty">Be the first to leave the couple a blessing — your note will appear here.</div>
        }
        {list.map((n, i) =>
        <div key={i} className="gb-note">
            "{n.m}"
            <span className="by">— {n.by}</span>
          </div>
        )}
      </div>
    </section>);

}

window.FAQ = FAQ;
window.RSVP = RSVP;
window.Playlist = Playlist;
window.Gifts = Gifts;