/* global React */

// ============================================================
// BOOKING — multi-step form (treatment → date/time → details → confirm)
// ============================================================

const BookPage = ({ initialTreatment }) => {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    treatment: initialTreatment || "",
    practitioner: "any",
    date: "",
    time: "",
    name: "",
    phone: "",
    email: "",
    notes: "",
    consent: false,
    channel: "form",
  });
  const [errors, setErrors] = React.useState({});
  const [confetti, setConfetti] = React.useState(false);
  const [reference, setReference] = React.useState("");

  const setField = (k, v) => {
    setData(d => ({ ...d, [k]: v }));
    setErrors(e => ({ ...e, [k]: undefined }));
  };

  const steps = [
    { label: "Treatment", short: "01" },
    { label: "Date & time", short: "02" },
    { label: "Your details", short: "03" },
    { label: "Confirm", short: "04" },
  ];

  const validate = (s) => {
    const e = {};
    if (s === 0) {
      if (!data.treatment) e.treatment = "Choose a treatment, or “Not sure yet”.";
    }
    if (s === 1) {
      if (!data.date) e.date = "Pick a date.";
      if (!data.time) e.time = "Pick a time.";
    }
    if (s === 2) {
      if (!data.name.trim()) e.name = "Full name please.";
      if (!/^[+\d\s]{8,}$/.test(data.phone)) e.phone = "A reachable number, please.";
      if (data.email && !/^\S+@\S+\.\S+$/.test(data.email)) e.email = "That email doesn't look right.";
      if (!data.consent) e.consent = "We need your consent to contact you.";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (!validate(step)) return;
    if (step === steps.length - 1) {
      // Submit
      const ref = "CC-" + Math.random().toString(36).slice(2, 7).toUpperCase();
      setReference(ref);
      setConfetti(true);
      setStep(step + 1);
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    setStep(step + 1);
  };

  const back = () => setStep(Math.max(0, step - 1));

  // Date options: next 14 days
  const dateOptions = React.useMemo(() => {
    const out = [];
    const now = new Date();
    for (let i = 1; i <= 14; i++) {
      const d = new Date(now);
      d.setDate(now.getDate() + i);
      out.push({
        value: d.toISOString().slice(0, 10),
        day: d.toLocaleDateString("en-GB", { weekday: "short" }),
        dd:  d.toLocaleDateString("en-GB", { day: "2-digit" }),
        mon: d.toLocaleDateString("en-GB", { month: "short" }),
        sunday: d.getDay() === 0,
      });
    }
    return out;
  }, []);

  const times = ["10:00", "11:00", "12:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00"];

  const treatmentOptions = [
    { value: "", label: "Not sure yet — recommend for me" },
    ...window.TREATMENTS.map(t => ({ value: t.slug, label: t.title })),
  ];

  const treatmentLabel = treatmentOptions.find(t => t.value === data.treatment)?.label || "Not sure yet";

  // Final success screen
  if (step === steps.length) {
    return (
      <div className="page-enter">
        <section style={{ padding: "80px 0", position: "relative", overflow: "hidden" }}>
          {confetti && <Confetti />}
          <div className="container" style={{ maxWidth: 720, textAlign: "center", position: "relative", zIndex: 2 }}>
            <div style={{
              width: 88, height: 88, borderRadius: "50%",
              background: "rgba(201,162,75,0.15)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              marginBottom: 32, color: "var(--gold-deep)",
            }}>
              <CheckIcon size={40}/>
            </div>
            <h1 className="display-1" style={{ marginBottom: 18, fontSize: "clamp(40px, 5vw, 64px)" }}>
              Consultation <em>requested</em>.
            </h1>
            <p className="lede" style={{ margin: "0 auto 32px" }}>
              Thank you, <strong style={{ color: "var(--espresso)" }}>{data.name.split(" ")[0]}</strong>. We'll WhatsApp you on <strong style={{ color: "var(--espresso)" }}>{data.phone}</strong> within the next clinic hour to confirm your slot.
            </p>

            <div className="card" style={{ padding: 28, textAlign: "left", marginBottom: 28 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
                <span className="eyebrow">Your reference</span>
                <span style={{ fontFamily: "ui-monospace, monospace", fontSize: 14, color: "var(--gold-deep)", letterSpacing: "0.1em" }}>
                  {reference}
                </span>
              </div>
              <SummaryRow label="Treatment"    value={treatmentLabel}/>
              <SummaryRow label="Practitioner" value={data.practitioner === "any" ? "First available doctor" : data.practitioner}/>
              <SummaryRow label="Date"         value={data.date && new Date(data.date).toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" })}/>
              <SummaryRow label="Time"         value={data.time}/>
              <SummaryRow label="Contact"      value={`${data.phone}${data.email ? " · " + data.email : ""}`}/>
            </div>

            <div className="row" style={{ justifyContent: "center", gap: 10 }}>
              <a href="#/home" className="btn btn--ghost">Back to home</a>
              <a href="https://wa.me/971581955350?text=Hi%20Covent%20Clinic%2C%20I%20just%20submitted%20a%20consultation%20request%20-%20reference%20" target="_blank" rel="noopener" className="btn btn--whatsapp">
                <WhatsAppIcon /> Continue on WhatsApp
              </a>
            </div>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div className="page-enter">
      <section style={{ padding: "56px 0 32px" }}>
        <div className="container" style={{ maxWidth: 920 }}>
          <div className="eyebrow center" style={{ marginBottom: 16 }}>Book a consultation</div>
          <h1 className="display-1 center" style={{ fontSize: "clamp(40px, 5vw, 64px)", marginBottom: 14 }}>
            Free 15-minute <em>consultation</em>.
          </h1>
          <p className="lede center" style={{ margin: "0 auto", maxWidth: 520 }}>
            No payment now. We'll confirm your slot by WhatsApp.
          </p>
        </div>
      </section>

      <section style={{ padding: "0 0 80px" }}>
        <div className="container" style={{ maxWidth: 920 }}>
          {/* Stepper */}
          <div style={{
            display: "grid",
            gridTemplateColumns: `repeat(${steps.length}, 1fr)`,
            gap: 8,
            marginBottom: 40,
          }}>
            {steps.map((s, i) => {
              const active = i === step;
              const done = i < step;
              return (
                <div key={i} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  <div style={{
                    height: 4, borderRadius: 4,
                    background: done || active ? "var(--gold)" : "var(--line)",
                    transition: "background 240ms",
                  }}/>
                  <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                    <span style={{
                      width: 22, height: 22, borderRadius: 999,
                      background: done ? "var(--gold)" : active ? "var(--espresso)" : "transparent",
                      border: done || active ? "none" : "1px solid var(--line-strong)",
                      color: done || active ? "var(--ivory)" : "var(--espresso-soft)",
                      display: "inline-flex", alignItems: "center", justifyContent: "center",
                      fontSize: 11,
                      fontWeight: 600,
                      flexShrink: 0,
                    }}>{done ? <CheckIcon size={12}/> : s.short}</span>
                    <span style={{
                      fontSize: 13,
                      color: active ? "var(--espresso)" : "var(--espresso-soft)",
                      fontWeight: active ? 500 : 400,
                    }}>{s.label}</span>
                  </div>
                </div>
              );
            })}
          </div>

          <div className="card" style={{ padding: "40px 44px", background: "var(--cream-card)" }}>
            {step === 0 && (
              <StepTreatment data={data} setField={setField} errors={errors} options={treatmentOptions}/>
            )}
            {step === 1 && (
              <StepDate data={data} setField={setField} errors={errors} dateOptions={dateOptions} times={times}/>
            )}
            {step === 2 && (
              <StepDetails data={data} setField={setField} errors={errors}/>
            )}
            {step === 3 && (
              <StepConfirm data={data} treatmentLabel={treatmentLabel}/>
            )}

            <div style={{ display: "flex", justifyContent: "space-between", gap: 12, marginTop: 36, paddingTop: 28, borderTop: "1px solid var(--line)" }}>
              <button
                onClick={back}
                disabled={step === 0}
                className="btn btn--ghost"
                style={{ visibility: step === 0 ? "hidden" : "visible" }}
              >
                ← Back
              </button>
              <button onClick={next} className="btn btn--primary">
                {step === steps.length - 1 ? "Confirm request" : "Continue"} <ChevronRight size={12}/>
              </button>
            </div>
          </div>

          {/* Side option */}
          <div className="row" style={{ justifyContent: "center", gap: 16, marginTop: 24, fontSize: 13, color: "var(--espresso-soft)" }}>
            <span>Prefer not to fill a form?</span>
            <a href="https://wa.me/971581955350?text=Hi%20Covent%20Clinic%2C%20I%27d%20like%20to%20book%20a%20consultation" target="_blank" rel="noopener" style={{ color: "#1DB855", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6 }}>
              <WhatsAppIcon size={14}/> Book by WhatsApp
            </a>
            <span style={{ color: "var(--line-strong)" }}>·</span>
            <a href="tel:+971581955350" style={{ color: "var(--espresso)", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 6 }}>
              <PhoneIcon size={14}/> Call +971 58 195 5350
            </a>
          </div>
        </div>
      </section>
    </div>
  );
};

// ============================================================
// Step 1: treatment
// ============================================================
const StepTreatment = ({ data, setField, errors, options }) => (
  <div>
    <h2 className="display-3" style={{ marginBottom: 8 }}>What brings you in?</h2>
    <p className="muted" style={{ marginBottom: 28 }}>Choose a treatment category, or pick "Not sure yet" and we'll match you with the right doctor.</p>

    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }} className="opt-grid">
      {options.map(opt => {
        const selected = data.treatment === opt.value;
        return (
          <button key={opt.value} onClick={() => setField("treatment", opt.value)}
            style={{
              padding: "20px 18px",
              borderRadius: 12,
              background: selected ? "var(--espresso)" : "var(--ivory)",
              color: selected ? "var(--ivory)" : "var(--espresso)",
              border: selected ? "1px solid var(--espresso)" : "1px solid var(--line)",
              cursor: "pointer",
              textAlign: "left",
              fontFamily: "var(--f-display)",
              fontSize: 19,
              lineHeight: 1.3,
              transition: "all 180ms",
            }}>
            {opt.label}
          </button>
        );
      })}
    </div>

    <div style={{ marginTop: 28 }}>
      <h3 className="eyebrow" style={{ marginBottom: 12 }}>Preferred practitioner</h3>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {[{ value: "any", label: "First available" }, ...window.PRACTITIONERS.map(p => ({ value: p.name, label: p.name }))].map(p => {
          const selected = data.practitioner === p.value;
          return (
            <button key={p.value} onClick={() => setField("practitioner", p.value)}
              style={{
                padding: "10px 18px",
                borderRadius: 999,
                background: selected ? "var(--gold)" : "transparent",
                color: selected ? "var(--charcoal)" : "var(--espresso)",
                border: selected ? "1px solid var(--gold)" : "1px solid var(--line-strong)",
                cursor: "pointer",
                fontSize: 13,
              }}>
              {p.label}
            </button>
          );
        })}
      </div>
    </div>
  </div>
);

// ============================================================
// Step 2: date & time
// ============================================================
const StepDate = ({ data, setField, errors, dateOptions, times }) => (
  <div>
    <h2 className="display-3" style={{ marginBottom: 8 }}>When works for you?</h2>
    <p className="muted" style={{ marginBottom: 28 }}>Pick a date and a rough time — we'll confirm an exact slot when we WhatsApp you back.</p>

    <h3 className="eyebrow" style={{ marginBottom: 14 }}>Date</h3>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 8, marginBottom: 28 }} className="date-grid">
      {dateOptions.map(d => {
        const selected = data.date === d.value;
        return (
          <button key={d.value}
            onClick={() => !d.sunday && setField("date", d.value)}
            disabled={d.sunday}
            style={{
              padding: "12px 8px",
              borderRadius: 10,
              background: selected ? "var(--espresso)" : d.sunday ? "transparent" : "var(--ivory)",
              color: selected ? "var(--ivory)" : d.sunday ? "var(--line-strong)" : "var(--espresso)",
              border: selected ? "1px solid var(--espresso)" : "1px solid var(--line)",
              cursor: d.sunday ? "not-allowed" : "pointer",
              textAlign: "center",
              transition: "all 160ms",
              opacity: d.sunday ? 0.5 : 1,
            }}>
            <div style={{ fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 4 }}>{d.day}</div>
            <div style={{ fontFamily: "var(--f-display)", fontSize: 22, lineHeight: 1, marginBottom: 2 }}>{d.dd}</div>
            <div style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase", opacity: 0.7 }}>
              {d.sunday ? "Closed" : d.mon}
            </div>
          </button>
        );
      })}
    </div>
    {errors.date && <div style={{ color: "#C0463A", fontSize: 13, marginTop: -16, marginBottom: 14 }}>{errors.date}</div>}

    <h3 className="eyebrow" style={{ marginBottom: 14 }}>Time</h3>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 }}>
      {times.map(t => {
        const selected = data.time === t;
        return (
          <button key={t} onClick={() => setField("time", t)}
            style={{
              padding: "12px 8px",
              borderRadius: 10,
              background: selected ? "var(--gold)" : "var(--ivory)",
              color: selected ? "var(--charcoal)" : "var(--espresso)",
              border: selected ? "1px solid var(--gold)" : "1px solid var(--line)",
              cursor: "pointer",
              fontFamily: "var(--f-display)",
              fontSize: 18,
              transition: "all 160ms",
            }}>
            {t}
          </button>
        );
      })}
    </div>
    {errors.time && <div style={{ color: "#C0463A", fontSize: 13, marginTop: 12 }}>{errors.time}</div>}
  </div>
);

