/* Booking, Media, Patient Stories, v1 visual language. */
const { useState, useEffect, useRef } = React;

/* ================= BOOKING ================= */
function AppointmentForm({ go, compact }) {
  const emptyForm = { name: "", email: "", phone: "", concern: CONCERNS[0], location: LOCATIONS[0].name, message: "", company: "" };
  const [form, setForm] = useState(emptyForm);
  const [err, setErr] = useState({});
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const startedAt = useRef(Date.now());
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = async (e) => {
    e.preventDefault();
    // Honeypot + minimum fill time: drop likely bot submissions quietly.
    if (form.company.trim() || Date.now() - startedAt.current < 1200) {
      setSent(true);
      return;
    }
    const er = {};
    if (!form.name.trim()) er.name = "Please enter your name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) er.email = "Enter a valid email address.";
    if (!/^[+\d][\d\s-]{7,}$/.test(form.phone.trim())) er.phone = "Enter a valid phone number.";
    if (!form.message.trim()) er.message = "Please briefly describe your concern.";
    setErr(er);
    if (Object.keys(er).length) return;

    setSending(true);
    setErr({});
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          access_key: CLINIC.web3formsAccessKey,
          subject: "New appointment request – " + CLINIC.name,
          name: form.name.trim(),
          email: form.email.trim(),
          phone: form.phone.trim(),
          concern: form.concern,
          location: compact ? LOCATIONS[0].name : form.location,
          message: form.message.trim(),
        }),
      });
      const data = await res.json();
      if (!res.ok || !data.success) throw new Error(data.message || "Unable to send your request.");
      setSent(true);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (error) {
      setErr({ form: error.message || "Something went wrong. Please try again or call the clinic directly." });
    } finally {
      setSending(false);
    }
  };
  if (sent) return (
    <div className="form-card">
      <div className="form-sent">
        <div className="tick"><Icon name="check" size={32} stroke={2.4} /></div>
        <h3>Thank you, {form.name.split(" ")[0]}!</h3>
        <p>Your request has been sent. The clinic will call you back within one working day to confirm your appointment.</p>
        <Btn onClick={() => { setSent(false); setForm(emptyForm); startedAt.current = Date.now(); }}>Send another request</Btn>
      </div>
    </div>
  );
  return (
    <form className="form-card" onSubmit={submit} autoComplete="on">
      <h3>Request an appointment</h3>
      <p>Fill in your details and the clinic will get back to you.</p>
      {err.form && <p className="field-err" style={{ marginBottom: 16 }}>{err.form}</p>}
      <div className="hp-field" aria-hidden="true">
        <label htmlFor="company">Company</label>
        <input
          id="company"
          type="text"
          name="company"
          value={form.company}
          onChange={e => set("company", e.target.value)}
          tabIndex={-1}
          autoComplete="off"
        />
      </div>
      <div className="field">
        <label>Full name</label>
        <input className={err.name ? "err" : ""} name="name" required value={form.name} onChange={e => set("name", e.target.value)} placeholder="Your name" disabled={sending} />
        {err.name && <span className="field-err">{err.name}</span>}
      </div>
      <div className="field">
        <label>Email</label>
        <input className={err.email ? "err" : ""} type="email" name="email" required value={form.email} onChange={e => set("email", e.target.value)} placeholder="you@example.com" disabled={sending} />
        {err.email && <span className="field-err">{err.email}</span>}
      </div>
      <div className="field">
        <label>Phone number</label>
        <input className={err.phone ? "err" : ""} name="phone" value={form.phone} onChange={e => set("phone", e.target.value)} placeholder="+91" disabled={sending} />
        {err.phone && <span className="field-err">{err.phone}</span>}
      </div>
      <div className="field">
        <label>Concern</label>
        <select name="concern" value={form.concern} onChange={e => set("concern", e.target.value)} disabled={sending}>
          {CONCERNS.map(c => <option key={c}>{c}</option>)}
        </select>
      </div>
      {!compact && (
        <div className="field">
          <label>Preferred location</label>
          <select name="location" value={form.location} onChange={e => set("location", e.target.value)} disabled={sending}>
            {LOCATIONS.map(l => <option key={l.name}>{l.name}, {l.line1}</option>)}
          </select>
        </div>
      )}
      <div className="field">
        <label>Message</label>
        <textarea rows="3" name="message" required value={form.message} onChange={e => set("message", e.target.value)} placeholder="Briefly describe your concern" disabled={sending} />
        {err.message && <span className="field-err">{err.message}</span>}
      </div>
      <Btn type="submit" icon="arrow" block disabled={sending}>{sending ? "Sending…" : "Send Request"}</Btn>
    </form>
  );
}

function Booking({ go }) {
  useReveal();
  return (
    <main>
      <section>
        <div className="wrap book-grid">
          <div className="book-maps reveal">
            {[
              { name: "Dr. Rajasekhar Reddy's Neurospine Clinic, Kukatpally", q: "Dr Rajasekhar Reddy Neuro and Spine Clinic, Road No 4, KPHB Colony, Kukatpally, Hyderabad, Telangana 500072" },
              { name: "Yashoda Hospitals, Hitec City", q: "Yashoda Hospitals Hitech City, Hitech City Main Road, Khanamet, Hyderabad, Telangana 500084" },
            ].map(m => (
              <div key={m.name} className="book-map">
                <b className="book-map-label"><Icon name="pin" size={16} />{m.name}</b>
                <div className="book-map-frame">
                  <iframe
                    title={`Map: ${m.name}`}
                    src={`https://www.google.com/maps?q=${encodeURIComponent(m.q)}&output=embed`}
                    loading="lazy"
                    referrerPolicy="no-referrer-when-downgrade"
                    allowFullScreen
                  />
                </div>
              </div>
            ))}
          </div>
          <div className="reveal">
            <div className="book-cta-row">
              <Btn contact="whatsapp" variant="whatsapp" icon="whatsapp">Message us on WhatsApp</Btn>
              <Btn contact="phone" variant="light" icon="phone">Call <ContactText kind="phone" /></Btn>
            </div>
            <AppointmentForm go={go} />
          </div>
        </div>
      </section>
    </main>
  );
}

