// BuildBinScreen — the "Build Your Bin" custom builder.
const BB = window.TheLittleScoopDesignSystem_cee583;

const FILLERS = [
  { id: "berry", label: "Strawberry rice", color: "#FF9DB3", deep: "#FF5E7E" },
  { id: "sunshine", label: "Sunshine rice", color: "#FFDC6B", deep: "#FFC93C" },
  { id: "ocean", label: "Ocean beads", color: "#86E0EA", deep: "#4FC3DC" },
  { id: "sprout", label: "Garden green", color: "#B6E27F", deep: "#82C91E" },
  { id: "cosmic", label: "Cosmic beans", color: "#C3A9EE", deep: "#9B7EDE" },
];
const PACKS = [
  { id: "garden", label: "Garden friends", dots: ["#82C91E", "#FF5E7E", "#FFC93C"] },
  { id: "sea", label: "Sea creatures", dots: ["#4FC3DC", "#2BA3BE", "#FF9DB3"] },
  { id: "space", label: "Space crew", dots: ["#9B7EDE", "#FFC93C", "#fff"] },
  { id: "berry", label: "Berry sweet", dots: ["#F23E63", "#9B7EDE", "#82C91E"] },
];
const ADDONS = [
  { id: "scoop", label: "Scoop & tongs", price: 2 },
  { id: "cups", label: "Counting cups", price: 2 },
  { id: "glow", label: "Glow-in-dark stars", price: 1.5 },
  { id: "magnifier", label: "Mini magnifier", price: 2 },
];
const BASE = 6, PACK_PRICE = 3, NAME_PRICE = 1;

function Swatch({ active, color, deep, label, onClick }) {
  return (
    <button onClick={onClick} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8, border: "none", background: "none", cursor: "pointer", padding: 0 }}>
      <span style={{ width: 64, height: 64, borderRadius: "var(--radius-lg)", background: `linear-gradient(135deg, ${color}, ${deep})`,
        boxShadow: active ? "0 0 0 4px var(--brand-primary)" : "var(--shadow-sm)", border: "2px solid rgba(255,255,255,.6)", transition: "box-shadow var(--dur-fast)" }} />
      <span style={{ fontFamily: "var(--font-body)", fontWeight: active ? 800 : 600, fontSize: "var(--text-sm)", color: active ? "var(--text-strong)" : "var(--text-body)" }}>{label}</span>
    </button>
  );
}

function StepHead({ n, title }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: "var(--space-4)" }}>
      <span style={{ width: 32, height: 32, flex: "none", borderRadius: "50%", background: "var(--brand-primary)", color: "#fff",
        fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-md)", display: "flex", alignItems: "center", justifyContent: "center" }}>{n}</span>
      <h2 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-xl)", color: "var(--text-strong)" }}>{title}</h2>
    </div>
  );
}

function BinPreview({ filler, pack, name }) {
  const dots = pack ? pack.dots : ["rgba(255,255,255,.7)"];
  const positions = [[22, 64], [40, 78], [58, 66], [72, 80], [30, 86], [64, 90], [48, 70]];
  return (
    <div style={{ position: "sticky", top: 92 }}>
      <div style={{ borderRadius: "var(--radius-2xl)", background: "var(--white)", border: "2px solid var(--border-soft)", boxShadow: "var(--shadow-md)", padding: "var(--space-5)", textAlign: "center" }}>
        <div style={{ position: "relative", height: 230, borderRadius: "var(--radius-xl)", overflow: "hidden",
          background: filler ? `linear-gradient(160deg, ${filler.color}, ${filler.deep})` : "var(--surface-sunken)",
          display: "flex", alignItems: "center", justifyContent: "center", transition: "background var(--dur-slow) var(--ease-out)" }}>
          {!filler && <span style={{ fontFamily: "var(--font-display)", color: "var(--text-faint)", fontSize: "var(--text-md)" }}>Pick a filler to start →</span>}
          {filler && positions.map((p, i) => (
            <span key={i} style={{ position: "absolute", left: p[0] + "%", top: p[1] + "%", width: 16, height: 16, borderRadius: "50%",
              background: dots[i % dots.length], boxShadow: "0 1px 3px rgba(0,0,0,.18)", transform: "translate(-50%,-50%)" }} />
          ))}
          {/* label */}
          {filler && (
            <div style={{ position: "absolute", top: 16, left: "50%", transform: "translateX(-50%)", background: "rgba(255,255,255,.92)",
              borderRadius: "var(--radius-pill)", padding: "6px 16px", boxShadow: "var(--shadow-sm)", maxWidth: "90%" }}>
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-sm)", color: "var(--text-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", display: "block" }}>
                {name ? name + "'s bin" : "My little bin"}
              </span>
            </div>
          )}
        </div>
        <p style={{ margin: "var(--space-3) 0 0", fontFamily: "var(--font-body)", fontWeight: 700, color: "var(--text-muted)", fontSize: "var(--text-sm)" }}>Live preview</p>
      </div>
    </div>
  );
}

