// BookingModal — lightweight call-booking popup

const BOOKING_AGENTS = [
  { name: "Anass",   avatar: "assets/reviews/testimonials-1.jpg", available: true  },
  { name: "Zaid",  avatar: "assets/reviews/testimonials-2.jpg", available: true  },
  { name: "Loqmane", avatar: "assets/reviews/testimonials-3.jpg", available: true },
];

const BOOKING_METHODS = [
  { value: "whatsapp" },
  { value: "phone"    },
  { value: "meet"     },
  { value: "zoom"     },
  { value: "teams"    },
];

const PREFERRED_DAYS = ["Today", "Tomorrow", "This week"];

const getBookingLang = () => {
  const l = document.documentElement.lang;
  return l === 'ar-MA' ? 'dar' : (l || 'en');
};

const BookingModal = ({ onClose }) => {
  const lang    = getBookingLang();
  const bk      = (key) => t('booking.' + key, lang);
  const modalRef = React.useRef(null);
  const [form, setForm] = React.useState({
    name: "", email: "", contactMethod: "",
    contactNumber: "", meetEmail: "",
    preferredDay: "", preferredTime: "", notes: "",
  });
  const [submitted,    setSubmitted]    = React.useState(false);
  const [submitting,   setSubmitting]   = React.useState(false);
  const [submitError,  setSubmitError]  = React.useState('');

  React.useEffect(() => {
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = ""; };
  }, []);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  React.useEffect(() => {
    const modal = modalRef.current;
    if (!modal) return;
    const sel    = 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])';
    const getAll = () => Array.from(modal.querySelectorAll(sel));
    getAll()[0]?.focus();
    const trap = (e) => {
      if (e.key !== "Tab") return;
      const all = getAll();
      if (!all.length) return;
      if (e.shiftKey) {
        if (document.activeElement === all[0])            { e.preventDefault(); all[all.length - 1].focus(); }
      } else {
        if (document.activeElement === all[all.length - 1]) { e.preventDefault(); all[0].focus(); }
      }
    };
    modal.addEventListener("keydown", trap);
    return () => modal.removeEventListener("keydown", trap);
  }, [submitted]);

  const set = (k) => (e) => {
    const v = e.target.value;
    setForm((f) => {
      const update = { [k]: v };
      if (k === "contactMethod" && ["meet", "zoom", "teams"].includes(v) && !f.meetEmail) {
        update.meetEmail = f.email;
      }
      return { ...f, ...update };
    });
  };

  const setDay = (d) => setForm((f) => ({ ...f, preferredDay: f.preferredDay === d ? "" : d }));

  const needsNumber = ["whatsapp", "phone"].includes(form.contactMethod);
  const needsEmail  = ["meet", "zoom", "teams"].includes(form.contactMethod);

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim() || !form.contactMethod) return;

    setSubmitting(true);
    setSubmitError('');

    const contactValue = needsNumber ? form.contactNumber : (needsEmail ? form.meetEmail : '');

    const res = await fetch(`${SUPABASE_URL}/rest/v1/bookings`, {
      method: 'POST',
      headers: {
        'Content-Type':  'application/json',
        'apikey':        SUPABASE_ANON_KEY,
        'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
        'Prefer':        'return=minimal',
      },
      body: JSON.stringify({
        name:           form.name,
        email:          form.email,
        contact_method: form.contactMethod,
        contact_value:  contactValue  || null,
        preferred_date: form.preferredDay  || null,
        preferred_time: form.preferredTime || null,
        notes:          form.notes    || null,
      }),
    });

    setSubmitting(false);

    if (!res.ok) {
      setSubmitError(bk('error'));
      return;
    }

    window.analytics?.bookingRequest();
    setSubmitted(true);
  };

  return (
    <div
      className="ag-modal-overlay"
      role="dialog" aria-modal="true" aria-labelledby="bk-modal-title"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="ag-modal ag-booking-modal" ref={modalRef}>

        <button type="button" className="ag-modal__close" onClick={onClose} aria-label="Close">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>

        {submitted ? (
          <div className="ag-booking-confirm">
            <div className="ag-modal__icon" aria-hidden="true">
              <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20,6 9,17 4,12"/>
              </svg>
            </div>
            <h2 className="ag-modal__title">{bk('successTitle')}</h2>
            <p className="ag-modal__sub">{bk('successSub')}</p>
            <Button variant="dark" onClick={onClose}>{bk('done')}</Button>
          </div>
        ) : (
          <>
            <div className="ag-booking-head">
              <h2 className="ag-booking-title" id="bk-modal-title">{bk('title')}</h2>
              <p className="ag-booking-sub">{bk('sub')}</p>
            </div>

            <div className="ag-booking-agents" aria-label="Available team members" role="list">
              {BOOKING_AGENTS.map((a, i) => (
                <div key={a.name} className="ag-booking-agent" role="listitem">
                  <span className="ag-avatar ag-booking-agent__avatar" style={{ backgroundImage: `url('${a.avatar}')` }} role="img" aria-label={a.name}/>
                  <span className="ag-booking-agent__name">{a.name}</span>
                  <span className="ag-booking-agent__role">{t('booking.agentRoles.' + i, lang)}</span>
                  <span className="ag-booking-agent__badge">
                    <span className="ag-booking-agent__dot" data-available={a.available} aria-hidden="true"/>
                    {a.available ? bk('available') : bk('agentTomorrow')}
                  </span>
                </div>
              ))}
            </div>

            <form className="ag-booking-form" onSubmit={submit} noValidate>

              <div className="ag-booking-form__row">
                <div className="ag-field">
                  <label htmlFor="bk-name">{bk('nameLabel')}</label>
                  <input id="bk-name" type="text" required value={form.name} onChange={set("name")} placeholder="Your Name"/>
                </div>
                <div className="ag-field">
                  <label htmlFor="bk-email">{bk('emailLabel')}</label>
                  <input id="bk-email" type="email" required value={form.email} onChange={set("email")} placeholder="Sam@wablan.com"/>
                </div>
              </div>

              <div className="ag-field">
                <label htmlFor="bk-method">{bk('methodLabel')}</label>
                <select id="bk-method" required value={form.contactMethod} onChange={set("contactMethod")}>
                  <option value="" disabled>{bk('methodPh')}</option>
                  {BOOKING_METHODS.map((m, i) => (
                    <option key={m.value} value={m.value}>{t('booking.methods.' + i, lang)}</option>
                  ))}
                </select>
              </div>

              {needsNumber && (
                <div className="ag-field ag-step-reveal">
                  <label htmlFor="bk-number">{form.contactMethod === "whatsapp" ? bk('waLabel') : bk('phoneLabel')}</label>
                  <input id="bk-number" type="tel" value={form.contactNumber} onChange={set("contactNumber")} placeholder="+1 (555) 000-0000"/>
                </div>
              )}

              {needsEmail && (
                <div className="ag-field ag-step-reveal">
                  <label htmlFor="bk-meet-email">{bk('meetLabel')} <span className="ag-field__optional">{bk('optional')}</span></label>
                  <input id="bk-meet-email" type="email" value={form.meetEmail} onChange={set("meetEmail")} placeholder={form.email || "email@company.com"}/>
                </div>
              )}

              <div className="ag-field">
                <label>{bk('dayLabel')}</label>
                <div className="ag-time-opts" role="group" aria-label={bk('dayLabel')}>
                  {PREFERRED_DAYS.map((d, i) => (
                    <button key={d} type="button" className={"ag-time-opt" + (form.preferredDay === d ? " is-on" : "")} onClick={() => setDay(d)} aria-pressed={form.preferredDay === d}>
                      {t('booking.days.' + i, lang)}
                    </button>
                  ))}
                </div>
              </div>

              <div className="ag-field">
                <label htmlFor="bk-time">{bk('timeLabel')} <span className="ag-field__optional">{bk('optional')}</span></label>
                <input id="bk-time" type="text" value={form.preferredTime} onChange={set("preferredTime")} placeholder={bk('timePh')}/>
              </div>

              <div className="ag-field">
                <label htmlFor="bk-notes">{bk('notesLabel')} <span className="ag-field__optional">{bk('optional')}</span></label>
                <textarea id="bk-notes" rows="3" value={form.notes} onChange={set("notes")} placeholder={bk('notesPh')}/>
              </div>

              <div className="ag-booking-footer">
                {submitError && (
                  <p style={{ margin: '0 0 8px', fontSize: '13px', color: 'rgb(220,38,38)' }}>{submitError}</p>
                )}
                <Button variant="accent" type="submit" disabled={submitting || !form.name.trim() || !form.email.trim() || !form.contactMethod}>
                  {submitting ? bk('submitting') : bk('submit')}
                </Button>
                <p className="ag-booking-micro">{bk('micro')}</p>
              </div>

            </form>
          </>
        )}
      </div>
    </div>
  );
};

window.BookingModal = BookingModal;
