// closing.jsx — Testimonials, Reserve/Contact, Footer
const { useState: useCloseState, useEffect: useCloseEffect } = React;

function Testimonials() {
  const [i, setI] = useCloseState(0);
  useCloseEffect(() => {
    const t = setInterval(() => setI(x => (x + 1) % TESTIMONIALS.length), 7000);
    return () => clearInterval(t);
  }, []);
  const t = TESTIMONIALS[i];
  return (
    <section className="section testimonials" id="testimonials">
      <div className="container narrow">
        <Reveal>
          <Eyebrow align="center" style={{ justifyContent: "center" }}>Client Word</Eyebrow>
          <div className="quote-wrap">
            <span className="quote-mark">”</span>
            <blockquote key={i} className="quote">{t.quote}</blockquote>
            <div className="quote-by">{t.who} · <span>{t.where}</span></div>
          </div>
          <div className="quote-dots">
            {TESTIMONIALS.map((_, k) => (
              <button key={k} className={`dot ${k === i ? "is-active" : ""}`} onClick={() => setI(k)} aria-label={`Quote ${k + 1}`} />
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

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

function DocUpload({ label, hint, icon, file, onFile, name }) {
  const inputRef = React.useRef(null);
  const icons = {
    id: <g><rect x="3" y="6" width="26" height="20" rx="3" /><circle cx="11" cy="14" r="3" /><path d="M6 22c1-2.6 3-4 5-4s4 1.4 5 4" /><path d="M19 13h7M19 17h7M19 21h4" /></g>,
    doc: <g><path d="M8 3h11l6 6v20a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z" /><path d="M19 3v6h6" /><path d="M12 17h9M12 21h9M12 13h4" /></g>,
  };
  return (
    <div className={`doc-tile ${file ? "is-filled" : ""}`} role="button" tabIndex={0}
      onClick={() => inputRef.current && inputRef.current.click()}>
      <input ref={inputRef} type="file" name={name} accept=".pdf,.jpg,.jpeg,.png,image/*" hidden
        onChange={(e) => onFile(e.target.files && e.target.files[0] ? e.target.files[0] : null)} />
      <span className="doc-ico">
        <svg viewBox="0 0 32 32" width="26" height="26" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">{icons[icon]}</svg>
      </span>
      <span className="doc-label">{label}</span>
      {file ? (
        <span className="doc-file">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 6.5" /></svg>
          {file.name}
        </span>
      ) : (
        <span className="doc-hint">{hint}</span>
      )}
    </div>
  );
}

function Reserve({ preset }) {
  const [form, setForm] = useCloseState({ name: "", phone: "", email: "", vehicle: "", dates: "", message: "", license: null, registration: null });
  const [err, setErr] = useCloseState({});
  const { sending, sent, sinkName, begin, onSinkLoad, reset } = useEmailForm();
  useCloseEffect(() => { if (preset) setForm(f => ({ ...f, vehicle: preset })); }, [preset]);
  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const setFile = (k) => (file) => setForm(f => ({ ...f, [k]: file }));
  const blank = { name: "", phone: "", email: "", vehicle: "", dates: "", message: "", license: null, registration: null };
  const subject = `New Reservation Request — ${form.name || "Website"}`;

  const onSubmit = (e) => {
    const er = {};
    if (!form.name.trim()) er.name = 1;
    if (!form.phone.trim() && !form.email.trim()) { er.phone = 1; er.email = 1; }
    setErr(er);
    if (Object.keys(er).length !== 0) { e.preventDefault(); return; }
    begin(); // allow the native form to POST (with attachments) into the hidden iframe
  };

  return (
    <section className="section reserve" id="reserve">
      <div className="container">
        <div className="reserve-grid">
          <Reveal className="reserve-intro">
            <Eyebrow>Reserve</Eyebrow>
            <h2 className="section-title">Begin Your Reservation</h2>
            <p className="section-intro">
              By reservation only. Tell us which service you have in mind and a member of the Reserve will
              reach out personally to arrange the particulars.
            </p>
            <ul className="contact-list">
              <li><span className="cl-k">Phone</span><a href={`tel:${CONTACT.phone.replace(/[^0-9]/g,"")}`}>{CONTACT.phone}</a></li>
              <li><span className="cl-k"></span><a href={`tel:${CONTACT.phone2.replace(/[^0-9]/g,"")}`}>{CONTACT.phone2}</a></li>
              <li><span className="cl-k">Email</span><a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a></li>
              <li><span className="cl-k">Hours</span><span>{CONTACT.hours}</span></li>
              <li><span className="cl-k">Area</span><span>{CONTACT.area}</span></li>
              <li><span className="cl-k">Instagram</span><a href={CONTACT.igUrl} target="_blank" rel="noreferrer">{CONTACT.ig}</a></li>
            </ul>
          </Reveal>

          <Reveal delay={100} className="reserve-form">
            {sent ? (
              <div className="form-sent">
                <span className="sent-tick">
                  <svg viewBox="0 0 48 48" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="24" cy="24" r="20" /><path d="M15 24.5l6 6 12-13" />
                  </svg>
                </span>
                <h3>Reservation Requested</h3>
                <p>Thank you, {form.name.split(" ")[0] || "and welcome"}. A member of the Reserve will be in touch shortly to confirm the details.</p>
                <button className="text-link" onClick={() => { reset(); setForm(blank); }}>Submit another request</button>
              </div>
            ) : (
              <form className="form-body" action={FORM_ENDPOINT} method="POST" encType="multipart/form-data" target={sinkName} onSubmit={onSubmit}>
                <FormSubmitMeta subject={subject} />
                <input type="hidden" name="Form" value="Begin Your Reservation" />
                <div className="form-row">
                  <Field label="Name"><input className={`inp ${err.name ? "inp-err" : ""}`} name="Name" value={form.name} onChange={set("name")} placeholder="Full name" /></Field>
                  <Field label="Phone"><input className={`inp ${err.phone ? "inp-err" : ""}`} name="Phone" value={form.phone} onChange={set("phone")} placeholder="(   )   -" /></Field>
                </div>
                <div className="form-row">
                  <Field label="Email"><input className={`inp ${err.email ? "inp-err" : ""}`} name="email" value={form.email} onChange={set("email")} placeholder="you@example.com" /></Field>
                  <Field label="Dates"><DatePicker value={form.dates} onChange={(v) => setForm(f => ({ ...f, dates: v }))} mode="range" placeholder="Select dates…" /><input type="hidden" name="Dates" value={form.dates} /></Field>
                </div>
                <Field label="Service of Interest">
                  <div className="select-wrap">
                    <select className="inp" name="Service" value={form.vehicle} onChange={set("vehicle")}>
                      <option value="">Select a service…</option>
                      {SERVICE_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
                    </select>
                    <i className="select-caret" />
                  </div>
                </Field>
                <Field label="Message"><textarea className="inp inp-area" rows={3} name="Message" value={form.message} onChange={set("message")} placeholder="Occasion, dates, location, anything we should know…" /></Field>

                <div className="form-docs">
                  <span className="field-label">Verification Documents <em>— optional, or bring at delivery</em></span>
                  <div className="doc-grid">
                    <DocUpload name="Driver's License" label="Driver’s License" hint="Photo or PDF" icon="id" file={form.license} onFile={setFile("license")} />
                    <DocUpload name="Insurance / Registration" label="Insurance / Registration" hint="Photo or PDF" icon="doc" file={form.registration} onFile={setFile("registration")} />
                  </div>
                  <p className="doc-secure">
                    <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></svg>
                    Shared securely and used only to verify your reservation. Up to 10 MB total.
                  </p>
                </div>

                {(err.name || err.phone) && <div className="form-hint">Please share your name and a way to reach you.</div>}
                <GoldButton full size="lg" disabled={sending}>{sending ? "Sending…" : "Request Reservation"}</GoldButton>
                <iframe name={sinkName} title="form-target" onLoad={onSinkLoad} style={{ display: "none" }} />
              </form>
            )}
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function Footer({ onGo, onReserve }) {
  return (
    <footer className="footer">
      <div className="container footer-inner">
        <div className="footer-brand">
          <Medallion size={64} />
          <div className="footer-wm">
            <span className="wm-main">Chairman’s Reserve</span>
            <span className="wm-sub">Luxury Experiences</span>
          </div>
          <div className="footer-powered">
            <img src="assets/bally-logo-v3.png" alt="" className="fp-logo" />
            <span>Powered by Bally &amp; Co. Motors</span>
          </div>
        </div>
        <div className="footer-cols">
          <div className="footer-col">
            <span className="footer-h">Explore</span>
            {NAV.map(item => <button key={item.label} onClick={() => item.view ? onGo({ view: item.view }) : onGo({ target: item.target })}>{item.label}</button>)}
            <button onClick={onReserve}>Reserve</button>
          </div>
          <div className="footer-col">
            <span className="footer-h">Contact</span>
            <a href={`tel:${CONTACT.phone.replace(/[^0-9]/g,"")}`}>{CONTACT.phone}</a>
            <a href={`tel:${CONTACT.phone2.replace(/[^0-9]/g,"")}`}>{CONTACT.phone2}</a>
            <a href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a>
            <span>{CONTACT.area}</span>
            <span>{CONTACT.hours}</span>
          </div>
          <div className="footer-col">
            <span className="footer-h">Follow</span>
            <a href={CONTACT.igUrl} target="_blank" rel="noreferrer" className="footer-ig">
              <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>
              {CONTACT.ig}
            </a>
            <a href="https://www.instagram.com/sendthewiretony" target="_blank" rel="noreferrer" className="footer-ig">
              <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>
              @sendthewiretony
            </a>
          </div>
        </div>
      </div>
      <div className="footer-base">
        <span className="footer-tag">By Reservation Only.</span>
        <span>© {new Date().getFullYear()} Chairman’s Reserve — Luxury Experiences</span>
      </div>
      <div className="footer-credit">© {new Date().getFullYear()} <a href="https://ironsitestudio.io" target="_blank" rel="noreferrer">IronSite Web Studio</a>. All rights reserved.</div>
    </footer>
  );
}

Object.assign(window, { Testimonials, Reserve, Footer, DocUpload });