/* ================= MEDIA ================= */
function Media({ go }) {
  useReveal();
  return (
    <main>
      <section>
        <div className="wrap">
          <ReelCarousel />

          <div className="media-yt-cta reveal">
            <Btn href={CLINIC.youtubeUrl} newTab icon="play">Visit our YouTube channel</Btn>
          </div>

          <div className="media-long reveal">
            <div className="res-grid">
              {MEDIA_VIDEOS.map(v => {
                const thumb = (
                  <div className="media-thumb">
                    {v.videoId ?
                      <img src={`https://img.youtube.com/vi/${v.videoId}/hqdefault.jpg`} alt={v.title} loading="lazy" /> :
                      <Ph label="video thumbnail" ratio="16 / 10" round={0} />
                    }
                    <span className="media-play"><Icon name="play" size={20} fill="#0E3A4A" stroke="#0E3A4A" /></span>
                    <span className="media-len">{v.len}</span>
                  </div>
                );
                const body = (
                  <div className="res-body">
                    <span className="res-cat">{v.cat}</span>
                    <h3>{v.title}</h3>
                    <p>{v.desc}</p>
                    <span className="res-read"><Icon name="play" size={14} />Watch</span>
                  </div>
                );
                if (v.videoId) {
                  return (
                    <a key={v.id} className="res-card" href={v.url || `https://www.youtube.com/watch?v=${v.videoId}`} target="_blank" rel="noopener noreferrer">
                      {thumb}{body}
                    </a>
                  );
                }
                return (
                  <button key={v.id} type="button" className="res-card" onClick={() => go("media")}>
                    {thumb}{body}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </section>
      <CTABand go={go} />
    </main>
  );
}

/* ================= PATIENT STORIES ================= */
function PatientStories({ go }) {
  useReveal();
  const [expanded, setExpanded] = useState({});
  const toggle = (i) => setExpanded((prev) => ({ ...prev, [i]: !prev[i] }));

  return (
    <main>
      <section className="testi home-stories">
        <div className="aurora" />
        <div className="wrap">
          <div className="sec-head reveal">
            <Eyebrow light>Written reviews</Eyebrow>
            <h2>Stories from the people we've cared for.</h2>
          </div>
          <div className="home-story-grid">
            {STORIES.map((s, i) => (
              <StoryCard key={i} story={s} expanded={!!expanded[i]} onToggle={() => toggle(i)} />
            ))}
          </div>
        </div>
      </section>
      <CTABand go={go} />
    </main>
  );
}

/* ================= PRIVACY POLICY ================= */
function Privacy({ go }) {
  useReveal();
  const updated = new Date().toLocaleDateString("en-IN", { year: "numeric", month: "long", day: "numeric" });
  return (
    <main>
      <section>
        <div className="wrap legal-wrap">
          <p className="legal-updated reveal">Last updated: {updated}</p>

          <div className="legal-block reveal">
            <h2>Information we collect</h2>
            <p>When you contact the clinic or request an appointment, we may collect your name, phone number, email address, and any details you choose to share about your symptoms or medical history. This information is used solely to respond to your enquiry and to provide care.</p>
          </div>

          <div className="legal-block reveal">
            <h2>How we use your information</h2>
            <p>Your information is used to schedule and manage appointments, to communicate with you about your care, and to maintain accurate medical records. We do not sell or rent your personal information to third parties.</p>
          </div>

          <div className="legal-block reveal">
            <h2>Data protection</h2>
            <p>We take reasonable steps to keep your information secure and confidential, in line with applicable medical confidentiality standards. Access is limited to the clinical and administrative team involved in your care.</p>
          </div>

          <div className="legal-block reveal">
            <h2>Your rights</h2>
            <p>You may request access to the personal information we hold about you, ask for corrections, or request deletion where appropriate. To make a request, please contact us using the details below.</p>
          </div>

          <div className="legal-block reveal">
            <h2>Contact us</h2>
            <p>
              For any questions about this policy or your information, reach us at{" "}
              <ContactLink kind="email" className="legal-link"><ContactText kind="email" /></ContactLink> or{" "}
              <ContactLink kind="phone" className="legal-link"><ContactText kind="phone" /></ContactLink>.
            </p>
          </div>

          <div style={{ marginTop: 40 }} className="reveal">
            <Btn variant="ghost" icon="arrow" onClick={() => go("home")}>Back to home</Btn>
          </div>
        </div>
      </section>
    </main>
  );
}

/* ================= MAPS ================= */
function Maps({ go }) {
  useReveal();
  return (
    <main>
      <PageHero
        eyebrow="Clinic locations"
        title="Find us on the map"
        sub="Visit Dr. Reddy at the Kukatpally clinic or at Yashoda Hospitals, Hitec City."
      />
      <LocationsSection go={go} />
      <CTABand go={go} />
    </main>
  );
}

Object.assign(window, { Booking, AppointmentForm, Media, PatientStories, Privacy, Maps });
