// Villa Mesochori — direct booking flow. Pricing comes from the owners' admin settings
// (window.VMContent); the request is emailed to the owners' address.
const bkNS = window.VillaMesochoriDesignSystem_9e1a21;
const { Button: BkButton, Input: BkInput, Select: BkSelect, Checkbox: BkCheckbox, Badge: BkBadge, LucideIcon: BkIcon } = bkNS;

function BkStep({ n, label, state }) {
  const done = state === "done", active = state === "active";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <span style={{
        width: 26, height: 26, borderRadius: "50%", display: "inline-flex", alignItems: "center", justifyContent: "center",
        font: "700 13px var(--font-body)",
        background: done ? "var(--secondary)" : active ? "var(--accent)" : "var(--surface-sunken)",
        color: done || active ? "#FFFDF9" : "var(--text-muted)",
        border: done || active ? "1px solid transparent" : "1px solid var(--border-strong)",
      }}>{done ? "✓" : n}</span>
      <span style={{ font: "600 14px var(--font-body)", color: active ? "var(--text-heading)" : "var(--text-muted)" }}>{label}</span>
    </div>
  );
}

function BkPrice({ c, nights, guests, stay, seasonal }) {
  return (
    <div style={{ background: "var(--surface-card)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-card)", padding: 24, position: "sticky", top: 24 }}>
      <h3 style={{ font: "var(--type-h4)", margin: "0 0 4px" }}>Your stay</h3>
      <p style={{ font: "var(--type-small)", color: "var(--text-muted)", margin: "0 0 16px" }}>{nights} night{nights === 1 ? "" : "s"} · {guests} guest{guests === 1 ? "" : "s"}</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 8, font: "var(--type-body)", borderBottom: "1px solid var(--border-soft)", paddingBottom: 14, marginBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <span>{seasonal ? `${nights} nights (seasonal rates)` : `${c.currency}${c.nightly} × ${nights} nights`}</span>
          <span>{c.currency}{stay}</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between" }}><span>Cleaning</span><span>{c.currency}{c.cleaning}</span></div>
        <div style={{ display: "flex", justifyContent: "space-between", color: "var(--text-muted)" }}><span>Platform fees</span><span>{c.currency}0 — you booked direct</span></div>
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", font: "700 17px var(--font-body)", color: "var(--text-heading)" }}>
        <span>Total</span><span>{c.currency}{stay + c.cleaning}</span>
      </div>
      <p style={{ font: "var(--type-small)", color: "var(--text-muted)", margin: "14px 0 0" }}>
        Pay a {c.depositPct}% deposit to hold the dates — we'll confirm by email within a day.
      </p>
    </div>
  );
}

