// StorefrontShowcase.jsx — "On your storefront": the live cart date picker, recreated 1:1
// from the production widget (delivery-scheduler.js). Picker variants (dropdown-switchable),
// the postcode availability check, and the out-of-area state. Storefront features only —
// no checkout-step / thank-you / tracking / SMS (those aren't shipped).
//
// Verified against live production (local-delivery-premium.myshopify.com/cart, Day-strip
// variant) on 2026-06-26: cream card + calendar header "Schedule Delivery", a
// Delivery/Pickup method selector, a postcode box (or pickup-area dropdown), a 14-day
// horizontal-scroll strip with UPPERCASE "FRI 26" pills, a "FRIDAY · CHOOSE A SLOT" label
// and 24-hour time slots. The area badge shows the real area NAME (no distance/km).

// ---- 14 days, exactly like the live strip (uppercase DOW + number, horizontal scroll) ----
const SF_DAYS = [
  { dow: "FRI", n: 26 }, { dow: "SAT", n: 27 }, { dow: "SUN", n: 28, full: true },
  { dow: "MON", n: 29 }, { dow: "TUE", n: 30 }, { dow: "WED", n: 1 }, { dow: "THU", n: 2 },
  { dow: "FRI", n: 3 }, { dow: "SAT", n: 4 }, { dow: "SUN", n: 5, full: true }, { dow: "MON", n: 6 },
  { dow: "TUE", n: 7 }, { dow: "WED", n: 8 }, { dow: "THU", n: 9 },
];
const SF_SLOTS = ["08:00 – 11:00", "11:00 – 14:00", "14:00 – 17:00", "17:00 – 20:00"];
const SF_AREA = "INNER WEST"; // the live widget shows the merchant's area NAME here (not a distance)
const SF_DOW_FULL = { SUN: "SUNDAY", MON: "MONDAY", TUE: "TUESDAY", WED: "WEDNESDAY", THU: "THURSDAY", FRI: "FRIDAY", SAT: "SATURDAY" };
function sfDow(n) { const d = SF_DAYS.find((x) => x.n === n); return d ? SF_DOW_FULL[d.dow] : "FRIDAY"; }
function sfDayLabel(n) {
  const d = SF_DAYS.find((x) => x.n === n) || SF_DAYS[0];
  const cap = (s) => s[0] + s.slice(1).toLowerCase();
  const mon = n >= 20 ? "Aug" : "Sep";
  return `${cap(SF_DOW_FULL[d.dow])}, ${n} ${mon}`;
}

// ---- theme presets (mirror the admin Display & accessibility themes) ----
const SF_THEMES = [
  { name: "Classic",  sw: ["#FFD60A", "#0F0F0F", "#FFFFFF"], accent: "#FFD60A", deep: "#F0B400", tint: "#FFF4B8", ink: "#0F0F0F", inkSoft: "#8A8A8A", inkMute: "#5C5C5C", line: "#E6E5DF", paper: "#FFFFFF", surface: "#FAF8F2", onAccent: "#0F0F0F" },
  { name: "Floral",   sw: ["#D6336C", "#3A1226", "#F9D9E4"], accent: "#D6336C", deep: "#B02457", tint: "#FBE6EE", ink: "#3A1226", inkSoft: "#A77E90", inkMute: "#7A5266", line: "#EAD6DE", paper: "#FFFFFF", surface: "#FCF1F5", onAccent: "#FFFFFF" },
  { name: "Midnight", sw: ["#FFD60A", "#1B2A4A", "#0F1830"], accent: "#FFD60A", deep: "#F0B400", tint: "#2A3A5C", ink: "#E8ECF5", inkSoft: "#8C9AB8", inkMute: "#B5C0D6", line: "#33446B", paper: "#1E2C4D", surface: "#16213E", onAccent: "#0F1830" },
  { name: "Blackout", sw: ["#FFD60A", "#0F0F0F", "#2A2A2A"], accent: "#FFD60A", deep: "#F0B400", tint: "#2E2E2E", ink: "#F2F2F2", inkSoft: "#8A8A8A", inkMute: "#B0B0B0", line: "#3A3A3A", paper: "#242424", surface: "#161616", onAccent: "#0A0A0A" },
  { name: "Native",   sw: ["#1E7A46", "#FFFFFF", "#D7EADB"], accent: "#1E7A46", deep: "#176038", tint: "#DCEFE2", ink: "#14331F", inkSoft: "#7FA98C", inkMute: "#4E7059", line: "#D7E5DB", paper: "#FFFFFF", surface: "#F1F7F2", onAccent: "#FFFFFF" },
];
// CSS-variable overrides that cascade into the widget preview
function sfThemeVars(name, wstyle) {
  const t = SF_THEMES.find((x) => x.name === name) || SF_THEMES[0];
  return {
    "--ld-yellow": t.accent, "--ld-yellow-deep": t.deep, "--ld-yellow-tint": t.tint,
    "--ld-ink": t.ink, "--ld-ink-soft": t.inkSoft, "--ld-ink-mute": t.inkMute,
    "--ld-line": t.line, "--ld-paper": t.paper, "--ld-cream": t.surface, "--ld-on-accent": t.onAccent,
    "--sf-shadow": wstyle === "Flat" ? "0 6px 18px rgba(15,15,15,0.12)" : "5px 5px 0 var(--ld-ink)",
    "--sf-btn-shadow": wstyle === "Flat" ? "none" : "2px 2px 0 var(--ld-ink)",
    "--sf-border": wstyle === "Flat" ? "1px" : "1.5px",
  };
}

