/* WEEKAWAY™ guest app prototype — HostOp portal flow, Solstice design system.
   Mock data only. No ID step. Fake door code 0000. */
const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

const SAMPLE = {
  brand: "WEEKAWAY™",
  property: "Sisters' Solstice",
  region: "Canmore · Alberta",
  address: "Sample Address · Canmore AB",
  checkIn: "Sat · Nov 8",
  checkInTime: "4:00 PM",
  checkOut: "Tue · Nov 11",
  checkOutTime: "10:00 AM",
  guests: 4,
  confirmation: "HMXXXXXXXX",
  doorCode: "0000",
  wifiNetwork: "WEEKAWAY-DEMO",
  wifiPassword: "demo-wifi-only",
  host: { name: "Philip", title: "Your host", avatar: "assets/host.jpg" },
  hero: "assets/header-canmore-opt.jpg",
  earlyPrice: 50,
  latePrice: 25,
  waiverPrice: 49,
};

/* Check-in steps mirror HostOp BOARDING_PASS_STEPS minus identity_verification */
const CHECKIN_STEPS = [
  { id: "guest_details", title: "Guest details", sub: "Who’s staying · arrival window" },
  { id: "damage_waiver", title: "Damage waiver", sub: "Optional · clear opt-out" },
  { id: "house_rules", title: "House rules", sub: "Review and agree" },
];

const ToastCtx = createContext(() => {});
function ToastProvider({ children }) {
  const [msg, setMsg] = useState(null);
  const timer = useRef(null);
  const show = useCallback((text) => {
    setMsg(text);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setMsg(null), 1600);
  }, []);
  return (
    <ToastCtx.Provider value={show}>
      {children}
      <div className={"toast" + (msg ? " show" : "")} role="status">
        <Icon name="check" size={15} stroke={2.2} />
        <span>{msg}</span>
      </div>
    </ToastCtx.Provider>
  );
}
const useToast = () => useContext(ToastCtx);

function Icon({ name, size = 22, stroke = 1.5, className = "", style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    if (!ref.current || !window.lucide) return;
    ref.current.innerHTML = "";
    const i = document.createElement("i");
    i.setAttribute("data-lucide", name);
    ref.current.appendChild(i);
    window.lucide.createIcons({
      attrs: { width: size, height: size, "stroke-width": stroke },
      nameAttr: "data-lucide",
    });
  }, [name, size, stroke]);
  return (
    <span ref={ref} className={"ic " + className} style={{ display: "inline-flex", width: size, height: size, ...style }} />
  );
}

function RevealField({ label, value }) {
  const toast = useToast();
  const [revealed, setRevealed] = useState(false);
  const [hit, setHit] = useState(false);
  return (
    <button
      className={"revealfield" + (revealed ? " revealed" : "") + (hit ? " hit" : "")}
      type="button"
      onClick={() => {
        if (!revealed) { setRevealed(true); return; }
        navigator.clipboard?.writeText(value);
        setHit(true); toast("Copied");
        setTimeout(() => setHit(false), 1200);
      }}
    >
      <span className="text">
        <span className="cap">{label}</span>
        <span className="value">{revealed ? value : "• • • •"}</span>
      </span>
      <span className="hint">
        <Icon name={hit ? "check" : revealed ? "copy" : "eye"} size={16} stroke={1.8} />
        {hit ? "Copied" : revealed ? "Tap to copy" : "Tap to reveal"}
      </span>
    </button>
  );
}

function CopyField({ label, value }) {
  const toast = useToast();
  return (
    <button className="revealfield" type="button" onClick={() => { navigator.clipboard?.writeText(value); toast("Copied"); }}>
      <span className="text">
        <span className="cap">{label}</span>
        <span className="value" style={{ letterSpacing: "0.02em", fontSize: 17 }}>{value}</span>
      </span>
      <span className="hint"><Icon name="copy" size={16} stroke={1.8} /> Tap to copy</span>
    </button>
  );
}

function TopBar({ title, onBack }) {
  return (
    <div className="topbar">
      {onBack ? (
        <button className="topbar-icon" type="button" onClick={onBack} aria-label="Back">
          <Icon name="arrow-left" size={20} />
        </button>
      ) : <span className="topbar-spacer" />}
      <span className="topbar-title">{title}</span>
      <span className="topbar-spacer" />
    </div>
  );
}

function StayDatesCard() {
  return (
    <div className="stay-card">
      <div className="stay-row">
        <div className="stay-half">
          <div className="stay-ic"><Icon name="log-in" size={18} /></div>
          <div>
            <div className="stay-k">Check-in</div>
            <div className="stay-v">{SAMPLE.checkIn}</div>
            <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{SAMPLE.checkInTime}</div>
          </div>
        </div>
        <div className="stay-div" />
        <div className="stay-half">
          <div className="stay-ic"><Icon name="log-out" size={18} /></div>
          <div>
            <div className="stay-k">Check-out</div>
            <div className="stay-v">{SAMPLE.checkOut}</div>
            <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{SAMPLE.checkOutTime}</div>
          </div>
        </div>
      </div>
      <div className="stay-note">
        <Icon name="map-pin" size={16} />
        <span>{SAMPLE.address}</span>
      </div>
    </div>
  );
}

