/* global React */
const { useState: useStateW, useEffect: useEffectW } = React;

/* ============== WAITLIST MODAL ==============
   Handles both: travel kit reservations + Century Club membership signup.
   Submits via mailto: to centurybarberpartners@gmail.com so requests
   land in Jeff's inbox immediately. */

function WaitlistModal({ open, kind, item, onClose }) {
  const [name, setName] = useStateW("");
  const [email, setEmail] = useStateW("");
  const [phone, setPhone] = useStateW("");
  const [qty, setQty] = useStateW(1);
  const [notes, setNotes] = useStateW("");
  const [submitted, setSubmitted] = useStateW(false);

  useEffectW(() => {
    if (open) {
      setSubmitted(false);
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!open) return null;

  const isKit = kind === "kit";
  const title = isKit
    ? `Reserve: ${item?.name || ""}`
    : "Join the Century Club";
  const sub = isKit
    ? "Travel kits launch soon — be first in line"
    : "Monthly membership · $49/mo";

  function buildMailto() {
    const to = "centurybarberpartners@gmail.com";
    const subj = isKit
      ? `WAITLIST: ${item?.tier} (${item?.name}) × ${qty}`
      : `MEMBERSHIP: Century Club signup`;
    const lines = isKit ? [
      `New travel kit waitlist signup`,
      `============================`,
      ``,
      `Kit: ${item?.tier} — ${item?.name}`,
      `Price: $${item?.price}`,
      `Quantity: ${qty}`,
      `Subtotal: $${(item?.price || 0) * qty}`,
      ``,
      `--- Customer ---`,
      `Name: ${name}`,
      `Email: ${email}`,
      `Phone: ${phone}`,
      ``,
      `Notes:`,
      notes || "(none)",
      ``,
      `--- Submitted via rinaldosbarbershop.com ---`,
    ] : [
      `New Century Club membership signup`,
      `===================================`,
      ``,
      `Plan: Century Club — $49/month`,
      `Includes: 2 cuts/mo, 10% off kits, priority booking, free birthday cut, members card`,
      ``,
      `--- Customer ---`,
      `Name: ${name}`,
      `Email: ${email}`,
      `Phone: ${phone}`,
      ``,
      `Notes:`,
      notes || "(none)",
      ``,
      `--- Submitted via rinaldosbarbershop.com ---`,
    ];
    const body = lines.join("\n");
    return `mailto:${to}?subject=${encodeURIComponent(subj)}&body=${encodeURIComponent(body)}`;
  }

  function handleSubmit(e) {
    e.preventDefault();
    if (!name || !email) return;
    // Open mail client
    window.location.href = buildMailto();
    // Show confirmation regardless (in case user has webmail or no client)
    setTimeout(() => setSubmitted(true), 200);
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>

        {!submitted ? (
          <>
            <div className="modal-header">
              <span className="eyebrow">{isKit ? "Travel Kit Waitlist" : "Membership"}</span>
              <h3>{title}</h3>
              <span className="script">{sub}</span>
            </div>

            {isKit && item && (
              <div className="modal-product">
                <div className={`tin-mini ${item.tin}`}>
                  <span>Rinaldo's</span>
                  <small>{item.tier.toUpperCase()}</small>
                </div>
                <div>
                  <div className="modal-product-name">{item.name}</div>
                  <div className="modal-product-tier">{item.tier} · ${item.price}</div>
                  <div className="modal-product-blurb">{item.blurb}</div>
                </div>
              </div>
            )}

            {!isKit && (
              <div className="modal-membership-summary">
                <div className="row"><span>Plan</span><b>The Century Club</b></div>
                <div className="row"><span>Rate</span><b>$49 / month</b></div>
                <div className="row"><span>Includes</span><b>2 cuts + perks</b></div>
                <div className="row"><span>Cancel</span><b>Anytime</b></div>
              </div>
            )}

            <form className="modal-form" onSubmit={handleSubmit}>
              <div className="bk-row">
                <div className="bk-field">
                  <label>Name *</label>
                  <input value={name} onChange={(e) => setName(e.target.value)} placeholder="John Smith" required />
                </div>
                <div className="bk-field">
                  <label>Phone</label>
                  <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="(814) 555-0123" />
                </div>
              </div>
              <div className="bk-field">
                <label>Email *</label>
                <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" required />
              </div>
              {isKit && (
                <div className="bk-field" style={{maxWidth: 200}}>
                  <label>Quantity</label>
                  <div className="qty-row">
                    <button type="button" onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
                    <span>{qty}</span>
                    <button type="button" onClick={() => setQty(qty + 1)}>+</button>
                  </div>
                </div>
              )}
              <div className="bk-field">
                <label>{isKit ? "Anything specific? (monogram, allergies, etc.)" : "Anything we should know?"}</label>
                <textarea rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} placeholder={isKit ? "Optional" : "Preferred chair time, etc."} />
              </div>

              <div className="modal-actions">
                <button type="button" className="btn btn-cream btn-sm" onClick={onClose}>Cancel</button>
                <button type="submit" className="btn">{isKit ? "Reserve My Kit →" : "Join the Club →"}</button>
              </div>
              <p className="modal-fineprint">
                {isKit
                  ? "We'll email you the moment the kits ship. No charge today — you'll confirm when they're ready."
                  : "We'll be in touch within 24 hours to set up your first appointment and payment."}
                <br/>
                Submissions go to <b>centurybarberpartners@gmail.com</b>.
              </p>
            </form>
          </>
        ) : (
          <div className="modal-confirm">
            <div className="stamp-mini">RECEIVED</div>
            <h3>You're on the list.</h3>
            <span className="script">we'll be in touch</span>
            <p>
              {isKit
                ? `Thanks, ${name}. We'll email ${email} as soon as the ${item?.tier} kits are ready to ship — and you'll be first in line.`
                : `Thanks, ${name}. Jeff will reach out to ${email} within 24 hours to get your Century Club membership set up.`}
            </p>
            <p style={{fontSize:13, opacity:0.7, marginTop:14}}>
              If your email client didn't open, copy this and send to <b>centurybarberpartners@gmail.com</b>:<br/>
              <code style={{display:'inline-block', background:'var(--cream-warm)', padding:'4px 8px', marginTop:6, fontSize:12}}>
                {isKit ? `Waitlist: ${item?.tier} × ${qty}` : "Membership signup"} — {name} ({email})
              </code>
            </p>
            <button className="btn" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

window.WaitlistModal = WaitlistModal;