// ---- inline icons (match the live widget chrome) ----
const SFCalIcon = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>
);
const SFTruckIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="4" width="14" height="12" rx="1.5"/><path d="M15 8h4l3 3.5V16h-7z"/><circle cx="5" cy="18.5" r="1.7"/><circle cx="18" cy="18.5" r="1.7"/></svg>
);
const SFClockIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>
);
const SFSearchIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>
);
const SFChevron = ({ open, size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="var(--ld-ink-mute)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms ease", flexShrink: 0 }}><path d="M6 9l6 6 6-6"/></svg>
);

// ---- shared widget chrome (header + method selector + postcode/area), exactly like live ----
function SFCardHeader({ method }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 16 }}>
      <span style={{ color: "var(--ld-ink)" }}><SFCalIcon size={19}/></span>
      <span style={{ fontSize: 17, fontWeight: 800, letterSpacing: "-0.3px" }}>{method === "pickup" ? "Schedule Pickup" : "Schedule Delivery"}</span>
    </div>
  );
}
function SFMethodRow({ method, setMethod }) {
  const opt = (id, label, icon) => {
    const on = method === id;
    return (
      <button type="button" onClick={() => setMethod(id)} style={{
        flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
        padding: "12px 10px", borderRadius: 10, fontSize: 14, fontWeight: 700, fontFamily: "inherit",
        cursor: "pointer", color: on ? "var(--ld-on-accent)" : "var(--ld-ink)",
        background: on ? "var(--ld-yellow)" : "var(--ld-paper)",
        border: `var(--sf-border, 1.5px) solid ${on ? "var(--ld-ink)" : "var(--ld-line)"}`,
        boxShadow: on ? "var(--sf-btn-shadow, 2px 2px 0 var(--ld-ink))" : "none",
        transition: "background 120ms ease, box-shadow 120ms ease",
      }}>{icon}{label}</button>
    );
  };
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 8 }}>Choose method <span style={{ color: "var(--ld-accent)" }}>*</span></div>
      <div style={{ display: "flex", gap: 10 }}>
        {opt("delivery", "Delivery", <SFTruckIcon/>)}
        {opt("pickup", "Pickup", <window.LDIcon.Pin size={15}/>)}
      </div>
    </div>
  );
}
function SFPostcodeRow() {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 8 }}>Enter your postcode</div>
      <div style={{ display: "flex", gap: 8 }}>
        <input defaultValue="2000" aria-label="Postcode" style={{ flex: 1, padding: "11px 14px", border: "1.5px solid var(--ld-ink)", borderRadius: 10, fontSize: 14, fontWeight: 600, fontFamily: "inherit", color: "var(--ld-ink)", outline: "none", background: "var(--ld-paper)" }}/>
        <button type="button" aria-label="Check postcode" style={{ width: 46, flexShrink: 0, borderRadius: 10, border: "var(--sf-border, 1.5px) solid var(--ld-ink)", background: "var(--ld-yellow)", boxShadow: "var(--sf-btn-shadow, 2px 2px 0 var(--ld-ink))", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", color: "var(--ld-on-accent)" }}><SFSearchIcon/></button>
      </div>
    </div>
  );
}
function SFAreaRow() {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 8 }}>Select a pickup area</div>
      <button type="button" style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", border: "1.5px solid var(--ld-ink)", borderRadius: 10, background: "var(--ld-paper)", fontSize: 14, fontWeight: 600, color: "var(--ld-ink-mute)", fontFamily: "inherit", cursor: "pointer" }}>
        <span>Choose an area</span><SFChevron/>
      </button>
    </div>
  );
}
function SFZoneHead({ method, title }) {
  const t = title || (method === "pickup" ? "Choose your pickup date" : "Choose your delivery date");
  return (
    <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12, marginBottom: 12 }}>
      <span style={{ fontSize: 15, fontWeight: 800 }}>{t}</span>
      <span className="ld-mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: "1px", color: "var(--ld-ink-soft)", whiteSpace: "nowrap" }}>{SF_AREA}</span>
    </div>
  );
}
function SFSlotLabel({ day }) {
  return (
    <div className="ld-mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: "1px", textTransform: "uppercase", color: "var(--ld-ink-soft)", margin: "14px 0 8px" }}>{sfDow(day)} · Choose a slot</div>
  );
}