// ============================================================
// Step 3: details
// ============================================================
const StepDetails = ({ data, setField, errors }) => (
  <div>
    <h2 className="display-3" style={{ marginBottom: 8 }}>Your details</h2>
    <p className="muted" style={{ marginBottom: 28 }}>Just enough so we can confirm your slot. Nothing else.</p>

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
      <div className={"field" + (errors.name ? " error" : "")}>
        <label>Full name</label>
        <input value={data.name} onChange={e => setField("name", e.target.value)} placeholder="e.g. Mia De Mansa"/>
        {errors.name && <span className="err">{errors.name}</span>}
      </div>
      <div className={"field" + (errors.phone ? " error" : "")}>
        <label>Phone / WhatsApp</label>
        <input value={data.phone} onChange={e => setField("phone", e.target.value)} placeholder="+971 58 ..."/>
        {errors.phone && <span className="err">{errors.phone}</span>}
      </div>
      <div className={"field" + (errors.email ? " error" : "")} style={{ gridColumn: "span 2" }}>
        <label>Email <span style={{ opacity: 0.5, textTransform: "none", letterSpacing: 0 }}>(optional)</span></label>
        <input value={data.email} onChange={e => setField("email", e.target.value)} placeholder="you@email.com"/>
        {errors.email && <span className="err">{errors.email}</span>}
      </div>
      <div className="field" style={{ gridColumn: "span 2" }}>
        <label>Notes <span style={{ opacity: 0.5, textTransform: "none", letterSpacing: 0 }}>(optional)</span></label>
        <textarea
          value={data.notes}
          onChange={e => setField("notes", e.target.value)}
          placeholder="Anything we should know — concerns, prior treatments, medications…"
          rows={3}
        />
      </div>
    </div>

    <label style={{ display: "flex", gap: 12, marginTop: 28, cursor: "pointer", fontSize: 13, color: "var(--espresso)", lineHeight: 1.55 }}>
      <input type="checkbox" checked={data.consent} onChange={e => setField("consent", e.target.checked)}
        style={{ marginTop: 3, accentColor: "var(--gold)" }}/>
      <span>
        I consent to Covent Clinic contacting me about my consultation request by phone, SMS, WhatsApp or email. I understand that all treatments are subject to a clinical assessment.
      </span>
    </label>
    {errors.consent && <div style={{ color: "#C0463A", fontSize: 13, marginTop: 8 }}>{errors.consent}</div>}
  </div>
);