/* ========== 1. Validate booking ========== */
function VerifyScreen({ onVerify }) {
  const [last, setLast] = useState("");
  const [code, setCode] = useState("");
  return (
    <div className="screen">
      <div className="screen-pad">
        <div className="verify-brand">
          <img src="assets/weekaway-logo.svg" alt="WEEKAWAY™" />
          <div className="eyebrow">Guest portal · Prototype</div>
          <h1 className="display">Find your stay</h1>
          <p className="lead">
            Confirm your booking to open check-in for {SAMPLE.property}.
          </p>
        </div>
        <div className="stack-lg" style={{ marginTop: 28 }}>
          <div className="field">
            <label>Last name</label>
            <input value={last} onChange={(e) => setLast(e.target.value)} placeholder="As on your reservation" />
          </div>
          <div className="field">
            <label>Confirmation code</label>
            <input value={code} onChange={(e) => setCode(e.target.value)} placeholder="e.g. HMXXXXXXXX" autoCapitalize="characters" />
          </div>
          <button className="btn btn-primary" type="button" onClick={() => onVerify()}>
            Continue to check-in
          </button>
          <div className="note">
            <Icon name="shield-check" size={18} />
            <div className="note-text">Demo only — any name and code opens the prototype. No live booking lookup.</div>
          </div>
        </div>
        <div className="footer-mark">WEEKAWAY™ · Sample data · Not live</div>
      </div>
    </div>
  );
}