function BuildBinScreen({ onAdd, mobile }) {
  const { Button, Input, Badge } = BB;
  const [filler, setFiller] = React.useState(null);
  const [pack, setPack] = React.useState(null);
  const [addons, setAddons] = React.useState([]);
  const [name, setName] = React.useState("");

  const toggleAddon = (id) => setAddons((a) => (a.includes(id) ? a.filter((x) => x !== id) : [...a, id]));
  const addonTotal = addons.reduce((s, id) => s + ADDONS.find((a) => a.id === id).price, 0);
  const total = (filler ? BASE : 0) + (pack ? PACK_PRICE : 0) + addonTotal + (name.trim() ? NAME_PRICE : 0);
  const ready = filler && pack;

  const build = () => {
    const fillerObj = filler;
    onAdd({
      id: "custom-" + Date.now(),
      title: (name.trim() ? name.trim() + "'s " : "Custom ") + "Build-a-Bin",
      price: total, ages: "3+", theme: filler.id, custom: true,
    }, 1);
  };

  return (
    <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "var(--space-6) var(--container-pad)" }}>
      <div style={{ textAlign: "center", marginBottom: "var(--space-6)" }}>
        <span style={{ display: "inline-flex" }}><Badge tone="grape" solid>The fun part</Badge></span>
        <h1 style={{ margin: "var(--space-3) 0 6px", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: mobile ? "var(--text-3xl)" : "var(--text-4xl)", color: "var(--text-strong)" }}>Build your bin</h1>
        <p style={{ margin: 0, fontSize: "var(--text-lg)", color: "var(--text-body)" }}>Four little steps to a one-of-a-kind sensory bin.</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr" : "1.4fr 1fr", gap: "var(--space-7)", alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-6)" }}>
          {/* Step 1 */}
          <div>
            <StepHead n="1" title="Choose your filler" />
            <div style={{ display: "flex", gap: "var(--space-5)", flexWrap: "wrap" }}>
              {FILLERS.map((f) => <Swatch key={f.id} {...f} active={filler?.id === f.id} onClick={() => setFiller(f)} />)}
            </div>
          </div>
          {/* Step 2 */}
          <div>
            <StepHead n="2" title="Add a treasure pack" />
            <div style={{ display: "grid", gridTemplateColumns: mobile ? "1fr 1fr" : "repeat(4,1fr)", gap: "var(--space-3)" }}>
              {PACKS.map((p) => (
                <button key={p.id} onClick={() => setPack(pack?.id === p.id ? null : p)} style={{ cursor: "pointer", textAlign: "left",
                  border: pack?.id === p.id ? "2px solid var(--brand-primary)" : "2px solid var(--border-soft)", background: "var(--white)",
                  borderRadius: "var(--radius-lg)", padding: "var(--space-4)", boxShadow: pack?.id === p.id ? "var(--shadow-sm)" : "none" }}>
                  <span style={{ display: "flex", gap: 5, marginBottom: 10 }}>
                    {p.dots.map((d, i) => <span key={i} style={{ width: 16, height: 16, borderRadius: "50%", background: d, border: "1px solid rgba(0,0,0,.06)" }} />)}
                  </span>
                  <span style={{ display: "block", fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-sm)", color: "var(--text-strong)" }}>{p.label}</span>
                  <span style={{ fontSize: "var(--text-xs)", fontWeight: 700, color: "var(--text-muted)" }}>+$3</span>
                </button>
              ))}
            </div>
          </div>
          {/* Step 3 */}
          <div>
            <StepHead n="3" title="Pile on the extras" />
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {ADDONS.map((a) => {
                const on = addons.includes(a.id);
                return (
                  <button key={a.id} onClick={() => toggleAddon(a.id)} style={{ display: "flex", alignItems: "center", gap: 12, cursor: "pointer",
                    border: on ? "2px solid var(--brand-primary)" : "2px solid var(--border-soft)", background: on ? "var(--brand-primary-tint)" : "var(--white)",
                    borderRadius: "var(--radius-lg)", padding: "12px 16px" }}>
                    <span style={{ width: 24, height: 24, borderRadius: 8, flex: "none", border: on ? "none" : "2px solid var(--border-strong)",
                      background: on ? "var(--brand-primary)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      {on && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l4 4 10-10"/></svg>}
                    </span>
                    <span style={{ flex: 1, textAlign: "left", fontFamily: "var(--font-body)", fontWeight: 700, color: "var(--text-strong)", fontSize: "var(--text-md)" }}>{a.label}</span>
                    <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, color: "var(--text-muted)" }}>+${a.price.toFixed(2)}</span>
                  </button>
                );
              })}
            </div>
          </div>
          {/* Step 4 */}
          <div>
            <StepHead n="4" title="Add a name (optional)" />
            <Input placeholder="e.g. Ada" value={name} onChange={(e) => setName(e.target.value)} hint="We'll print it on the bin label · +$1" containerStyle={{ maxWidth: 320 }} />
          </div>
        </div>

        {/* Preview + summary */}
        <div>
          <BinPreview filler={filler} pack={pack} name={name.trim()} />
          <div style={{ marginTop: "var(--space-4)", background: "var(--surface-raised)", border: "2px solid var(--border-soft)", borderRadius: "var(--radius-xl)", padding: "var(--space-5)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: "var(--space-3)" }}>
              <span style={{ fontFamily: "var(--font-body)", fontWeight: 700, color: "var(--text-body)" }}>Your bin</span>
              <span style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: "var(--text-2xl)", color: "var(--brand-primary)" }}>${total.toFixed(2)}</span>
            </div>
            <Button variant="primary" size="lg" block disabled={!ready} onClick={build}>
              {ready ? "Add my bin to cart" : "Pick a filler & pack"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BuildBinScreen });