// PayPal deposit button — renders only when the owners have set a PayPal Client ID
function PayPalDeposit({ c, amount, note }) {
  const ref = React.useRef(null);
  const [state, setState] = React.useState("loading"); // loading | ready | paid | error
  React.useEffect(() => {
    if (!c.paypalClientId) return;
    const render = () => {
      if (!window.paypal || !ref.current) return;
      ref.current.innerHTML = "";
      window.paypal.Buttons({
        style: { color: "gold", shape: "pill", label: "pay", height: 44 },
        createOrder: (data, actions) => actions.order.create({
          purchase_units: [{ description: note, amount: { value: amount.toFixed(2), currency_code: c.payCurrency } }],
        }),
        onApprove: (data, actions) => actions.order.capture().then(() => setState("paid")),
        onError: () => setState("error"),
      }).render(ref.current).then(() => setState("ready")).catch(() => setState("error"));
    };
    const id = "vm-paypal-sdk";
    if (document.getElementById(id)) { render(); return; }
    const s = document.createElement("script");
    s.id = id;
    s.src = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(c.paypalClientId)}&currency=${encodeURIComponent(c.payCurrency)}&intent=capture`;
    s.onload = render;
    s.onerror = () => setState("error");
    document.head.appendChild(s);
  }, []);

  if (!c.paypalClientId) return null;
  if (state === "paid") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        <BkBadge tone="success">Deposit paid — thank you</BkBadge>
        <p style={{ font: "var(--type-body)", color: "var(--text-body)", margin: 0, maxWidth: 480 }}>
          Your dates are held. We'll email your receipt and confirmation shortly.
        </p>
      </div>
    );
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10, maxWidth: 420, width: "100%" }}>
      <span style={{ font: "600 15px var(--font-body)", color: "var(--text-heading)" }}>
        Hold your dates now — pay the {c.depositPct}% deposit ({c.currency}{amount.toFixed(2)})
      </span>
      <div ref={ref}></div>
      {state === "loading" && <span style={{ font: "var(--type-small)", color: "var(--text-muted)" }}>Loading secure payment…</span>}
      {state === "error" && <span style={{ font: "var(--type-small)", color: "var(--text-muted)" }}>Payment didn't load — no problem, we'll send payment details by email instead.</span>}
      <span style={{ font: "var(--type-small)", color: "var(--text-muted)" }}>Paying by card works too — no PayPal account needed.</span>
    </div>
  );
}

// Square card deposit — renders when the owners have set Square App + Location IDs.
// The card is tokenized in the browser; the charge happens on the server (api.php).
function SquareDeposit({ c, amount, note }) {
  const boxRef = React.useRef(null);
  const cardRef = React.useRef(null);
  const [state, setState] = React.useState("loading"); // loading | ready | paying | paid | error | unavailable
  const [errMsg, setErrMsg] = React.useState("");
  React.useEffect(() => {
    if (!c.squareAppId || !c.squareLocationId) return;
    if (!window.VMContent.serverMode()) { setState("unavailable"); return; }
    const init = () => {
      if (!window.Square || !boxRef.current) { setState("error"); return; }
      window.Square.payments(c.squareAppId, c.squareLocationId).card()
        .then((card) => card.attach(boxRef.current).then(() => { cardRef.current = card; setState("ready"); }))
        .catch(() => setState("error"));
    };
    const id = "vm-square-sdk";
    if (document.getElementById(id)) { init(); return; }
    const s = document.createElement("script");
    s.id = id;
    s.src = "https://web.squarecdn.com/v1/square.js";
    s.onload = init;
    s.onerror = () => setState("error");
    document.head.appendChild(s);
  }, []);

  if (!c.squareAppId || !c.squareLocationId) return null;
  if (state === "unavailable") return null; // needs the live server
  if (state === "paid") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        <BkBadge tone="success">Deposit paid by card — thank you</BkBadge>
        <p style={{ font: "var(--type-body)", color: "var(--text-body)", margin: 0, maxWidth: 480 }}>Your dates are held. We'll email your receipt and confirmation shortly.</p>
      </div>
    );
  }

  const pay = () => {
    if (!cardRef.current) return;
    setState("paying"); setErrMsg("");
    cardRef.current.tokenize().then((r) => {
      if (r.status !== "OK") { setState("ready"); setErrMsg("Check the card details and try again."); return; }
      fetch("api.php?action=square-pay", {
        method: "POST",
        body: JSON.stringify({ sourceId: r.token, amount: Math.round(amount * 100), currency: c.payCurrency, note: note }),
      })
        .then((res) => res.json())
        .then((d) => { if (d.ok) setState("paid"); else { setState("ready"); setErrMsg(d.error || "The payment was declined."); } })
        .catch(() => { setState("ready"); setErrMsg("Connection problem — nothing was charged. Try again."); });
    });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10, maxWidth: 420, width: "100%" }}>
      <span style={{ font: "600 15px var(--font-body)", color: "var(--text-heading)" }}>Or pay the deposit by card</span>
      <div ref={boxRef}></div>
      {state === "loading" && <span style={{ font: "var(--type-small)", color: "var(--text-muted)" }}>Loading secure card form…</span>}
      {state === "error" && <span style={{ font: "var(--type-small)", color: "var(--text-muted)" }}>Card payments didn't load — we'll send payment details by email instead.</span>}
      {errMsg && <span style={{ font: "var(--type-small)", color: "var(--danger, #B4452E)" }}>{errMsg}</span>}
      {(state === "ready" || state === "paying") && (
        <div><BkButton size="lg" onClick={pay} disabled={state === "paying"}>{state === "paying" ? "Processing…" : `Pay ${c.currency}${amount.toFixed(2)} deposit`}</BkButton></div>
      )}
    </div>
  );
}

function Booking({ onHome }) {
  const c = window.VMContent.get();
  const [step, setStep] = React.useState(0);
  const [checkin, setCheckin] = React.useState("2026-08-28");
  const [nights, setNights] = React.useState(5);
  const [guests, setGuests] = React.useState(2);
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [notes, setNotes] = React.useState("");
  const steps = ["Dates & guests", "Your details", "Review & send", "Sent"];
  // Availability synced from the owners' Google Calendar
  const [busy, setBusy] = React.useState(null); // null = loading, {configured, set}
  React.useEffect(() => {
    window.VMContent.getAvailability().then((a) => setBusy({ configured: a.configured, set: new Set(a.busy) }));
  }, []);
  const dates = Array.from({ length: nights }, (_, i) => {
    const d = new Date(checkin + "T12:00:00");
    d.setDate(d.getDate() + i);
    return d.toISOString().slice(0, 10);
  });
  const perNight = dates.map((d) => window.VMContent.priceFor(d));
  const stay = perNight.reduce((s, p) => s + p, 0);
  const seasonal = perNight.some((p) => p !== perNight[0]);
  const total = stay + c.cleaning;
  const conflictDates = busy && busy.configured ? dates.filter((d) => busy.set.has(d)) : [];
  const conflict = conflictDates.length > 0;

  const [sending, setSending] = React.useState(false);
  const sendRequest = () => {
    setSending(true);
    window.VMContent.addGuest({
      name: name, email: email, checkin: checkin, nights: nights, guests: guests,
      notes: notes, total: `${c.currency}${total}`,
    }).then(() => { setSending(false); setStep(3); })
      .catch(() => { setSending(false); setStep(3); });
  };

  return (
    <div data-screen-label="Booking" style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "48px var(--container-pad) 0" }}>
      <button onClick={onHome} style={{ appearance: "none", background: "none", border: "none", padding: 0, font: "600 14px var(--font-body)", color: "var(--link)", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6 }}>
        <BkIcon name="arrow-left" size={16} /> Back to the house
      </button>
      <h1 style={{ font: "var(--type-h1)", margin: "16px 0 24px" }}>Book your stay</h1>
      <div style={{ display: "flex", gap: 28, marginBottom: 40, flexWrap: "wrap" }}>
        {steps.map((s, i) => <BkStep key={s} n={i + 1} label={s} state={i < step ? "done" : i === step ? "active" : "todo"} />)}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 40, alignItems: "start" }}>
        <div>
          {step === 0 && (
            <div className="vm-step" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <BkInput label="Check-in" type="date" value={checkin} onChange={(e) => setCheckin(e.target.value)} prefix={<BkIcon name="calendar" size={16} />} hint={`From ${c.checkIn}`} />
                <BkSelect label="Nights" value={`${nights}`} onChange={(e) => setNights(Number(e.target.value))}
                  options={["2", "3", "4", "5", "6", "7", "10", "14"].filter((n) => Number(n) >= c.minNights).map((n) => ({ value: n, label: `${n} nights` }))}
                  hint={`${c.minNights}-night minimum · check-out by ${c.checkOut}`} />
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
                <BkSelect label="Guests" value={`${guests}`} onChange={(e) => setGuests(Number(e.target.value))}
                  options={Array.from({ length: c.maxGuests }, (_, i) => ({ value: `${i + 1}`, label: `${i + 1} guest${i ? "s" : ""}` }))}
                  hint={`The house sleeps ${c.maxGuests} — no extra beds or cribs, sorry`} />
              </div>
              {busy && busy.configured && !conflict && (
                <p style={{ font: "var(--type-small)", color: "var(--secondary)", margin: 0, display: "flex", alignItems: "center", gap: 6 }}>
                  <BkIcon name="calendar-check" size={15} /> These dates are free on our calendar
                </p>
              )}
              {conflict && (
                <div style={{ background: "var(--surface-sunken)", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", padding: "14px 16px", font: "var(--type-body)", color: "var(--text-body)", display: "flex", gap: 10, alignItems: "flex-start" }}>
                  <span style={{ color: "var(--accent)", display: "inline-flex", marginTop: 2 }}><BkIcon name="calendar-x" size={18} /></span>
                  <span>Sorry — the house is already booked on {conflictDates.slice(0, 3).join(", ")}{conflictDates.length > 3 ? ` and ${conflictDates.length - 3} more night${conflictDates.length - 3 === 1 ? "" : "s"}` : ""}. Try shifting your dates.</span>
                </div>
              )}
              <div><BkButton size="lg" onClick={() => setStep(1)} disabled={conflict}>Continue</BkButton></div>
            </div>
          )}

          {step === 1 && (
            <div className="vm-step" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              <BkInput label="Your name" placeholder="Alex Papadopoulos" value={name} onChange={(e) => setName(e.target.value)} />
              <BkInput label="Email" type="email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} hint="Our reply and welcome notes go here" />
              <BkInput label="Anything we should know?" placeholder="Arrival time, questions…" value={notes} onChange={(e) => setNotes(e.target.value)} />
              <BkCheckbox label="I've read the house rules — no smoking, no pets, no parties" defaultChecked />
              <div style={{ display: "flex", gap: 12 }}>
                <BkButton variant="secondary" onClick={() => setStep(0)}>Back</BkButton>
                <BkButton size="lg" onClick={() => setStep(2)}>Review request</BkButton>
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="vm-step" style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              <div style={{ background: "var(--surface-sunken)", border: "1px solid var(--border-soft)", borderRadius: "var(--radius-md)", padding: 20, display: "flex", flexDirection: "column", gap: 6, font: "var(--type-body)" }}>
                <span><strong>{checkin}</strong> · {nights} nights · {guests} guest{guests === 1 ? "" : "s"}</span>
                <span>{name || "Your name"} · {email || "your email"}</span>
                {notes ? <span style={{ color: "var(--text-muted)" }}>"{notes}"</span> : null}
              </div>
              <p style={{ font: "var(--type-body)", color: "var(--text-body)", margin: 0, maxWidth: 480 }}>
                Sending this delivers your request straight to us — nothing else to do. We'll be in touch within 24 hours to confirm your dates.
              </p>
              <div style={{ display: "flex", gap: 12 }}>
                <BkButton variant="secondary" onClick={() => setStep(1)}>Back</BkButton>
                <BkButton size="lg" onClick={sendRequest} disabled={sending}>{sending ? "Sending…" : `Send request — then pay the ${c.depositPct}% deposit`}</BkButton>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="vm-step" style={{ display: "flex", flexDirection: "column", gap: 18, alignItems: "flex-start" }}>
              <BkBadge tone="success">Request received</BkBadge>
              <h2 style={{ font: "var(--type-h2)", margin: 0 }}>Thank you — we'll be in touch within 24 hours</h2>
              <p style={{ font: "var(--type-body-lg)", margin: 0, maxWidth: 520 }}>
                Your request is with us. We'll confirm your dates by email and send directions with our arrival notes. Check-in is from {c.checkIn}.
              </p>
              <p style={{ font: "var(--type-hand)", fontSize: 24, color: "var(--limewash-600)", margin: 0, transform: "rotate(-1.2deg)" }}>
                Keep an eye out for a little gift on your arrival. — Maria &amp; the family
              </p>
              <PayPalDeposit c={c} amount={total * c.depositPct / 100} note={`Villa Mesochori — booking deposit, ${checkin}, ${nights} nights`} />
              <SquareDeposit c={c} amount={total * c.depositPct / 100} note={`Villa Mesochori — booking deposit, ${checkin}, ${nights} nights`} />
              <div style={{ display: "flex", gap: 12 }}>
                <BkButton variant="secondary" onClick={onHome}>Back to the house</BkButton>
                <BkButton variant="ghost" onClick={() => setStep(0)}>Start another request</BkButton>
              </div>
            </div>
          )}
        </div>

        {step < 3 && <BkPrice c={c} nights={nights} guests={guests} stay={stay} seasonal={seasonal} />}
      </div>
    </div>
  );
}

window.VMBooking = Booking;