/* ========== HostOp-style locked portal home with progress ========== */
function CheckInHub({ done, onOpenStep, guestName }) {
  const completed = CHECKIN_STEPS.filter((s) => done[s.id]).length;
  const next = CHECKIN_STEPS.find((s) => !done[s.id]);
  return (
    <div className="screen">
      <div className="hero-band" style={{ backgroundImage: `url(${SAMPLE.hero})`, minHeight: 200 }}>
        <div className="scrim" />
        <div className="inner">
          <div className="eyebrow">{SAMPLE.region}</div>
          <h1 className="display" style={{ fontSize: 32 }}>{SAMPLE.property}</h1>
          <p className="lead">
            {guestName ? `Welcome, ${guestName}.` : "Welcome."} Your stay starts soon — let’s get you ready.
          </p>
        </div>
      </div>
      <div className="screen-pad tight">
        <div className="stack-lg">
          <StayDatesCard />

          <div className="lock-callout">
            <Icon name="lock" size={20} />
            <div>
              <div className="lock-callout-title">Your entry instructions are locked</div>
              <div className="lock-callout-text">
                Complete check-in to unlock how to get in, Wi-Fi, and arrival instructions.
              </div>
            </div>
          </div>

          <div className="progress-card">
            <div className="progress-head">
              <span className="progress-label">Check-in progress</span>
              <span className="progress-count">{completed} of {CHECKIN_STEPS.length} complete</span>
            </div>
            <div className="progress-bar" style={{ marginBottom: 8 }}>
              <span style={{ width: `${(completed / CHECKIN_STEPS.length) * 100}%` }} />
            </div>
            <div className="progress-list">
              {CHECKIN_STEPS.map((s, i) => {
                const isDone = !!done[s.id];
                const isCurrent = next && next.id === s.id;
                return (
                  <button
                    key={s.id}
                    type="button"
                    className={"progress-step" + (isDone ? " done" : "") + (isCurrent ? " current" : "")}
                    onClick={() => !isDone && onOpenStep(s.id)}
                  >
                    <span className="ps-num">{isDone ? "✓" : i + 1}</span>
                    <span className="ps-body">
                      <span className="ps-title">{s.title}</span>
                      <span className="ps-sub">{isDone ? "Done" : s.sub}</span>
                    </span>
                    {!isDone && <Icon name="chevron-right" size={18} className="ps-chev" />}
                  </button>
                );
              })}
            </div>
          </div>

          {next && (
            <button className="btn btn-primary" type="button" onClick={() => onOpenStep(next.id)}>
              Continue check-in →
            </button>
          )}

          <div className="section-label">Coming after check-in</div>
          <div className="portal-grid">
            {[
              ["wifi", "Wi-Fi"],
              ["map", "Directions"],
              ["key-round", "Door code"],
            ].map(([icon, label]) => (
              <div key={label} className="navcard" style={{ opacity: 0.55, cursor: "default" }}>
                <span className="navcard-ic"><Icon name={icon} size={20} /></span>
                <span className="navcard-text">
                  <span className="navcard-title">{label}</span>
                  <span className="navcard-desc">Unlocks when check-in is complete</span>
                </span>
                <Icon name="lock" size={16} className="navcard-chev" />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ========== 2. Guest details ========== */
function GuestDetailsScreen({ initial, onSave, onSkip, onBack }) {
  const [fullName, setFullName] = useState(initial.fullName || "");
  const [eta, setEta] = useState(initial.eta || "");
  const etas = [
    { id: "before4", label: "Before 4 PM" },
    { id: "4to6", label: "4 – 6 PM" },
    { id: "after6", label: "After 6 PM" },
    { id: "unsure", label: "Not sure yet" },
  ];
  return (
    <div className="screen">
      <TopBar title="Guest details" onBack={onBack} />
      <div className="screen-pad">
        <div className="step-meta">
          <span className="step-pill">Step 1 of 3</span>
        </div>
        <h1 className="display" style={{ fontSize: 30 }}>Who’s staying?</h1>
        <p className="lead">Tell us the primary guest name and when you plan to arrive.</p>
        <div className="stack-lg" style={{ marginTop: 20 }}>
          <div className="field">
            <label>Full name</label>
            <input value={fullName} onChange={(e) => setFullName(e.target.value)} placeholder="Primary guest" />
          </div>
          <div>
            <div className="cap" style={{ marginBottom: 8 }}>Estimated arrival</div>
            <div className="eta-grid">
              {etas.map((e) => (
                <button key={e.id} type="button" className={"eta-opt" + (eta === e.id ? " on" : "")} onClick={() => setEta(e.id)}>
                  {e.label}
                </button>
              ))}
            </div>
          </div>
          <button
            className="btn btn-primary"
            type="button"
            onClick={() => onSave({ fullName: fullName.trim() || "Guest", eta: eta || "unsure" })}
          >
            Save and continue
          </button>
          <button className="btn btn-ghost" type="button" onClick={onSkip} style={{ width: "100%", justifyContent: "center" }}>
            Skip for now
          </button>
        </div>
      </div>
    </div>
  );
}

/* ========== 3. Damage waiver ========== */
function WaiverScreen({ onPaid, onOptOut, onBack }) {
  const [checked, setChecked] = useState(false);
  return (
    <div className="screen">
      <TopBar title="Damage waiver" onBack={onBack} />
      <div className="screen-pad">
        <div className="step-meta">
          <span className="step-pill">Step 2 of 3</span>
        </div>
        <h1 className="display" style={{ fontSize: 30 }}>Optional damage waiver</h1>
        <p className="lead">
          Add a damage waiver for accidental damage during your stay, or continue without it. Opting out is a normal choice.
        </p>
        <div className="stack-lg" style={{ marginTop: 20 }}>
          <button type="button" className={"waiver-opt" + (checked ? " on" : "")} onClick={() => setChecked((c) => !c)}>
            <span className="checkbox">{checked ? <Icon name="check" size={14} stroke={2.4} /> : null}</span>
            <span>
              <strong style={{ display: "block", fontSize: 16, marginBottom: 4 }}>
                Damage waiver · CA${SAMPLE.waiverPrice}
              </strong>
              <span className="muted">Recommended. Unticked by default. Not required to finish check-in.</span>
            </span>
          </button>
          {checked && (
            <button className="btn btn-pay" type="button" onClick={onPaid}>
              <Icon name="smartphone" size={18} /> Pay with Apple Pay / Google Pay
            </button>
          )}
          <button className="btn btn-secondary" type="button" onClick={onOptOut}>
            No thanks — continue without a waiver
          </button>
          <div className="note">
            <Icon name="info" size={18} />
            <div className="note-text">Prototype mock. Copy avoids restricted words. Lawyer and broker review still pending.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ========== 4. House rules ========== */
function HouseRulesScreen({ onAgree, onSkip, onBack }) {
  const [agreed, setAgreed] = useState(false);
  const rules = [
    ["moon", "Quiet hours", "10 PM – 8 AM. Keep voices and music considerate."],
    ["ban", "No parties", "No events or large gatherings."],
    ["cigarette-off", "No smoking", "Including cannabis, indoors or on decks."],
    ["paw-print", "Pets", "Only if approved on your booking."],
  ];
  return (
    <div className="screen">
      <TopBar title="House rules" onBack={onBack} />
      <div className="screen-pad">
        <div className="step-meta">
          <span className="step-pill">Step 3 of 3</span>
        </div>
        <h1 className="display" style={{ fontSize: 30 }}>Review house rules</h1>
        <p className="lead">Please read these before we unlock your stay.</p>
        <div className="card" style={{ marginTop: 16 }}>
          {rules.map(([icon, title, text]) => (
            <div className="rule" key={title}>
              <Icon name={icon} size={18} />
              <div>
                <div className="rule-title">{title}</div>
                <div className="rule-text">{text}</div>
              </div>
            </div>
          ))}
        </div>
        <div className="stack-lg" style={{ marginTop: 16 }}>
          <button type="button" className={"rules-agree" + (agreed ? " on" : "")} onClick={() => setAgreed((a) => !a)}>
            <span className="checkbox">{agreed ? <Icon name="check" size={14} stroke={2.4} /> : null}</span>
            <span className="muted" style={{ color: "var(--ink)" }}>I agree to the house rules for this stay.</span>
          </button>
          <button className="btn btn-primary" type="button" disabled={!agreed} onClick={onAgree}>
            Agree and finish check-in
          </button>
          <button className="btn btn-ghost" type="button" onClick={onSkip} style={{ width: "100%", justifyContent: "center" }}>
            Skip for now
          </button>
        </div>
      </div>
    </div>
  );
}

/* ========== Confirmation (HostOp-style) ========== */
function ConfirmationScreen({ onHome, unlocked }) {
  return (
    <div className="screen">
      <div className="screen-pad">
        <div className="verify-brand" style={{ paddingTop: 40 }}>
          <div className="eyebrow">Check-in complete</div>
          <h1 className="display">You’re all set</h1>
          <p className="lead">
            {unlocked
              ? "Entry details are ready. Door code, Wi-Fi, and arrival steps are in your stay portal."
              : "Entry details unlock closer to check-in. You’ll still get the normal Airbnb message 24 hours before arrival."}
          </p>
        </div>
        <div className="stack-lg" style={{ marginTop: 24 }}>
          <div className={"lock-callout" + (unlocked ? " ready" : "")}>
            <Icon name={unlocked ? "circle-check" : "timer"} size={20} />
            <div>
              <div className="lock-callout-title">{unlocked ? "Entry ready" : "Door code unlocks closer to arrival"}</div>
              <div className="lock-callout-text">
                {unlocked
                  ? "Tap below to open your stay home."
                  : "Available about 24 hours before check-in · sample countdown in the portal."}
              </div>
            </div>
          </div>
          <button className="btn btn-primary" type="button" onClick={onHome}>
            Go to your stay
          </button>
        </div>
      </div>
    </div>
  );
}

/* ========== Unlocked stay portal (HostOp sections) ========== */
function StayPortal({ guestName, onNav, upsellState, onBuy, earlyPurchased, latePurchased }) {
  return (
    <div className="screen">
      <div className="hero-band" style={{ backgroundImage: `url(${SAMPLE.hero})`, minHeight: 200 }}>
        <div className="scrim" />
        <div className="inner">
          <div className="eyebrow">Your stay · WEEKAWAY™</div>
          <h1 className="display" style={{ fontSize: 32 }}>
            {guestName ? `Hi ${guestName.split(" ")[0]}` : "Welcome"}
          </h1>
          <p className="lead">{SAMPLE.property} · {SAMPLE.checkIn} → {SAMPLE.checkOut}</p>
        </div>
      </div>
      <div className="screen-pad tight">
        <div className="stack-lg">
          <div className="codecard">
            <span className="cap">Front door code</span>
            <div className="codecard-rule">Tap below to reveal</div>
            <div style={{ marginTop: 8 }}>
              <button
                type="button"
                className="btn btn-secondary"
                style={{ background: "rgba(255,255,255,0.12)", color: "#fff", borderColor: "rgba(255,255,255,0.2)" }}
                onClick={() => onNav("door")}
              >
                View door code
              </button>
            </div>
          </div>

          <div className="section-label">Getting in</div>
          <div className="portal-grid">
            <button className="navcard" type="button" onClick={() => onNav("door")}>
              <span className="navcard-ic"><Icon name="key-round" size={20} /></span>
              <span className="navcard-text">
                <span className="navcard-title">Door code</span>
                <span className="navcard-desc">Tap to reveal · sample only</span>
              </span>
              <Icon name="chevron-right" size={18} className="navcard-chev" />
            </button>
            <button className="navcard" type="button" onClick={() => onNav("arrival")}>
              <span className="navcard-ic"><Icon name="map" size={20} /></span>
              <span className="navcard-text">
                <span className="navcard-title">Arrival guide</span>
                <span className="navcard-desc">Step-by-step entry</span>
              </span>
              <Icon name="chevron-right" size={18} className="navcard-chev" />
            </button>
            <button className="navcard" type="button" onClick={() => onNav("wifi")}>
              <span className="navcard-ic"><Icon name="wifi" size={20} /></span>
              <span className="navcard-text">
                <span className="navcard-title">Wi-Fi</span>
                <span className="navcard-desc">Network + password</span>
              </span>
              <Icon name="chevron-right" size={18} className="navcard-chev" />
            </button>
            <button className="navcard" type="button" onClick={() => onNav("wallet")}>
              <span className="navcard-ic"><Icon name="wallet" size={20} /></span>
              <span className="navcard-text">
                <span className="navcard-title">Add to Wallet</span>
                <span className="navcard-desc">Stay times + door code</span>
              </span>
              <Icon name="chevron-right" size={18} className="navcard-chev" />
            </button>
          </div>

          <div className="section-label">Enhance your stay</div>
          <UpsellCard kind="early" state={earlyPurchased ? "purchased" : upsellState.early} onBuy={onBuy} />
          <UpsellCard kind="late" state={latePurchased ? "purchased" : upsellState.late} onBuy={onBuy} />

          <div className="section-label">During your stay</div>
          <div className="portal-grid">
            {[
              ["book-open", "Home guide", "Appliances & how-tos", "guide"],
              ["compass", "Local guide", "Canmore picks", "local"],
              ["cross", "Nearby essentials", "ATM · grocery · pharmacy", "essentials"],
              ["calendar-plus", "Extend stay", "Request extra nights", "extend"],
              ["receipt", "Receipts", "Waiver & upsells", "receipts"],
              ["circle-check", "Check-out", "Departure checklist", "checkout"],
            ].map(([icon, title, desc, id]) => (
              <button key={id} className="navcard" type="button" onClick={() => onNav(id)}>
                <span className="navcard-ic"><Icon name={icon} size={20} /></span>
                <span className="navcard-text">
                  <span className="navcard-title">{title}</span>
                  <span className="navcard-desc">{desc}</span>
                </span>
                <Icon name="chevron-right" size={18} className="navcard-chev" />
              </button>
            ))}
          </div>

          <div className="host-row">
            <img src={SAMPLE.host.avatar} alt="" />
            <span className="by">Hosted by {SAMPLE.host.name} · Text anytime</span>
          </div>
        </div>
      </div>
    </div>
  );
}

function UpsellCard({ kind, state, onBuy }) {
  const isEarly = kind === "early";
  const title = isEarly ? "Early check-in" : "Late checkout";
  const price = isEarly ? SAMPLE.earlyPrice : SAMPLE.latePrice;
  const detail = isEarly
    ? "Arrive from noon on check-in day (normal 4:00 PM)."
    : "Check out at 11:00 AM (normal 10:00 AM). Hard maximum.";
  if (state === "checkback") {
    return (
      <div className="upsell checkback">
        <div className="upsell-head">
          <div>
            <span className="badge badge-muted">Check back</span>
            <div className="upsell-title">{title}</div>
          </div>
          <span className="upsell-price">—</span>
        </div>
        <p className="muted" style={{ margin: 0 }}>
          {isEarly ? "Check back on Nov 7 at 4:00 PM if the night before is still free." : "Check back on Nov 10 if no one arrives that day."}
        </p>
      </div>
    );
  }
  if (state === "unavailable") {
    return (
      <div className="upsell unavailable">
        <div className="upsell-head">
          <div>
            <span className="badge badge-warn">Not available</span>
            <div className="upsell-title">{title}</div>
          </div>
          <span className="upsell-price">—</span>
        </div>
        <p className="muted" style={{ margin: 0 }}>Not available for this stay.</p>
      </div>
    );
  }
  if (state === "purchased") {
    return (
      <div className="upsell purchased">
        <div className="upsell-head">
          <div>
            <span className="badge badge-ok">Purchased</span>
            <div className="upsell-title">{title}</div>
          </div>
          <span className="upsell-price">CA${price}</span>
        </div>
        <p className="muted" style={{ margin: 0 }}>Host notified so cleaners can be told.</p>
      </div>
    );
  }
  return (
    <div className="upsell available">
      <div className="upsell-head">
        <div>
          <span className="badge badge-accent">Available</span>
          <div className="upsell-title">{title}</div>
        </div>
        <span className="upsell-price">CA${price}</span>
      </div>
      <p className="muted" style={{ margin: 0 }}>{detail}</p>
      <button className="btn btn-primary" type="button" onClick={() => onBuy(kind)} style={{ marginTop: 4 }}>
        Add {isEarly ? "early check-in" : "late checkout"}
      </button>
    </div>
  );
}

function DoorCodeScreen({ onBack }) {
  return (
    <div className="screen">
      <TopBar title="Door code" onBack={onBack} />
      <div className="screen-pad">
        <div className="eyebrow">Unlocked</div>
        <h1 className="display" style={{ fontSize: 30 }}>Front door</h1>
        <p className="lead">Sample code only — not a real lock PIN.</p>
        <div className="stack-lg" style={{ marginTop: 18 }}>
          <RevealField label="Front door code" value={SAMPLE.doorCode} />
          <div className="card">
            <div className="cap">Address</div>
            <div className="sub-h" style={{ fontSize: 18 }}>{SAMPLE.address}</div>
            <p className="muted" style={{ margin: "8px 0 0" }}>Keypad on the front door. Press checkmark after the code.</p>
          </div>
        </div>
      </div>
    </div>
  );
}

function ArrivalGuideScreen({ onBack }) {
  const [done, setDone] = useState({});
  const steps = [
    { id: "find", title: "Find the home", text: "Pull into the driveway. Exterior lights welcome you after dusk." },
    { id: "park", title: "Park", text: "Use the driveway spaces. Leave street access clear." },
    { id: "lock", title: "Unlock the front door", text: "Enter the door code on the keypad, then press the checkmark." },
    { id: "inside", title: "Inside", text: "Wi-Fi details are under Wi-Fi in your stay portal." },
  ];
  return (
    <div className="screen">
      <TopBar title="Arrival guide" onBack={onBack} />
      <div className="screen-pad">
        <h1 className="display" style={{ fontSize: 30 }}>Getting in</h1>
        <div className="stack" style={{ marginTop: 16 }}>
          <RevealField label="Front door code" value={SAMPLE.doorCode} />
          <ol className="steps">
            {steps.map((s, i) => (
              <li key={s.id}>
                <button type="button" className={"step" + (done[s.id] ? " done" : "")} onClick={() => setDone((d) => ({ ...d, [s.id]: !d[s.id] }))}>
                  <span className="step-num">{done[s.id] ? "✓" : i + 1}</span>
                  <span className="step-body">
                    <span className="step-title">{s.title}</span>
                    <span className="step-text">{s.text}</span>
                  </span>
                </button>
              </li>
            ))}
          </ol>
        </div>
      </div>
    </div>
  );
}

function WifiScreen({ onBack }) {
  return (
    <div className="screen">
      <TopBar title="Wi-Fi" onBack={onBack} />
      <div className="screen-pad">
        <div className="stack">
          <CopyField label="Network" value={SAMPLE.wifiNetwork} />
          <RevealField label="Password" value={SAMPLE.wifiPassword} />
          <div className="note"><Icon name="info" size={18} /><div className="note-text">Demo credentials only.</div></div>
        </div>
      </div>
    </div>
  );
}

function WalletScreen({ onBack }) {
  const toast = useToast();
  return (
    <div className="screen">
      <TopBar title="Wallet pass" onBack={onBack} />
      <div className="screen-pad">
        <div className="card" style={{ background: "linear-gradient(160deg,#1F3326,#2f4a38)", color: "#fff", border: "none", padding: 22 }}>
          <img src="assets/weekaway-logo-reverse.svg" alt="" style={{ height: 22, marginBottom: 18 }} />
          <div className="cap" style={{ color: "rgba(255,255,255,0.55)" }}>Your stay at</div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 26, marginTop: 4 }}>{SAMPLE.property}</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 22 }}>
            <div>
              <div className="cap" style={{ color: "rgba(255,255,255,0.55)" }}>Check in</div>
              <div style={{ marginTop: 4 }}>{SAMPLE.checkIn}<br />{SAMPLE.checkInTime}</div>
            </div>
            <div>
              <div className="cap" style={{ color: "rgba(255,255,255,0.55)" }}>Check out</div>
              <div style={{ marginTop: 4 }}>{SAMPLE.checkOut}<br />{SAMPLE.checkOutTime}</div>
            </div>
          </div>
          <div style={{ marginTop: 18 }}>
            <div className="cap" style={{ color: "rgba(255,255,255,0.55)" }}>Door code</div>
            <div style={{ fontSize: 22, letterSpacing: "0.18em", marginTop: 6, fontWeight: 500 }}>0000</div>
          </div>
        </div>
        <div className="stack" style={{ marginTop: 16 }}>
          <button className="btn btn-wallet" type="button" onClick={() => toast("Mock — Apple Wallet not connected")}>Add to Apple Wallet</button>
          <button className="btn btn-secondary" type="button" onClick={() => toast("Mock — Google Wallet not connected")}>Save to Google Wallet</button>
        </div>
      </div>
    </div>
  );
}

function SimpleListScreen({ title, onBack, items }) {
  return (
    <div className="screen">
      <TopBar title={title} onBack={onBack} />
      <div className="screen-pad">
        <div className="card">
          {items.map(([icon, t, m]) => (
            <div className="local-item" key={t}>
              <span className="local-ic"><Icon name={icon} size={18} /></span>
              <div>
                <div className="local-title">{t}</div>
                <div className="local-meta">{m}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function CheckoutScreen({ onBack }) {
  const [done, setDone] = useState({});
  const tasks = [
    { id: "dishes", title: "Run the dishwasher", text: "Or leave dirty dishes stacked inside." },
    { id: "trash", title: "Take out trash", text: "Bins at the side of the driveway." },
    { id: "towels", title: "Leave towels in the tub", text: "Used towels in the bathtub is perfect." },
    { id: "thermo", title: "Set thermostat to 18°C", text: "Help us keep energy use low." },
    { id: "lock", title: "Lock the door behind you", text: "The keypad locks automatically." },
  ];
  return (
    <div className="screen">
      <TopBar title="Check-out" onBack={onBack} />
      <div className="screen-pad">
        <div className="eyebrow">Departure · {SAMPLE.checkOutTime}</div>
        <h1 className="display" style={{ fontSize: 30 }}>Before you go</h1>
        <p className="lead">{Object.values(done).filter(Boolean).length} of {tasks.length} tasks</p>
        <ol className="steps" style={{ marginTop: 16 }}>
          {tasks.map((t, i) => (
            <li key={t.id}>
              <button type="button" className={"step" + (done[t.id] ? " done" : "")} onClick={() => setDone((d) => ({ ...d, [t.id]: !d[t.id] }))}>
                <span className="step-num">{done[t.id] ? "✓" : i + 1}</span>
                <span className="step-body">
                  <span className="step-title">{t.title}</span>
                  <span className="step-text">{t.text}</span>
                </span>
              </button>
            </li>
          ))}
        </ol>
      </div>
    </div>
  );
}

function ExtendScreen({ onBack }) {
  const toast = useToast();
  return (
    <div className="screen">
      <TopBar title="Extend stay" onBack={onBack} />
      <div className="screen-pad">
        <h1 className="display" style={{ fontSize: 30 }}>Stay longer?</h1>
        <p className="lead">Current checkout {SAMPLE.checkOut} · {SAMPLE.checkOutTime}. We’ll check availability first.</p>
        <div className="stack-lg" style={{ marginTop: 20 }}>
          <div className="card">
            <div className="cap">Request new checkout</div>
            <div className="sub-h" style={{ fontSize: 18 }}>Pick a date (mock)</div>
            <p className="muted" style={{ margin: "8px 0 0" }}>No charge until the host approves. OTA guests: request through the booking channel.</p>
          </div>
          <button className="btn btn-primary" type="button" onClick={() => toast("Mock — availability check")}>Check availability</button>
        </div>
      </div>
    </div>
  );
}

function ReceiptsScreen({ onBack }) {
  return (
    <div className="screen">
      <TopBar title="Receipts" onBack={onBack} />
      <div className="screen-pad">
        <div className="card" style={{ textAlign: "center", padding: 28 }}>
          <Icon name="receipt" size={28} style={{ color: "var(--sage)", margin: "0 auto 12px" }} />
          <div className="sub-h">No charges yet</div>
          <p className="muted" style={{ margin: "8px 0 0" }}>Waiver and upsell receipts will show here.</p>
        </div>
      </div>
    </div>
  );
}

/* ========== Shells + root ========== */
function DevBar({ screen, setScreen, upsellPreset, setUpsellPreset, resetCheckin }) {
  return (
    <div className="devbar">
      <label>Screen</label>
      <select value={screen} onChange={(e) => setScreen(e.target.value)}>
        <option value="verify">1 · Validate booking</option>
        <option value="hub">2 · Check-in hub (locked)</option>
        <option value="guest_details">3 · Guest details</option>
        <option value="damage_waiver">4 · Damage waiver</option>
        <option value="house_rules">5 · House rules</option>
        <option value="confirmation">6 · Confirmation</option>
        <option value="stay">7 · Stay portal</option>
        <option value="door">Door code</option>
        <option value="arrival">Arrival guide</option>
        <option value="wifi">Wi-Fi</option>
        <option value="wallet">Wallet</option>
        <option value="checkout">Check-out</option>
        <option value="enhance">Enhance only</option>
      </select>
      <label>Upsells</label>
      <select value={upsellPreset} onChange={(e) => setUpsellPreset(e.target.value)}>
        <option value="checkback">Check back</option>
        <option value="available">Available</option>
        <option value="purchased">Purchased</option>
        <option value="unavailable">Unavailable</option>
      </select>
      <button type="button" onClick={resetCheckin}>Reset check-in</button>
      <span className="tag">DEV · HostOp flow</span>
    </div>
  );
}

const DT_NAV = [
  { id: "verify", icon: "log-in", label: "Validate" },
  { id: "hub", icon: "list-checks", label: "Check-in hub" },
  { id: "guest_details", icon: "user", label: "Guest details" },
  { id: "damage_waiver", icon: "shield", label: "Damage waiver" },
  { id: "house_rules", icon: "scroll-text", label: "House rules" },
  { id: "confirmation", icon: "circle-check", label: "Confirmation" },
  { id: "stay", icon: "house", label: "Stay portal" },
  { id: "door", icon: "key-round", label: "Door code" },
  { id: "arrival", icon: "map", label: "Arrival guide" },
  { id: "enhance", icon: "sparkles", label: "Enhance" },
  { id: "checkout", icon: "log-out", label: "Check-out" },
];

function DesktopShell({ screen, setScreen, children }) {
  return (
    <div className="dt-root">
      <aside className="dt-sidebar">
        <div className="dt-side-head">
          <img className="dt-side-logo" src="assets/weekaway-logo-reverse.svg" alt="WEEKAWAY™" />
          <div className="dt-side-prop">
            <div className="dt-side-eyebrow">{SAMPLE.region}</div>
            <div className="dt-side-name">{SAMPLE.property}</div>
          </div>
        </div>
        <nav className="dt-nav">
          {DT_NAV.map((n) => (
            <button key={n.id} type="button" className={"dt-nav-item" + (screen === n.id ? " active" : "")} onClick={() => setScreen(n.id)}>
              <Icon name={n.icon} size={19} stroke={1.6} />
              <span>{n.label}</span>
            </button>
          ))}
        </nav>
        <div className="dt-side-foot">
          <div className="dt-host">
            <img src={SAMPLE.host.avatar} alt="" />
            <div>
              <div className="dt-host-name">{SAMPLE.host.name}</div>
              <div className="dt-host-role">HostOp-style flow · Prototype</div>
            </div>
          </div>
        </div>
      </aside>
      <main className="dt-main"><div className="screen">{children}</div></main>
    </div>
  );
}

function MobileShell({ children, showTabs, tab, onTab }) {
  const tabs = [
    { id: "hub", icon: "list-checks", label: "Check-in" },
    { id: "stay", icon: "house", label: "Stay" },
    { id: "enhance", icon: "sparkles", label: "Enhance" },
    { id: "checkout", icon: "circle-check", label: "Depart" },
  ];
  return (
    <div className="stage">
      <div className="app">
        <div className="viewport">{children}</div>
        {showTabs && (
          <nav className="tabbar">
            {tabs.map((t) => (
              <button key={t.id} type="button" className={"tabbar-btn" + (tab === t.id ? " active" : "")} onClick={() => onTab(t.id)}>
                <Icon name={t.icon} size={20} stroke={1.7} />
                <span>{t.label}</span>
              </button>
            ))}
          </nav>
        )}
      </div>
    </div>
  );
}

function Root() {
  const params = new URLSearchParams(window.location.search);
  const [isDesktop, setIsDesktop] = useState(() => window.matchMedia("(min-width: 769px)").matches);
  const [screen, setScreen] = useState(params.get("screen") || "verify");
  const [done, setDone] = useState(() => {
    if (params.get("complete") === "1") return { guest_details: true, damage_waiver: true, house_rules: true };
    return {};
  });
  const [guest, setGuest] = useState({ fullName: "", eta: "" });
  const [upsellPreset, setUpsellPreset] = useState(params.get("upsell") || "available");
  const [earlyPurchased, setEarlyPurchased] = useState(params.get("upsell") === "purchased");
  const [latePurchased, setLatePurchased] = useState(false);
  const toast = useToast();
  const hideDev = params.get("shot") === "1";

  useEffect(() => {
    if (!hideDev) document.body.classList.add("dev-on");
    else document.body.classList.remove("dev-on");
    const mq = window.matchMedia("(min-width: 769px)");
    const onChange = (e) => setIsDesktop(e.matches);
    mq.addEventListener ? mq.addEventListener("change", onChange) : mq.addListener(onChange);
    return () => {
      mq.removeEventListener ? mq.removeEventListener("change", onChange) : mq.removeListener(onChange);
    };
  }, [hideDev]);

  useEffect(() => {
    const t = setTimeout(() => window.lucide && window.lucide.createIcons(), 60);
    return () => clearTimeout(t);
  }, [screen, isDesktop, done]);

  const mark = (id) => setDone((d) => ({ ...d, [id]: true }));
  const allDone = CHECKIN_STEPS.every((s) => done[s.id]);
  const go = (id) => setScreen(id);

  const afterStep = (id) => {
    mark(id);
    const order = CHECKIN_STEPS.map((s) => s.id);
    const idx = order.indexOf(id);
    const nextIncomplete = order.slice(idx + 1).find((x) => !done[x] && x !== id);
    // recompute with this step done
    const nextDone = { ...done, [id]: true };
    const next = CHECKIN_STEPS.find((s) => !nextDone[s.id]);
    if (next) go(next.id);
    else go("confirmation");
  };

  const upsellState = {
    early: upsellPreset,
    late: upsellPreset === "available" ? "checkback" : upsellPreset,
  };

  const onBuy = (kind) => {
    if (kind === "early") setEarlyPurchased(true);
    else setLatePurchased(true);
    toast("Purchased · Philip notified (mock)");
  };

  const backToHub = () => go(allDone ? "stay" : "hub");

  let body = null;
  if (screen === "verify") {
    body = <VerifyScreen onVerify={() => go("hub")} />;
  } else if (screen === "hub") {
    body = (
      <CheckInHub
        done={done}
        guestName={guest.fullName}
        onOpenStep={(id) => go(id)}
      />
    );
  } else if (screen === "guest_details") {
    body = (
      <GuestDetailsScreen
        initial={guest}
        onBack={() => go("hub")}
        onSave={(g) => { setGuest(g); afterStep("guest_details"); }}
        onSkip={() => afterStep("guest_details")}
      />
    );
  } else if (screen === "damage_waiver") {
    body = (
      <WaiverScreen
        onBack={() => go("hub")}
        onPaid={() => { toast("Waiver paid (mock)"); afterStep("damage_waiver"); }}
        onOptOut={() => afterStep("damage_waiver")}
      />
    );
  } else if (screen === "house_rules") {
    body = (
      <HouseRulesScreen
        onBack={() => go("hub")}
        onAgree={() => afterStep("house_rules")}
        onSkip={() => afterStep("house_rules")}
      />
    );
  } else if (screen === "confirmation") {
    body = <ConfirmationScreen unlocked={allDone} onHome={() => go("stay")} />;
  } else if (screen === "stay" || screen === "enhance") {
    body = (
      <StayPortal
        guestName={guest.fullName}
        onNav={go}
        upsellState={upsellState}
        onBuy={onBuy}
        earlyPurchased={earlyPurchased}
        latePurchased={latePurchased}
      />
    );
  } else if (screen === "door") {
    body = <DoorCodeScreen onBack={() => go("stay")} />;
  } else if (screen === "arrival") {
    body = <ArrivalGuideScreen onBack={() => go("stay")} />;
  } else if (screen === "wifi") {
    body = <WifiScreen onBack={() => go("stay")} />;
  } else if (screen === "wallet") {
    body = <WalletScreen onBack={() => go("stay")} />;
  } else if (screen === "guide") {
    body = (
      <SimpleListScreen
        title="Home guide"
        onBack={() => go("stay")}
        items={[
          ["wifi", "Wi-Fi & streaming", "Network details"],
          ["flame", "Hot tub", "How to start"],
          ["droplets", "Sauna", "Heat-up tips"],
          ["utensils", "Kitchen", "Appliances"],
        ]}
      />
    );
  } else if (screen === "local") {
    body = (
      <SimpleListScreen
        title="Local guide"
        onBack={() => go("stay")}
        items={[
          ["utensils", "Communal", "Walkable dining"],
          ["coffee", "Altitude Coffee", "5 min"],
          ["mountain", "Ha Ling Peak", "Trailhead 10 min"],
        ]}
      />
    );
  } else if (screen === "essentials") {
    body = (
      <SimpleListScreen
        title="Nearby essentials"
        onBack={() => go("stay")}
        items={[
          ["landmark", "ATM", "Main Street"],
          ["shopping-cart", "Grocery", "Safeway · 6 min"],
          ["cross", "Pharmacy", "Shoppers"],
          ["parking-circle", "Parking", "Driveway only"],
        ]}
      />
    );
  } else if (screen === "extend") {
    body = <ExtendScreen onBack={() => go("stay")} />;
  } else if (screen === "receipts") {
    body = <ReceiptsScreen onBack={() => go("stay")} />;
  } else if (screen === "checkout") {
    body = <CheckoutScreen onBack={() => go("stay")} />;
  } else {
    body = <VerifyScreen onVerify={() => go("hub")} />;
  }

  const showTabs = !["verify", "guest_details", "damage_waiver", "house_rules", "confirmation"].includes(screen);
  const mobileTab = ["hub", "guest_details", "damage_waiver", "house_rules"].includes(screen)
    ? "hub"
    : screen === "checkout"
      ? "checkout"
      : screen === "enhance"
        ? "enhance"
        : "stay";

  return (
    <>
      {!hideDev && (
        <DevBar
          screen={screen}
          setScreen={go}
          upsellPreset={upsellPreset}
          setUpsellPreset={(p) => { setUpsellPreset(p); setEarlyPurchased(false); setLatePurchased(false); }}
          resetCheckin={() => { setDone({}); setGuest({ fullName: "", eta: "" }); go("verify"); }}
        />
      )}
      {isDesktop ? (
        <DesktopShell screen={screen} setScreen={go}>{body}</DesktopShell>
      ) : (
        <MobileShell
          showTabs={showTabs}
          tab={mobileTab}
          onTab={(id) => {
            if (id === "hub") go(allDone ? "stay" : "hub");
            else go(id);
          }}
        >
          {body}
        </MobileShell>
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(
  <ToastProvider><Root /></ToastProvider>
);