// the cream widget card with the shared chrome; `children` is a render-fn receiving the method
function SFShell({ relative, children }) {
  const [method, setMethod] = React.useState("delivery");
  return (
    <div style={{
      background: "var(--ld-cream)", border: "var(--sf-border, 1.5px) solid var(--ld-ink)", borderRadius: 14,
      padding: 16, boxShadow: "var(--sf-shadow, 5px 5px 0 var(--ld-ink))", width: "100%", maxWidth: 380,
      position: relative ? "relative" : "static", overflow: relative ? "hidden" : "visible",
      minHeight: relative ? 520 : undefined,
    }}>
      <SFCardHeader method={method}/>
      <SFMethodRow method={method} setMethod={setMethod}/>
      {method === "delivery" ? <SFPostcodeRow/> : <SFAreaRow/>}
      {typeof children === "function" ? children(method) : children}
    </div>
  );
}

// ---- the day strip + slots (shared) ----
function SFDayStrip({ day, onSelect }) {
  return (
    <div style={{ display: "flex", gap: 6, overflowX: "auto", paddingBottom: 4, scrollbarWidth: "none", WebkitMaskImage: "linear-gradient(to right, #000 90%, transparent)", maskImage: "linear-gradient(to right, #000 90%, transparent)" }}>
      {SF_DAYS.map((d) => {
        const sel = day === d.n, full = d.full;
        return (
          <button key={`${d.dow}-${d.n}`} type="button" disabled={full} onClick={() => { if (!full) onSelect(d.n); }} style={{
            flex: "0 0 auto", width: 48, padding: "7px 0", borderRadius: 7, textAlign: "center",
            cursor: full ? "not-allowed" : "pointer", fontFamily: "inherit",
            background: sel ? "var(--ld-yellow)" : "var(--ld-paper)",
            border: `1.5px solid ${sel ? "var(--ld-ink)" : "var(--ld-line)"}`,
            color: sel ? "var(--ld-on-accent)" : "var(--ld-ink)",
            opacity: full ? 0.45 : 1, transition: "background 120ms ease, border-color 120ms ease",
          }}>
            <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: "0.5px", color: sel ? "var(--ld-on-accent)" : "var(--ld-ink-soft)" }}>{d.dow}</div>
            <div style={{ fontSize: 15, fontWeight: 800, textDecoration: full ? "line-through" : "none" }}>{d.n}</div>
          </button>
        );
      })}
    </div>
  );
}
function SFSlots({ compact, selected, onSelect }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
      {SF_SLOTS.map((t, i) => {
        const full = i === SF_SLOTS.length - 1, sel = t === selected;
        return (
          <button key={t} type="button" disabled={full} onClick={() => { if (!full && onSelect) onSelect(t); }} style={{
            display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
            padding: "10px 8px", borderRadius: 8, fontSize: 12.5, fontWeight: 700, fontFamily: "inherit",
            cursor: full ? "not-allowed" : "pointer",
            background: sel ? "var(--ld-yellow)" : "var(--ld-paper)",
            border: `1.5px solid ${sel ? "var(--ld-ink)" : "var(--ld-line)"}`,
            color: full ? "var(--ld-ink-soft)" : sel ? "var(--ld-on-accent)" : "var(--ld-ink)",
            textDecoration: full ? "line-through" : "none",
            transition: "background 120ms ease, border-color 120ms ease",
            ...(compact ? { flex: "1 1 44%" } : {}),
          }}>
            <span>{t}</span>
            {sel && <window.LDIcon.Check size={12}/>}
            {full && <span className="ld-mono" style={{ fontSize: 8 }}>FULL</span>}
          </button>
        );
      })}
    </div>
  );
}

// the selection summary line (dropdowns / calendar / stepped variants show this in live)
function SFSelline({ day, slot }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14, padding: "10px 12px", background: "var(--ld-paper)", border: "1.5px solid var(--ld-line)", borderRadius: 10 }}>
      <span style={{ width: 18, height: 18, borderRadius: "50%", background: "var(--ld-yellow)", border: "1.5px solid var(--ld-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, color: "var(--ld-on-accent)" }}><window.LDIcon.Check size={11}/></span>
      <span style={{ fontSize: 12.5, fontWeight: 600 }}>{slot} · {sfDayLabel(day)} — {SF_AREA.split(" ").map((w) => w[0] + w.slice(1).toLowerCase()).join(" ")}</span>
    </div>
  );
}

