/* Recare — Hero with embedded booking widget (bilingual).
   Booking form submits to /api/bookings on confirm. */
function Hero({ onBook = () => {}, lang = "EN" }) {
  const t = T(lang).hero;
  const [step, setStep] = React.useState(0);
  const [specialtyIdx, setSpecialtyIdx] = React.useState(0);
  const [locationIdx, setLocationIdx] = React.useState(0);
  const [dateIdx, setDateIdx] = React.useState(0);
  const [timeIdx, setTimeIdx] = React.useState(null);

  const [fullName, setFullName] = React.useState("");
  const [mobile,   setMobile]   = React.useState("");
  const [nid,      setNid]      = React.useState("");

  const [submitting, setSubmitting] = React.useState(false);
  const [done,       setDone]       = React.useState(false);
  const [error,      setError]      = React.useState(null);

  const submit = async () => {
    setError(null);
    if (!fullName.trim() || !mobile.trim()) {
      setError(lang === "AR" ? "يرجى إدخال الاسم ورقم الجوال." : "Please enter your name and mobile.");
      return;
    }
    setSubmitting(true);
    try {
      const res = await fetch("/api/bookings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          full_name:      fullName.trim(),
          mobile:         mobile.trim(),
          national_id:    nid.trim() || null,
          specialty:      t.book.specialties[specialtyIdx],
          center:         t.book.locations[locationIdx],
          preferred_day:  t.book.days[dateIdx],
          preferred_time: timeIdx != null ? t.book.times[timeIdx] : null,
          lang,
        }),
      });
      if (!res.ok) throw new Error("submit_failed");
      setDone(true);
    } catch (e) {
      setError(lang === "AR"
        ? "تعذّر إرسال الطلب. حاول مرة أخرى."
        : "Could not submit. Please try again.");
    } finally {
      setSubmitting(false);
    }
  };

  const reset = () => {
    setDone(false); setStep(0); setTimeIdx(null);
    setFullName(""); setMobile(""); setNid(""); setError(null);
  };

  const advance = () => {
    if (step < 2) setStep(s => s + 1);
    else submit();
  };

  const successText = lang === "AR"
    ? { title: "تم استلام طلبك", sub: "سيتواصل معك فريق الحجز قريبًا لتأكيد الموعد.", again: "حجز موعد آخر" }
    : { title: "Booking received", sub: "Our team will call you shortly to confirm your appointment.", again: "Book another" };

  return (
    <section className="hero">
      <div className="hero__bg-pattern"></div>
      <div className="container hero__inner">
        <div className="hero__grid">
          <div>
            <Chip tone="dark" icon="sparkle">{t.chip}</Chip>
            <h1 className="hero__title" style={{ marginTop: 18 }}>
              {t.titleA} <em>{t.titleB}</em>
            </h1>
            <p className="hero__sub">{t.sub}</p>
            <div className="hero__cta-row">
              <Button variant="primary" size="lg" icon="calendar" onClick={onBook}>{t.ctaBook}</Button>
              <Button variant="ghost-light" size="lg" icon="video">{t.ctaTele}</Button>
            </div>
            <div className="hero__stats">
              {t.stats.map((s, i) => (
                <div key={i}>
                  <div className="hero__stat-num">{s.num}<small style={{ color: 'var(--rc-teal-300)' }}>{s.suffix}</small></div>
                  <div className="hero__stat-lbl">{s.lbl}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Booking card */}
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <div className="book-card" role="region" aria-label={t.book.title}>
              {done ? (
                <div style={{ textAlign: 'center', padding: '24px 8px' }}>
                  <div style={{ width: 56, height: 56, borderRadius: 99, background: 'rgba(46,157,136,0.15)', display: 'grid', placeItems: 'center', margin: '0 auto 14px', color: 'var(--rc-teal-500)' }}>
                    <Icon name="check" size={28} />
                  </div>
                  <div className="book-card__title">{successText.title}</div>
                  <div className="book-card__sub" style={{ marginTop: 6 }}>{successText.sub}</div>
                  <div style={{ marginTop: 18 }}>
                    <Button variant="ghost" onClick={reset}>{successText.again}</Button>
                  </div>
                </div>
              ) : (
                <>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
                    <div>
                      <div className="book-card__title">{t.book.title}</div>
                      <div className="book-card__sub">{t.book.step(step + 1)}</div>
                    </div>
                    <Chip tone="success" icon="check">{t.book.insuranceChip}</Chip>
                  </div>
                  <div className="book-card__steps">
                    {[0,1,2].map(i => <div key={i} className={`book-card__step-dot ${i <= step ? "is-active" : ""}`}></div>)}
                  </div>
                  <div className="book-card__fields">
                    {step === 0 && (
                      <>
                        <Field label={t.book.specialty}>
                          <Select value={specialtyIdx} onChange={(e) => setSpecialtyIdx(Number(e.target.value))}>
                            {t.book.specialties.map((s, i) => <option key={i} value={i}>{s}</option>)}
                          </Select>
                        </Field>
                        <Field label={t.book.location}>
                          <Select value={locationIdx} onChange={(e) => setLocationIdx(Number(e.target.value))}>
                            {t.book.locations.map((l, i) => <option key={i} value={i}>{l}</option>)}
                          </Select>
                        </Field>
                      </>
                    )}
                    {step === 1 && (
                      <>
                        <Field label={t.book.day}>
                          <div style={{ display: 'flex', gap: 8 }}>
                            {t.book.days.map((d, i) => (
                              <button key={i} type="button"
                                onClick={() => setDateIdx(i)}
                                className={`spec-pill ${dateIdx === i ? "is-active" : ""}`}
                                style={{ flex: 1, justifyContent: 'center' }}>
                                {d}
                              </button>
                            ))}
                          </div>
                        </Field>
                        <Field label={t.book.time}>
                          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
                            {t.book.times.map((tm, i) => (
                              <button key={tm} type="button"
                                onClick={() => setTimeIdx(i)}
                                className={`spec-pill ${timeIdx === i ? "is-active" : ""}`}
                                style={{ justifyContent: 'center', padding: '8px 0' }}>
                                {tm}
                              </button>
                            ))}
                          </div>
                        </Field>
                      </>
                    )}
                    {step === 2 && (
                      <>
                        <Field label={t.book.fullName}>
                          <Input placeholder={t.book.fullNameP} value={fullName} onChange={e => setFullName(e.target.value)} />
                        </Field>
                        <div className="book-card__row">
                          <Field label={t.book.mobile}>
                            <Input placeholder={t.book.mobileP} value={mobile} onChange={e => setMobile(e.target.value)} />
                          </Field>
                          <Field label={t.book.idLabel}>
                            <Input placeholder={t.book.idP} value={nid} onChange={e => setNid(e.target.value)} />
                          </Field>
                        </div>
                        {error && (
                          <div style={{ background: '#FEECEC', color: '#B42318', padding: '8px 12px', borderRadius: 8, fontSize: 13 }}>
                            {error}
                          </div>
                        )}
                      </>
                    )}
                  </div>
                  <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
                    {step > 0 && (
                      <Button variant="ghost" onClick={() => setStep(s => s - 1)} icon="arrowLeft">{t.book.back}</Button>
                    )}
                    <Button variant="primary" iconRight={step < 2 ? "arrow" : undefined} icon={step === 2 ? "check" : undefined}
                      onClick={advance}
                      disabled={submitting}
                      style={{ marginInlineStart: 'auto' }}>
                      {submitting ? (lang === "AR" ? "جاري الإرسال…" : "Sending…") : (step < 2 ? t.book.next : t.book.confirm)}
                    </Button>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Hero });
