// 5-step booking overlay
const { useMemo: _useMemo } = React;

const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const DAYS = ["Mo","Tu","We","Th","Fr","Sa","Su"];

function startOfMonth(y, m) { return new Date(y, m, 1); }
function daysInMonth(y, m) { return new Date(y, m + 1, 0).getDate(); }
function fmtDate(d) {
  if (!d) return "—";
  return d.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short" });
}
function nightsBetween(a, b) {
  if (!a || !b) return 0;
  return Math.round((b - a) / (1000 * 60 * 60 * 24));
}

function Calendar({ year, month, range, hover, onPick, onHover, onNav }) {
  const first = startOfMonth(year, month);
  // shift so Monday is first
  const startDay = (first.getDay() + 6) % 7;
  const days = daysInMonth(year, month);
  const cells = [];
  for (let i = 0; i < startDay; i++) cells.push(null);
  for (let d = 1; d <= days; d++) cells.push(new Date(year, month, d));
  const today = new Date(); today.setHours(0,0,0,0);

  return (
    <div className="cal">
      <h4>
        <span>{MONTHS[month]} {year}</span>
        <span className="nav-arrows">
          <button onClick={() => onNav(-1)}>‹</button>
          <button onClick={() => onNav(1)}>›</button>
        </span>
      </h4>
      <div className="cal-grid">
        {DAYS.map(d => <div className="dh" key={d}>{d}</div>)}
        {cells.map((d, i) => {
          if (!d) return <div key={i} />;
          const t = d.getTime();
          const disabled = d < today;
          let cls = "day";
          if (disabled) cls += " disabled";
          if (range[0] && range[0].getTime() === t) cls += " start";
          if (range[1] && range[1].getTime() === t) cls += " end";
          if (range[0] && range[1] && t > range[0].getTime() && t < range[1].getTime()) cls += " in-range";
          else if (range[0] && !range[1] && hover && t > range[0].getTime() && t < hover.getTime()) cls += " in-range";
          return (
            <div
              key={i}
              className={cls}
              onClick={() => !disabled && onPick(d)}
              onMouseEnter={() => !disabled && onHover(d)}
            >
              {d.getDate()}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function StepIndicator({ step }) {
  const steps = ["Dates", "Room", "Extras", "Guest", "Confirm"];
  return (
    <div className="steps">
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          <div className={`step ${i === step ? "active" : ""} ${i < step ? "done" : ""}`}>
            <span className="dot" />
            <span>0{i+1} {s}</span>
          </div>
          {i < steps.length - 1 && <div className="step-sep" />}
        </React.Fragment>
      ))}
    </div>
  );
}

function StepDates({ state, set }) {
  const [calY, setCalY] = useState(state.checkIn ? state.checkIn.getFullYear() : 2026);
  const [calM, setCalM] = useState(state.checkIn ? state.checkIn.getMonth() : 6);
  const [hover, setHover] = useState(null);

  const pick = (d) => {
    if (!state.checkIn || (state.checkIn && state.checkOut)) {
      set({ checkIn: d, checkOut: null });
    } else if (d > state.checkIn) {
      set({ checkOut: d });
    } else {
      set({ checkIn: d, checkOut: null });
    }
  };

  const nextY = calM === 11 ? calY + 1 : calY;
  const nextM = (calM + 1) % 12;

  const nights = nightsBetween(state.checkIn, state.checkOut);

  return (
    <div className="booking-screen">
      <div className="mono" style={{color:"var(--terracotta)",marginBottom:14}}>STEP 01 / 05</div>
      <h2>When would you like to come?</h2>
      <div className="sub">Pick check-in, then check-out. Minimum stay is two nights in high season.</div>

      <div className="date-layout">
        <div className="calendars">
          <Calendar
            year={calY} month={calM}
            range={[state.checkIn, state.checkOut]}
            hover={hover}
            onPick={pick}
            onHover={setHover}
            onNav={(dir) => {
              const nm = calM + dir;
              if (nm < 0) { setCalY(calY - 1); setCalM(11); }
              else if (nm > 11) { setCalY(calY + 1); setCalM(0); }
              else setCalM(nm);
            }}
          />
          <Calendar
            year={nextY} month={nextM}
            range={[state.checkIn, state.checkOut]}
            hover={hover}
            onPick={pick}
            onHover={setHover}
            onNav={(dir) => {
              const nm = calM + dir;
              if (nm < 0) { setCalY(calY - 1); setCalM(11); }
              else if (nm > 11) { setCalY(calY + 1); setCalM(0); }
              else setCalM(nm);
            }}
          />
        </div>

        <div className="date-side">
          <h4>Your stay</h4>
          <div className="summary-row">
            <span className="lbl">Check in</span>
            <span className="val">{fmtDate(state.checkIn)}</span>
          </div>
          <div className="summary-row">
            <span className="lbl">Check out</span>
            <span className="val">{fmtDate(state.checkOut)}</span>
          </div>
          <div className="summary-row">
            <span className="lbl">Nights</span>
            <span className="val">{nights || "—"}</span>
          </div>

          <h4 style={{marginTop: 36}}>Who's coming</h4>
          {[
            { k: "adults", t: "Adults", s: "13+", min: 1 },
            { k: "children", t: "Children", s: "3–12", min: 0 },
            { k: "infants", t: "Infants", s: "0–2", min: 0 }
          ].map(g => (
            <div className="guest-row" key={g.k}>
              <div className="t">{g.t}<small>{g.s}</small></div>
              <div className="stepper">
                <button disabled={state[g.k] <= g.min} onClick={() => set({ [g.k]: state[g.k] - 1 })}>−</button>
                <div className="v">{state[g.k]}</div>
                <button onClick={() => set({ [g.k]: state[g.k] + 1 })}>+</button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function StepRoom({ state, set }) {
  const allTypes = [];
  window.SK_DATA.buildings.forEach(b => {
    b.types.forEach(t => allTypes.push({ ...t, building: b.name, buildingId: b.id, hero: b.hero }));
  });
  const totalGuests = state.adults + state.children;
  const cats = ["All", ...new Set(allTypes.map(t => t.cat))];
  const [catFilter, setCatFilter] = useState("All");

  let listed = allTypes;
  if (catFilter !== "All") listed = listed.filter(t => t.cat === catFilter);
  // Move non-fitting to the end
  listed = [
    ...listed.filter(t => t.sleeps >= totalGuests && state.adults <= (t.maxAdults || t.sleeps)),
    ...listed.filter(t => !(t.sleeps >= totalGuests && state.adults <= (t.maxAdults || t.sleeps)))
  ];
  const fittingCount = allTypes.filter(t => t.sleeps >= totalGuests && state.adults <= (t.maxAdults || t.sleeps)).length;

  return (
    <div className="booking-screen">
      <div className="mono" style={{color:"var(--terracotta)",marginBottom:14}}>STEP 02 / 05</div>
      <h2>Choose your apartment.</h2>
      <div className="sub">{fittingCount} of {allTypes.length} apartment types fit {state.adults} adult{state.adults!==1 && "s"}{state.children?` + ${state.children} child${state.children!==1?"ren":""}`:""}.</div>

      <div className="gal-cats" style={{marginTop: 32, marginBottom: 8}}>
        {cats.map(c => (
          <button
            key={c}
            className={`gal-cat ${c === catFilter ? "on" : ""}`}
            onClick={() => setCatFilter(c)}
          >
            {c}
            <span className="ct">{c === "All" ? allTypes.length : allTypes.filter(t => t.cat === c).length}</span>
          </button>
        ))}
      </div>

      <div className="room-list">
        {listed.map((t, i) => {
          const fits = t.sleeps >= totalGuests && state.adults <= (t.maxAdults || t.sleeps);
          const sel = state.roomId === `${t.buildingId}-${t.code}`;
          return (
            <div
              className={`room-card ${sel ? "selected" : ""}`}
              key={`${t.buildingId}-${t.code}`}
              onClick={() => fits && set({ roomId: `${t.buildingId}-${t.code}`, roomName: t.name, roomBuilding: t.building, roomPrice: t.from })}
              style={{ opacity: fits ? 1 : 0.45, cursor: fits ? "pointer" : "not-allowed" }}
            >
              <div className="img"><img src={t.photos ? t.photos[0] : t.hero} alt={t.name} /></div>
              <div className="body">
                <div className="name">
                  {t.name}
                  <small>{t.cat} · {t.building} · {t.units}</small>
                </div>
                <div className="feats">
                  <span>{t.size} m²</span>
                  <span>·</span>
                  <span>Sleeps {t.sleeps}</span>
                  <span>·</span>
                  <span>Max {t.maxAdults || t.sleeps} adults</span>
                  <span>·</span>
                  <span>{t.code === "MZN" ? "3 levels" : t.code === "DUP" || t.code === "JRD" ? "Duplex" : "One level"}</span>
                </div>
                <div className="desc">
                  {t.code === "MZN" && "The biggest of the apartments — three levels of stone and timber, with a private roof terrace looking down the bay."}
                  {t.code === "DUP" && "Two-storey apartment with a bedroom upstairs and the main living space opening to the courtyard."}
                  {t.code === "1BR" && t.buildingId === "king" && "A compact one-bedroom with a small kitchen, terrace and the original stone walls."}
                  {t.code === "1BR" && t.buildingId === "prince" && "A compact one-bedroom on the Privé side — quietest part of the resort, kitchenette, private balcony."}
                  {t.code === "1BF" && "Same plan as the 1BR with an extra sofa-bed in the living room — for one child or a teenager."}
                  {t.code === "FAM" && "Family Studio with kitchen — open-plan, sofa bed, sleeps four. Soft-pastel walls, generous bathroom, garden view."}
                  {t.code === "JR1" && "Brand-new junior suite with kitchenette (not for cooking), marble bathroom and full-width balcony over the pool."}
                  {t.code === "JRD" && "The duplex junior suite — two floors, ideal for big families. Best view of the bay."}
                </div>
                <div className="chip-row">
                  {["Private balcony","A/C","Free Wi-Fi","Soundproof","Safe"].map(c => <span className="chip" key={c}>{c}</span>)}
                </div>
              </div>
              <div className="right">
                <div className="price">
                  <div className="from">From</div>
                  <div className="amt">€{t.from}</div>
                  <div className="per">/ night incl. tax</div>
                </div>
                <div className="btn" style={{borderColor: sel ? "var(--terracotta)" : "currentColor", color: sel ? "var(--terracotta)" : "inherit"}}>
                  {sel ? "Selected ✓" : fits ? "Select" : "Too small"}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

const EXTRAS = [
  { id: "breakfast", t: "Breakfast buffet", d: "Daily buffet in the new restaurant. Local bread, eggs to order, fruit from the garden, Greek yoghurt.", cap: "Most popular", price: 14, per: "person / day" },
  { id: "transfer", t: "Airport transfer", d: "Private car from Thessaloniki airport. Driver waits with a small sign. One car, up to three guests.", cap: "Logistics", price: 140, per: "one way" },
  { id: "boat", t: "Diaporos boat tour", d: "Three hours around the nine islets with Captain Stelios. Stops at two hidden coves. Snorkels provided.", cap: "Half-day", price: 65, per: "person" },
  { id: "late", t: "Late check-out", d: "Keep the room until 6pm on departure day. Subject to availability — we'll confirm 24h before.", cap: "Comfort", price: 35, per: "one-time" },
  { id: "yoga", t: "Yoga package", d: "Seven sessions across your stay with The Harpy. Mat, towel and water included; outdoor deck.", cap: "Wellness", price: 90, per: "person / week" },
  { id: "wine", t: "Welcome wine basket", d: "A bottle of Naoussa Xinomavro, local cheeses, olives and bread waiting in the room on arrival.", cap: "Arrival", price: 45, per: "one-time" }
];

function StepExtras({ state, set }) {
  const toggle = (id) => {
    const e = { ...state.extras };
    if (e[id]) delete e[id]; else e[id] = true;
    set({ extras: e });
  };
  return (
    <div className="booking-screen">
      <div className="mono" style={{color:"var(--terracotta)",marginBottom:14}}>STEP 03 / 05</div>
      <h2>Anything to add?</h2>
      <div className="sub">Optional. You can also arrange any of these once you arrive.</div>

      <div className="extras-grid">
        {EXTRAS.map(e => (
          <div key={e.id} className={`extra-card ${state.extras[e.id] ? "on" : ""}`} onClick={() => toggle(e.id)}>
            <div>
              <div className="cap">{e.cap}</div>
              <div className="t">{e.t}</div>
              <div className="d">{e.d}</div>
            </div>
            <div className="ec-right">
              <div className="toggle-dot" />
              <div className="ec-price" style={{color: state.extras[e.id] ? "var(--paper)" : "var(--ink)"}}>
                €{e.price}
                <small>{e.per}</small>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function StepGuest({ state, set }) {
  const update = (k) => (e) => set({ guest: { ...state.guest, [k]: e.target.value } });
  return (
    <div className="booking-screen">
      <div className="mono" style={{color:"var(--terracotta)",marginBottom:14}}>STEP 04 / 05</div>
      <h2>Just a few details.</h2>
      <div className="sub">We use these only for the booking. No newsletter unless you ask.</div>

      <div className="guest-layout">
        <div className="field-grid">
          <div className="field">
            <label>First name</label>
            <input type="text" value={state.guest.first} onChange={update("first")} placeholder="Alexandra" />
          </div>
          <div className="field">
            <label>Last name</label>
            <input type="text" value={state.guest.last} onChange={update("last")} placeholder="Papadopoulou" />
          </div>
          <div className="field">
            <label>Email</label>
            <input type="email" value={state.guest.email} onChange={update("email")} placeholder="alexandra@example.com" />
          </div>
          <div className="field">
            <label>Phone</label>
            <input type="tel" value={state.guest.phone} onChange={update("phone")} placeholder="+30 698 123 4567" />
          </div>
          <div className="field">
            <label>Country</label>
            <select value={state.guest.country} onChange={update("country")}>
              <option>Greece</option>
              <option>United Kingdom</option>
              <option>Germany</option>
              <option>France</option>
              <option>Netherlands</option>
              <option>Italy</option>
              <option>Other</option>
            </select>
          </div>
          <div className="field">
            <label>Arrival time</label>
            <select value={state.guest.arrival} onChange={update("arrival")}>
              <option>Before noon</option>
              <option>12:00 – 15:00</option>
              <option>15:00 – 18:00</option>
              <option>After 18:00</option>
              <option>Not sure yet</option>
            </select>
          </div>
          <div className="field full">
            <label>Special requests</label>
            <textarea value={state.guest.notes} onChange={update("notes")} placeholder="A cot for the baby, a bottle of wine for an anniversary, the apartment closest to the pool..." />
            <div className="hint">Anything we can do to make the room ready for you.</div>
          </div>
        </div>

        <ReviewSide state={state} />
      </div>
    </div>
  );
}

function ReviewSide({ state }) {
  const nights = nightsBetween(state.checkIn, state.checkOut) || 5;
  const room = (state.roomPrice || 145) * nights;
  const extraTotal = Object.keys(state.extras).reduce((s, id) => {
    const e = EXTRAS.find(x => x.id === id);
    if (!e) return s;
    if (e.per.includes("person / day")) return s + e.price * (state.adults + state.children) * nights;
    if (e.per.includes("person / week")) return s + e.price * (state.adults + state.children);
    if (e.per.includes("person")) return s + e.price * (state.adults + state.children);
    return s + e.price;
  }, 0);
  const taxes = Math.round((room + extraTotal) * 0.04);
  const total = room + extraTotal + taxes;

  return (
    <div className="review-side">
      <h4>Your stay</h4>
      <div className="review-row">
        <span>{state.roomName || "Select a room"}</span>
        <span>€{room}</span>
      </div>
      <div className="review-row">
        <span style={{color:"var(--muted)",fontSize:13}}>{fmtDate(state.checkIn)} → {fmtDate(state.checkOut)} · {nights}n</span>
        <span style={{color:"var(--muted)",fontSize:13}}>€{state.roomPrice || 145}/n</span>
      </div>

      {Object.keys(state.extras).length > 0 && (
        <>
          <h4 style={{marginTop:24}}>Extras</h4>
          {Object.keys(state.extras).map(id => {
            const e = EXTRAS.find(x => x.id === id);
            return (
              <div className="review-row" key={id}>
                <span>{e.t}</span>
                <span>€{e.price}</span>
              </div>
            );
          })}
        </>
      )}

      <div className="review-row" style={{marginTop:12}}>
        <span style={{color:"var(--muted)",fontSize:13}}>Tax & city fee (4%)</span>
        <span>€{taxes}</span>
      </div>
      <div className="review-row total">
        <span className="lbl">Total</span>
        <span className="val">€{total}</span>
      </div>
      <div style={{marginTop:14, fontSize:11, color:"var(--muted)", fontFamily:"JetBrains Mono, monospace", letterSpacing:"0.1em"}}>
        Pay 20% now · the rest on arrival
      </div>
    </div>
  );
}

function StepConfirm({ state, reset }) {
  const ref = "SK-" + Date.now().toString().slice(-6);
  const nights = nightsBetween(state.checkIn, state.checkOut) || 5;
  return (
    <div className="confirm">
      <div className="check">✓</div>
      <div className="mono" style={{color:"var(--terracotta)",marginBottom:14}}>RESERVATION HELD · 24 HOURS</div>
      <h2>Καλωσήρθατε,<br/><em>{state.guest.first || "guest"}</em>.</h2>
      <p>
        Your apartment is held. A confirmation went to <strong>{state.guest.email || "your email"}</strong> with the full details and a payment link for the 20% deposit. You can pay any time in the next twenty-four hours.
      </p>
      <div className="ref">REF / {ref}</div>

      <div className="policy-bar">
        <div className="pb-cell"><div className="lbl">Check-in</div><div className="val">15:00</div></div>
        <div className="pb-cell"><div className="lbl">Check-out</div><div className="val">11:00</div></div>
        <div className="pb-cell"><div className="lbl">Season</div><div className="val">May 1 — Sep 30</div></div>
        <div className="pb-cell"><div className="lbl">Nights</div><div className="val">{nights}</div></div>
      </div>
      <div style={{marginTop: 48, display: "flex", gap: 16, justifyContent: "center"}}>
        <button className="btn btn-solid" onClick={reset}>Make another reservation</button>
        <button className="btn">Add to calendar →</button>
      </div>

      <div style={{marginTop: 80, padding: 32, background: "var(--paper-2)", textAlign: "left"}}>
        <div className="mono" style={{color:"var(--terracotta)",marginBottom:14}}>WHILE YOU WAIT</div>
        <div style={{fontFamily: "Cormorant Garamond, serif", fontSize: 24, lineHeight: 1.4}}>
          The forecast for {fmtDate(state.checkIn)} is sunny, 28°C. Pack lighter than you think. We have everything you need at the bar.
        </div>
      </div>
    </div>
  );
}

function Booking({ open, close }) {
  const [step, setStep] = useState(0);
  const [state, setState] = useState({
    checkIn: new Date(2026, 6, 14),
    checkOut: new Date(2026, 6, 19),
    adults: 2, children: 0, infants: 0,
    roomId: null, roomName: null, roomBuilding: null, roomPrice: null,
    extras: { breakfast: true },
    guest: { first: "", last: "", email: "", phone: "", country: "Greece", arrival: "15:00 – 18:00", notes: "" }
  });

  const set = (patch) => setState(s => ({ ...s, ...patch }));
  const reset = () => { setStep(0); setState(s => ({ ...s, roomId: null, guest: { first: "", last: "", email: "", phone: "", country: "Greece", arrival: "15:00 – 18:00", notes: "" }})); };

  const nights = nightsBetween(state.checkIn, state.checkOut);
  const room = (state.roomPrice || 145) * (nights || 5);
  const extraTotal = Object.keys(state.extras).reduce((s, id) => {
    const e = EXTRAS.find(x => x.id === id);
    if (!e) return s;
    return s + e.price;
  }, 0);
  const taxes = Math.round((room + extraTotal) * 0.04);
  const total = room + extraTotal + taxes;

  const canAdvance = (() => {
    if (step === 0) return state.checkIn && state.checkOut && nights > 0;
    if (step === 1) return !!state.roomId;
    if (step === 3) return state.guest.first && state.guest.email;
    return true;
  })();

  return (
    <div className={`booking-overlay ${open ? "open" : ""}`}>
      <div className="booking-head">
        <div className="brand">
          <div className="mark">Simon King</div>
          <div className="loc">Reservations</div>
        </div>
        <StepIndicator step={step} />
        <button className="close" onClick={close}>Close <span style={{fontSize:16,lineHeight:0}}>×</span></button>
      </div>

      <div className="booking-body">
        {step === 0 && <StepDates state={state} set={set} />}
        {step === 1 && <StepRoom state={state} set={set} />}
        {step === 2 && <StepExtras state={state} set={set} />}
        {step === 3 && <StepGuest state={state} set={set} />}
        {step === 4 && <StepConfirm state={state} reset={reset} />}
      </div>

      {step < 4 && (
        <div className="booking-foot">
          <div className="foot-summary">
            <div>
              <div className="lbl">Total · 20% deposit now</div>
              <div className="v">€{total}<small> / €{Math.round(total * 0.2)} due</small></div>
            </div>
          </div>
          <div className="row">
            {step > 0 && <button className="btn" onClick={() => setStep(s => s - 1)}>← Back</button>}
            <button
              className="btn btn-solid"
              disabled={!canAdvance}
              style={{opacity: canAdvance ? 1 : 0.4, cursor: canAdvance ? "pointer" : "not-allowed"}}
              onClick={() => canAdvance && setStep(s => s + 1)}
            >
              {step === 3 ? "Confirm reservation" : "Continue"} →
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Booking });