// inline themed dropdown (Dropdowns variant) — expands in place so it isn't clipped
function SFSelect({ label, value, options, onChange, tint, icon }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ marginBottom: 10 }}>
      <label className="ld-mono" style={{ fontSize: 10, color: "var(--ld-ink-soft)", letterSpacing: "0.8px", textTransform: "uppercase", fontWeight: 600 }}>{label}</label>
      <button type="button" onClick={() => setOpen((o) => !o)} style={{
        marginTop: 6, width: "100%", display: "flex", alignItems: "center", gap: 10,
        padding: "12px 14px", border: "1.5px solid var(--ld-ink)", borderRadius: 10, fontSize: 13, fontWeight: 600,
        background: tint ? "var(--ld-yellow-tint)" : "var(--ld-paper)", cursor: "pointer", fontFamily: "inherit", color: "var(--ld-ink)",
      }}>
        {icon && <span style={{ color: "var(--ld-ink)", display: "inline-flex", flexShrink: 0 }}>{icon}</span>}
        <span style={{ flex: 1, textAlign: "left" }}>{value}</span>
        <SFChevron open={open}/>
      </button>
      {open && (
        <div style={{ marginTop: 6, border: "1.5px solid var(--ld-ink)", borderRadius: 10, overflow: "hidden" }}>
          {options.map((o) => {
            const sel = o === value;
            return (
              <div key={o} onClick={() => { onChange(o); setOpen(false); }}
                onMouseEnter={(e) => { if (!sel) e.currentTarget.style.background = "var(--ld-yellow-tint)"; }}
                onMouseLeave={(e) => { if (!sel) e.currentTarget.style.background = "var(--ld-paper)"; }}
                style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 14px", fontSize: 13, fontWeight: sel ? 700 : 500, cursor: "pointer", background: sel ? "var(--ld-yellow)" : "var(--ld-paper)", color: sel ? "var(--ld-on-accent)" : "var(--ld-ink)" }}>
                <span>{o}</span>{sel && <window.LDIcon.Check size={12}/>}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ============================ variant bodies ============================
function SFStrip() {
  const [day, setDay] = React.useState(26);
  const [slot, setSlot] = React.useState(SF_SLOTS[0]);
  return (
    <SFShell>{(method) => (
      <div>
        <SFZoneHead method={method}/>
        <SFDayStrip day={day} onSelect={setDay}/>
        <SFSlotLabel day={day}/>
        <SFSlots selected={slot} onSelect={setSlot}/>
      </div>
    )}</SFShell>
  );
}

function SFDropdowns() {
  const [day, setDay] = React.useState(26);
  const [date, setDate] = React.useState("Friday, 26 Aug");
  const [time, setTime] = React.useState(SF_SLOTS[0]);
  return (
    <SFShell>{(method) => (
      <div>
        <SFSelect label={method === "pickup" ? "Pickup date" : "Delivery date"} value={date} icon={<SFCalIcon size={15}/>}
          onChange={(v) => { setDate(v); const n = parseInt(v.match(/\d+/)?.[0] || "26", 10); setDay(n); }}
          options={["Friday, 26 Aug", "Saturday, 27 Aug", "Monday, 29 Aug", "Tuesday, 30 Aug"]}/>
        <SFSelect label="Time slot" value={time} icon={<SFClockIcon size={15}/>} tint onChange={setTime} options={SF_SLOTS.slice(0, 2)}/>
        <label className="ld-mono" style={{ fontSize: 10, color: "var(--ld-ink-soft)", letterSpacing: "0.8px", textTransform: "uppercase", fontWeight: 600 }}>Delivery note (optional)</label>
        <textarea rows={2} placeholder="e.g. ring twice, leave at door" style={{ marginTop: 6, width: "100%", padding: "11px 14px", border: "1.5px solid var(--ld-line)", borderRadius: 10, fontSize: 13, fontFamily: "inherit", color: "var(--ld-ink)", outline: "none", background: "var(--ld-paper)", resize: "none" }}/>
        <SFSelline day={day} slot={time}/>
      </div>
    )}</SFShell>
  );
}

function SFCalendar() {
  const cells = Array.from({ length: 35 }, (_, i) => i - 2);
  const [sel, setSel] = React.useState(26);
  const [slot, setSlot] = React.useState(SF_SLOTS[0]);
  const leg = (label, style) => (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
      <span style={{ width: 9, height: 9, borderRadius: 3, ...style }}/>
      <span style={{ fontSize: 9.5, color: "var(--ld-ink-mute)" }}>{label}</span>
    </span>
  );
  return (
    <SFShell>{(method) => (
      <div>
        <SFZoneHead method={method} title={method === "pickup" ? "Pick a pickup date" : "Pick a delivery date"}/>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
          <span style={{ fontSize: 14, fontWeight: 800 }}>August 2026</span>
          <span style={{ display: "flex", gap: 6 }}>
            <span style={{ width: 24, height: 24, borderRadius: 6, border: "1.5px solid var(--ld-line)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>‹</span>
            <span style={{ width: 24, height: 24, borderRadius: 6, border: "1.5px solid var(--ld-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>›</span>
          </span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 3, marginBottom: 10 }}>
          {["S", "M", "T", "W", "T", "F", "S"].map((d, i) => <div key={i} style={{ textAlign: "center", fontSize: 9, fontWeight: 700, color: "var(--ld-ink-soft)" }}>{d}</div>)}
          {cells.map((n, i) => {
            const valid = n >= 1 && n <= 31, today = n === 25, past = valid && n < 26, selectable = valid && !past, isSel = n === sel;
            return (
              <div key={i} onClick={() => { if (selectable) setSel(n); }} style={{
                position: "relative", textAlign: "center", padding: "5px 0", fontSize: 11, borderRadius: 6,
                cursor: selectable ? "pointer" : "default", fontWeight: isSel ? 800 : 500, aspectRatio: "1 / 1",
                display: "flex", alignItems: "center", justifyContent: "center",
                background: isSel ? "var(--ld-yellow)" : "transparent",
                border: isSel ? "1.5px solid var(--ld-ink)" : today ? "1.5px dashed var(--ld-ink)" : "1.5px solid transparent",
                color: isSel ? "var(--ld-on-accent)" : !valid || past ? "var(--ld-line)" : "var(--ld-ink)",
              }}>{valid ? n : ""}{today && <span style={{ position: "absolute", bottom: 3, left: "50%", transform: "translateX(-50%)", width: 3, height: 3, borderRadius: "50%", background: "var(--ld-accent)" }}/>}</div>
            );
          })}
        </div>
        <div style={{ display: "flex", justifyContent: "center", gap: 14, marginBottom: 4 }}>
          {leg("Selected", { background: "var(--ld-yellow)", border: "1px solid var(--ld-ink)" })}
          {leg("Today", { border: "1px dashed var(--ld-ink)" })}
          {leg("Full", { background: "var(--ld-line)" })}
        </div>
        <SFSelline day={sel} slot={slot}/>
        <SFSlotLabel day={sel}/>
        <SFSlots selected={slot} onSelect={setSlot}/>
      </div>
    )}</SFShell>
  );
}

// Stepped — true accordion: only the active step is open; completed steps collapse to a
// summary row with a "Change" button; later steps are locked until earlier ones are done.
function SFStepped() {
  const [day, setDay] = React.useState(null);
  const [slot, setSlot] = React.useState(null);
  const [note, setNote] = React.useState("");
  const [override, setOverride] = React.useState(null); // user tapped "Change"
  const steps = [
    { key: "date", label: "Choose a date", value: day ? sfDayLabel(day) : "", done: day != null },
    { key: "slot", label: "Choose a time slot", value: slot || "", done: slot != null },
    { key: "note", label: "Add a note (optional)", value: note, done: false },
  ];
  const firstIncomplete = steps.find((s) => !s.done)?.key || "note";
  const active = override && steps.find((s) => s.key === override) ? override : firstIncomplete;
  const idxOf = (k) => steps.findIndex((s) => s.key === k);

  return (
    <SFShell>{(method) => (
      <div>
        <SFZoneHead method={method} title={method === "pickup" ? "Schedule your pickup" : "Schedule your delivery"}/>
        {steps.map((s, i) => {
          const isActive = s.key === active;
          const locked = i > idxOf(active) && !s.done && !(override && active === s.key);
          const n = i + 1;
          return (
            <div key={s.key} style={{ border: `1.5px solid ${isActive ? "var(--ld-ink)" : "var(--ld-line)"}`, borderRadius: 10, padding: "11px 13px", marginBottom: 8, background: isActive ? "var(--ld-yellow-tint)" : "var(--ld-paper)", opacity: locked ? 0.5 : 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 22, height: 22, borderRadius: "50%", flexShrink: 0, display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800, border: "1.5px solid var(--ld-ink)", background: s.done ? "var(--ld-yellow)" : "transparent", color: s.done ? "var(--ld-on-accent)" : "var(--ld-ink)" }}>{s.done ? <window.LDIcon.Check size={12}/> : n}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="ld-mono" style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: "1px", textTransform: "uppercase", color: "var(--ld-ink-soft)" }}>Step {n} · {s.label}</div>
                  {s.value && !isActive && <div style={{ fontSize: 13, fontWeight: 700, marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.value}</div>}
                </div>
                {s.done && !isActive && <button type="button" onClick={() => setOverride(s.key)} style={{ background: "none", border: "none", textDecoration: "underline", color: "var(--ld-ink-mute)", fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", flexShrink: 0 }}>Change</button>}
              </div>
              {isActive && (
                <div style={{ marginTop: 10 }}>
                  {s.key === "date" && <SFDayStrip day={day} onSelect={(n2) => { setDay(n2); setOverride(null); }}/>}
                  {s.key === "slot" && <SFSlots compact selected={slot} onSelect={(t) => { setSlot(t); setOverride(null); }}/>}
                  {s.key === "note" && <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="e.g. ring twice, leave at door" style={{ width: "100%", padding: "10px 12px", border: "1.5px solid var(--ld-line)", borderRadius: 8, fontSize: 13, fontFamily: "inherit", color: "var(--ld-ink)", outline: "none", background: "var(--ld-paper)" }}/>}
                </div>
              )}
            </div>
          );
        })}
        {day != null && slot != null && <SFSelline day={day} slot={slot}/>}
      </div>
    )}</SFShell>
  );
}

// Bottom sheet — the trigger lives in the card; the sheet slides up within the card frame.
function SFSheet() {
  const [open, setOpen] = React.useState(false);
  const [day, setDay] = React.useState(26);
  const [slot, setSlot] = React.useState(SF_SLOTS[0]);
  const [confirmed, setConfirmed] = React.useState(false);
  return (
    <SFShell relative>{(method) => (
      <React.Fragment>
        <SFZoneHead method={method}/>
        <div onClick={() => setOpen(true)} style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 14px", border: "var(--sf-border, 1.5px) solid var(--ld-ink)", borderRadius: 12, cursor: "pointer", background: "var(--ld-paper)", boxShadow: "var(--sf-btn-shadow, 3px 3px 0 var(--ld-ink))" }}>
          <span style={{ width: 40, height: 40, borderRadius: 10, background: "var(--ld-yellow)", border: "1.5px solid var(--ld-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, color: "var(--ld-on-accent)" }}><SFCalIcon size={18}/></span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="ld-mono" style={{ fontSize: 9, color: "var(--ld-ink-soft)", letterSpacing: "0.8px", textTransform: "uppercase" }}>{method === "pickup" ? "Pickup date & time" : "Delivery date & time"}</div>
            <div style={{ fontSize: 14, fontWeight: 800, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{confirmed ? `${sfDayLabel(day)} · ${slot}` : "Choose date & time"}</div>
          </div>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--ld-ink-mute)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M9 6l6 6-6 6"/></svg>
        </div>

        {/* dim backdrop */}
        <div onClick={() => setOpen(false)} style={{ position: "absolute", inset: 0, background: "rgba(15,15,15,0.45)", opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity 250ms ease", zIndex: 5 }}/>

        {/* the bottom sheet */}
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, background: "var(--ld-paper)", borderRadius: "20px 20px 0 0", boxShadow: "0 -12px 40px rgba(0,0,0,0.22)", padding: "14px 18px 20px", transform: open ? "translateY(0)" : "translateY(110%)", transition: "transform 320ms cubic-bezier(0.22,1,0.36,1)", zIndex: 6 }}>
          <div style={{ width: 40, height: 4, borderRadius: 999, background: "var(--ld-line)", margin: "0 auto 14px" }}/>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, marginBottom: 16 }}>
            <h4 style={{ fontSize: 17, fontWeight: 800, margin: 0, letterSpacing: "-0.3px", maxWidth: 240 }}>When would you like your {method === "pickup" ? "pickup" : "delivery"}?</h4>
            <button onClick={() => setOpen(false)} aria-label="Close" style={{ width: 30, height: 30, borderRadius: 8, border: "1.5px solid var(--ld-ink)", background: "var(--ld-paper)", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--ld-ink)" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
          </div>
          <div className="ld-mono" style={{ fontSize: 10, color: "var(--ld-ink-soft)", letterSpacing: "1px", textTransform: "uppercase", marginBottom: 8, fontWeight: 700 }}>Date</div>
          <div style={{ marginBottom: 16 }}><SFDayStrip day={day} onSelect={setDay}/></div>
          <div className="ld-mono" style={{ fontSize: 10, color: "var(--ld-ink-soft)", letterSpacing: "1px", textTransform: "uppercase", marginBottom: 8, fontWeight: 700 }}>{method === "pickup" ? "Pickup window" : "Time window"}</div>
          <SFSlots selected={slot} onSelect={setSlot}/>
          <button onClick={() => { setConfirmed(true); setOpen(false); }} className="ld-btn ld-btn-primary ld-btn-lg" style={{ width: "100%", justifyContent: "center", marginTop: 16, color: "var(--ld-on-accent)", boxShadow: "var(--sf-btn-shadow, 0 4px 0 var(--ld-ink))" }}>Confirm</button>
        </div>
      </React.Fragment>
    )}</SFShell>
  );
}

function LDStorefront() {
  const variants = [
    { id: "strip", name: "Day strip", desc: "A horizontal row of days with time slots underneath — compact and quick. The default." },
    { id: "dropdowns", name: "Dropdowns", desc: "Two tidy dropdowns for date and time, plus an optional note — great for narrow cart drawers." },
    { id: "calendar", name: "Calendar", desc: "A full month grid for stores whose customers book further ahead." },
    { id: "stepped", name: "Stepped", desc: "A guided, one-step-at-a-time flow: pick a date, then a slot, then leave a note." },
    { id: "sheet", name: "Bottom sheet", desc: "A sheet that slides up from the bottom of the screen — ideal on mobile." },
  ];
  const [vid, setVid] = React.useState("strip");
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, []);
  const cur = variants.find((v) => v.id === vid);
  const body = { strip: <SFStrip/>, dropdowns: <SFDropdowns/>, calendar: <SFCalendar/>, stepped: <SFStepped/>, sheet: <SFSheet/> }[vid];
  const [theme, setTheme] = React.useState("Classic");
  const [wstyle, setWstyle] = React.useState("Bold");

  return (
    <section id="storefront" style={{ background: "var(--ld-paper)", padding: "112px 0", borderTop: "1px solid var(--ld-line)" }}>
      <div className="ld-container-wide">
        <div style={{ maxWidth: 720, marginBottom: 48 }}>
          <span className="ld-eyebrow ld-eyebrow-dot">On your storefront</span>
          <h2 className="ld-h2" style={{ marginTop: 16 }}>One date picker, five ways to show it.</h2>
          <p className="ld-lead" style={{ marginTop: 16 }}>
            Pick the layout that fits your theme and your customers. Every variant comes in ready-made theme presets and works on the cart drawer and the cart page.
          </p>
        </div>

        {/* picker variants */}
        <div className="ld-split-l" style={{ alignItems: "flex-start", marginBottom: 96 }}>
          <div>
            <div ref={ref} style={{ position: "relative", maxWidth: 320 }}>
              <span className="ld-mono" style={{ fontSize: 11, color: "var(--ld-ink-soft)", letterSpacing: "1px", textTransform: "uppercase", fontWeight: 600 }}>Picker variant</span>
              <button type="button" onClick={() => setOpen((o) => !o)} aria-expanded={open} style={{
                marginTop: 8, width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
                padding: "14px 16px", fontSize: 16, fontWeight: 700, fontFamily: "inherit", textAlign: "left",
                background: "var(--ld-paper)", border: `2px solid var(--ld-ink)`, borderRadius: 12, cursor: "pointer",
                boxShadow: "4px 4px 0 var(--ld-ink)",
              }}>
                <span>{cur.name}</span>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--ld-ink)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms ease" }}><path d="M6 9l6 6 6-6"/></svg>
              </button>
              {open && (
                <div style={{ position: "absolute", top: "calc(100% + 8px)", left: 0, right: 0, zIndex: 60, background: "var(--ld-paper)", border: "2px solid var(--ld-ink)", borderRadius: 12, boxShadow: "var(--ld-shadow-pop)", padding: 6 }}>
                  {variants.map((v) => (
                    <div key={v.id} onClick={() => { setVid(v.id); setOpen(false); }}
                      onMouseEnter={(e) => { if (v.id !== vid) e.currentTarget.style.background = "var(--ld-yellow-tint)"; }}
                      onMouseLeave={(e) => { if (v.id !== vid) e.currentTarget.style.background = "transparent"; }}
                      style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 12px", borderRadius: 8, cursor: "pointer", fontSize: 15, fontWeight: v.id === vid ? 700 : 500, background: v.id === vid ? "var(--ld-yellow)" : "transparent" }}>
                      <span>{v.name}</span>{v.id === vid && <window.LDIcon.Check size={14}/>}
                    </div>
                  ))}
                </div>
              )}
            </div>
            <p className="ld-body" style={{ marginTop: 22, maxWidth: 360 }}>{cur.desc}</p>

            {/* theme & appearance — drives the live preview */}
            <div style={{ marginTop: 28, paddingTop: 26, borderTop: "1px solid var(--ld-line)", maxWidth: 380 }}>
              <span className="ld-mono" style={{ fontSize: 11, color: "var(--ld-ink-soft)", letterSpacing: "1px", textTransform: "uppercase", fontWeight: 600 }}>Theme &amp; appearance</span>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 12 }}>
                {SF_THEMES.map((t) => {
                  const on = t.name === theme;
                  return (
                    <button key={t.name} type="button" onClick={() => setTheme(t.name)} aria-pressed={on} style={{
                      flex: "1 1 96px", minWidth: 90, cursor: "pointer", textAlign: "left", fontFamily: "inherit",
                      background: "var(--ld-paper)", border: `2px solid ${on ? "var(--ld-ink)" : "var(--ld-line)"}`,
                      borderRadius: 10, padding: "8px 8px 7px", boxShadow: on ? "3px 3px 0 var(--ld-ink)" : "none",
                      transition: "box-shadow 120ms ease, border-color 120ms ease",
                    }}>
                      <div style={{ display: "flex", gap: 3, marginBottom: 6 }}>
                        {t.sw.map((c, i) => <span key={i} style={{ flex: 1, height: 18, borderRadius: 4, background: c, border: "1px solid var(--ld-ink)" }}/>)}
                      </div>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                        <span style={{ fontSize: 12, fontWeight: 700 }}>{t.name}</span>
                        {on && <window.LDIcon.Check size={12}/>}
                      </div>
                    </button>
                  );
                })}
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 16, flexWrap: "wrap" }}>
                <span className="ld-mono" style={{ fontSize: 10, letterSpacing: "1px", textTransform: "uppercase", color: "var(--ld-ink-soft)", fontWeight: 600 }}>Style</span>
                <div style={{ display: "inline-flex", border: "1.5px solid var(--ld-ink)", borderRadius: 10, overflow: "hidden" }}>
                  {["Bold", "Flat"].map((s) => (
                    <button key={s} type="button" onClick={() => setWstyle(s)} style={{
                      padding: "7px 16px", fontSize: 13, fontWeight: 700, fontFamily: "inherit", cursor: "pointer", border: "none",
                      borderLeft: s === "Flat" ? "1.5px solid var(--ld-ink)" : "none",
                      background: wstyle === s ? "var(--ld-yellow)" : "var(--ld-paper)", color: "var(--ld-ink)",
                    }}>{s}</button>
                  ))}
                </div>
              </div>
              <p className="ld-small" style={{ marginTop: 14, color: "var(--ld-ink-soft)", maxWidth: 360 }}>
                Ready-made theme presets and a bold or flat style — the preview updates live. No custom code.
              </p>
            </div>
          </div>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <div style={{ ...sfThemeVars(theme, wstyle), color: "var(--ld-ink)" }}>{body}</div>
          </div>
        </div>

        {/* postcode availability check */}
        <div className="ld-split-r" style={{ alignItems: "center", marginBottom: 96 }}>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <div style={{ background: "var(--ld-cream)", border: "1.5px solid var(--ld-ink)", borderRadius: 14, padding: 16, boxShadow: "5px 5px 0 var(--ld-ink)", width: "100%", maxWidth: 380 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
                <div style={{ width: 48, height: 48, borderRadius: 10, background: "linear-gradient(135deg,#F4DFC8,#E9C39C)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 22 }}>🌸</div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 800 }}>Wild Garden Bouquet</div>
                  <div className="ld-small">$68.00</div>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 700, marginBottom: 10 }}>
                <window.LDIcon.Pin size={14}/> Local same-day delivery available
              </div>
              <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 8 }}>Enter your postcode</div>
              <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
                <div style={{ flex: 1, padding: "11px 14px", background: "var(--ld-paper)", border: "1.5px solid var(--ld-ink)", borderRadius: 10, fontSize: 14, fontWeight: 600 }}>2000</div>
                <button aria-label="Check" style={{ width: 46, flexShrink: 0, borderRadius: 10, border: "1.5px solid var(--ld-ink)", background: "var(--ld-yellow)", boxShadow: "2px 2px 0 var(--ld-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><SFSearchIcon/></button>
              </div>
              <div style={{ display: "flex", alignItems: "flex-start", gap: 8, background: "var(--ld-paper)", border: "1.5px solid var(--ld-ok)", borderRadius: 10, padding: "10px 12px" }}>
                <span style={{ color: "var(--ld-ok)", marginTop: 1 }}><window.LDIcon.Check size={14}/></span>
                <div style={{ fontSize: 12 }}>
                  <div style={{ fontWeight: 700 }}>Same-day to Inner West</div>
                  <div className="ld-small">Order before 2pm · pick your slot in the cart</div>
                </div>
              </div>
            </div>
          </div>
          <div>
            <span className="ld-pill-tint">Postcode check</span>
            <h3 className="ld-h3" style={{ marginTop: 14, marginBottom: 14 }}>Shoppers check delivery right inside the cart.</h3>
            <p className="ld-lead">
              The picker checks the customer’s postcode against your delivery areas and shows whether you deliver there — and on which days — before they reach checkout.
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: "20px 0 0", display: "flex", flexDirection: "column", gap: 12 }}>
              {["Matches the postcode to the right delivery area", "Shows the days and slots available for that area", "Offers pickup when an address is outside your delivery areas"].map((t) => (
                <li key={t} style={{ display: "flex", gap: 12, alignItems: "flex-start", fontSize: 15 }}>
                  <span style={{ width: 22, height: 22, borderRadius: 6, background: "var(--ld-yellow)", border: "1.5px solid var(--ld-ink)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 1 }}><window.LDIcon.Check size={13}/></span>
                  {t}
                </li>
              ))}
            </ul>
          </div>
        </div>

        {/* unavailable / out-of-area state */}
        <SFUnavailable/>
      </div>
    </section>
  );
}

function SFUnavailable() {
  return (
    <div className="ld-split-l" style={{ alignItems: "center" }}>
      <div>
        <span className="ld-pill-tint">When delivery isn’t available</span>
        <h3 className="ld-h3" style={{ marginTop: 14, marginBottom: 14 }}>Never a dead end at the cart.</h3>
        <p className="ld-lead">
          If an address is outside your delivery areas, the picker says so and offers pickup instead — so you don’t lose the sale.
        </p>
      </div>
      <div style={{ display: "flex", justifyContent: "center" }}>
        <div style={{ background: "var(--ld-cream)", border: "1.5px solid var(--ld-ink)", borderRadius: 14, padding: 16, boxShadow: "5px 5px 0 var(--ld-ink)", width: "100%", maxWidth: 380 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 16 }}>
            <span style={{ color: "var(--ld-ink)" }}><SFCalIcon size={19}/></span>
            <span style={{ fontSize: 17, fontWeight: 800, letterSpacing: "-0.3px" }}>Schedule Delivery</span>
          </div>
          <div style={{ background: "var(--ld-accent-tint)", border: "1.5px solid var(--ld-accent)", borderRadius: 12, padding: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
              <span style={{ width: 28, height: 28, borderRadius: 8, background: "var(--ld-ink)", color: "var(--ld-accent)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><window.LDIcon.Pin size={15}/></span>
              <span style={{ fontSize: 14, fontWeight: 800 }}>We don’t deliver to 9999 yet</span>
            </div>
            <p className="ld-small" style={{ marginBottom: 14 }}>Your address is outside our delivery zones. You can pick up at our store instead.</p>
            <button className="ld-btn ld-btn-dark" style={{ width: "100%", justifyContent: "center" }}>Switch to pickup</button>
          </div>
        </div>
      </div>
    </div>
  );
}
window.LDStorefront = LDStorefront;