// ============================================================
// Step 4: confirm
// ============================================================
const StepConfirm = ({ data, treatmentLabel }) => (
  <div>
    <h2 className="display-3" style={{ marginBottom: 8 }}>Almost done.</h2>
    <p className="muted" style={{ marginBottom: 28 }}>Have a quick look — we'll send a confirmation to WhatsApp.</p>

    <div style={{ background: "var(--ivory)", border: "1px solid var(--line)", borderRadius: 14, padding: "8px 24px" }}>
      <SummaryRow label="Treatment"    value={treatmentLabel}/>
      <SummaryRow label="Practitioner" value={data.practitioner === "any" ? "First available doctor" : data.practitioner}/>
      <SummaryRow label="Date"         value={data.date && new Date(data.date).toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" })}/>
      <SummaryRow label="Time"         value={data.time}/>
      <SummaryRow label="Name"         value={data.name}/>
      <SummaryRow label="Phone"        value={data.phone}/>
      {data.email && <SummaryRow label="Email" value={data.email}/>}
      {data.notes && <SummaryRow label="Notes" value={data.notes}/>}
    </div>

    <div style={{ marginTop: 20, fontSize: 12, color: "var(--espresso-soft)", lineHeight: 1.6, fontStyle: "italic" }}>
      Submitting this request does not confirm your booking. A team member will WhatsApp you within the next clinic hour to finalise the slot. The consultation itself is free.
    </div>
  </div>
);

const SummaryRow = ({ label, value }) => (
  <div style={{
    display: "grid", gridTemplateColumns: "140px 1fr",
    padding: "14px 0", borderBottom: "1px solid var(--line)",
    alignItems: "baseline",
  }}>
    <div style={{ fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--espresso-soft)" }}>{label}</div>
    <div style={{ fontFamily: "var(--f-display)", fontSize: 18, color: "var(--espresso)" }}>{value || "—"}</div>
  </div>
);

// ============================================================
// Confetti (gold + blush + ivory dots that fall)
// ============================================================
const Confetti = () => {
  const colors = ["#C9A24B", "#E4CE9A", "#E7C9C2", "#FCFAF4", "#3B2C24"];
  const pieces = React.useMemo(() => Array.from({ length: 80 }).map((_, i) => ({
    id: i,
    left: Math.random() * 100,
    delay: Math.random() * 0.6,
    duration: 2.4 + Math.random() * 1.6,
    color: colors[Math.floor(Math.random() * colors.length)],
    size: 6 + Math.random() * 6,
    rot: Math.random() * 360,
  })), []);
  return (
    <div style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden", zIndex: 1 }}>
      <style>{`
        @keyframes confetti-fall {
          0%   { transform: translateY(-40px) rotate(0deg); opacity: 1; }
          100% { transform: translateY(120vh) rotate(720deg); opacity: 0; }
        }
      `}</style>
      {pieces.map(p => (
        <span key={p.id} style={{
          position: "absolute",
          left: `${p.left}%`,
          top: 0,
          width: p.size, height: p.size * 0.4,
          background: p.color,
          borderRadius: 2,
          transform: `rotate(${p.rot}deg)`,
          animation: `confetti-fall ${p.duration}s ${p.delay}s ease-in forwards`,
        }}/>
      ))}
    </div>
  );
};

Object.assign(window, { BookPage });
