/* Canvas editor — immersive room view, floating dock, mode-aware submit flow */
const { PS_DATA: DB } = window;
const { useState: useStateB, useEffect: useEffectB } = React;

const TOOLS_B = [
  ["template", "LayoutTemplate", "Templates"],
  ["photo", "Image", "Photo"],
  ["text", "Type", "Text"],
  ["font", "CaseSensitive", "Font"],
  ["color", "Palette", "Color"],
  ["size", "Ruler", "Size"],
  ["frame", "Frame", "Frame"],
];

function TrayBody({ tool, design, update, lock }) {
  const onPick = t => update(DB.applyTemplate(design, t));
  const custom = !!design.custom;
  const lockedNote = label => (
    <div style={{ display: "flex", gap: 10, alignItems: "center", padding: "14px 16px", background: "var(--paper-2)", borderRadius: "var(--r-md)", color: "var(--ink-2)", fontSize: 13.5, lineHeight: 1.45 }}>
      <Icon name="Lock" size={17} style={{ color: "var(--ink-3)", flex: "none" }} />
      <span>{label} is set by this template, so your design stays consistent. Edit the <b style={{ color: "var(--ink)" }}>Text</b> instead.</span>
    </div>
  );
  switch (tool) {
    case "template": return <TemplateGrid design={design} onPick={onPick} cols={6} />;
    case "photo": return (custom && !design.hasPhotoZone) ? lockedNote("The background") : <PhotoEditor design={design} update={update} />;
    case "text": return <TextFields design={design} update={update} />;
    case "font": return custom ? lockedNote("The font") : <FontRow design={design} update={update} />;
    case "color": return custom ? lockedNote("Colours are") : (
      <div style={{ display: "flex", gap: 34, flexWrap: "wrap" }}>
        <div><div className="eyebrow" style={{ marginBottom: 11 }}>Background</div><BgRow design={design} update={update} /></div>
        <div><div className="eyebrow" style={{ marginBottom: 11 }}>Text color</div><TextColorRow design={design} update={update} /></div>
      </div>
    );
    case "size": return <SizeRow design={design} update={update} lock={lock} />;
    case "frame": return <FrameRow design={design} update={update} lock={lock} />;
    default: return null;
  }
}
const TOOL_TITLE = { template: "Choose a template", photo: "Add your photo", text: "Edit your words", font: "Pick a typeface", color: "Colors", size: "Choose a size", frame: "Add a frame" };

function VariantB({ design, update, bp, entry, showIntro, onCloseIntro, onResetDesign, undo, redo, canUndo, canRedo, onShare }) {
  const [tool, setTool] = useStateB(null);
  const [review, setReview] = useStateB(false);
  const [output, setOutput] = useStateB(false);
  const [checkout, setCheckout] = useStateB(null);
  const [done, setDone] = useStateB(null);
  const mobile = bp === "mobile";
  const etsy = entry.mode === "etsy";
  const price = DB.priceFor(design);
  const maxH = mobile ? 320 : bp === "tablet" ? 440 : 540;
  const curTmpl = DB.TEMPLATES.find(t => t.id === design.templateId) || DB.TEMPLATES[0];
  const photoLive = curTmpl.kind === "photo";
  const lockFormat = etsy;

  // close tray on Escape
  useEffectB(() => {
    if (!tool) return;
    const onKey = e => { if (e.key === "Escape") setTool(null); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [tool]);

  const openReview = () => { setTool(null); setReview(true); };
  const openOutput = () => { setTool(null); setOutput(true); };
  // shop: review sheet -> full checkout (address/shipping/payment)
  const confirm = () => {
    const size = DB.SIZES.find(s => s.id === design.size) || DB.SIZES[1];
    const frame = DB.FRAMES.find(f => f.id === design.frame) || DB.FRAMES[0];
    setReview(false);
    setCheckout({ design, subtotal: DB.priceFor(design), credit: 0,
      lineItem: { title: entry.productName, sub: size.label + " cm · " + frame.label, design } });
  };
  // etsy: print upsell review -> full checkout, crediting the Etsy payment
  const openPrintCheckout = ({ subtotal, lineItem }) => {
    setOutput(false);
    setCheckout({ design, subtotal, credit: entry.paid || 0, lineItem });
  };
  const restart = () => {
    setDone(null);
    if (!etsy && onResetDesign) onResetDesign();
  };

  return (
    <div style={{ position: "relative", height: "100%", overflow: "hidden", background: "#E3D7C0" }}>
      <RoomScene d={design} maxH={maxH} live={photoLive} update={update} edit={true} />

      {/* top overlay */}
      <div style={{ position: "absolute", top: 0, left: 0, right: 0, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: mobile ? "13px 12px" : "18px 22px", zIndex: 6 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 14px 8px 9px", background: "rgba(255,253,245,.82)", backdropFilter: "blur(10px)", borderRadius: "var(--r-pill)", boxShadow: "var(--sh-sm)", minWidth: 0 }}>
          <div style={{ width: 26, height: 26, borderRadius: 7, background: "var(--clay)", color: "#FFF7EF", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="Frame" size={15} /></div>
          {!mobile && <span style={{ fontFamily: "var(--serif)", fontSize: 16, fontWeight: 600 }}>Belle Maison</span>}
          {etsy && (
            <span style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 9px", borderRadius: 99, background: "var(--sage-tint)", color: "#46522F", fontSize: 11, fontWeight: 700, whiteSpace: "nowrap" }}>
              <Icon name="BadgeCheck" size={12} /> {mobile ? "Paid" : entry.orderRef}
            </span>
          )}
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: etsy ? "7px 8px 7px 14px" : "7px 8px 7px 16px", background: "rgba(255,253,245,.82)", backdropFilter: "blur(10px)", borderRadius: "var(--r-pill)", boxShadow: "var(--sh-sm)" }}>
          {/* undo / redo / share cluster */}
          {undo && (
            <div style={{ display: "flex", alignItems: "center", gap: 2, marginRight: 2 }}>
              <button onClick={undo} disabled={!canUndo} title="Undo (⌘Z)" aria-label="Undo"
                style={{ width: 34, height: 34, borderRadius: "50%", border: "none", background: "transparent", color: canUndo ? "var(--ink-2)" : "var(--ink-soft)", cursor: canUndo ? "pointer" : "default", display: "flex", alignItems: "center", justifyContent: "center", opacity: canUndo ? 1 : .45 }}>
                <Icon name="Undo2" size={17} />
              </button>
              <button onClick={redo} disabled={!canRedo} title="Redo (⇧⌘Z)" aria-label="Redo"
                style={{ width: 34, height: 34, borderRadius: "50%", border: "none", background: "transparent", color: canRedo ? "var(--ink-2)" : "var(--ink-soft)", cursor: canRedo ? "pointer" : "default", display: "flex", alignItems: "center", justifyContent: "center", opacity: canRedo ? 1 : .45 }}>
                <Icon name="Redo2" size={17} />
              </button>
              {onShare && !mobile && (
                <button onClick={onShare} title="Copy a share link" aria-label="Share"
                  style={{ width: 34, height: 34, borderRadius: "50%", border: "none", background: "transparent", color: "var(--ink-2)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <Icon name="Share2" size={16} />
                </button>
              )}
              <span style={{ width: 1, height: 22, background: "var(--line-2)", margin: "0 2px" }} />
            </div>
          )}
          {!etsy && <span style={{ fontFamily: "var(--serif)", fontSize: 20, fontWeight: 600 }}>${price}</span>}
          {etsy && !mobile && <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-2)" }}>{entry.purchased}</span>}
          <button className="btn btn-primary" style={{ minHeight: 40, padding: "10px 18px", fontSize: 14 }} onClick={etsy ? openOutput : openReview}>
            {etsy ? <><Icon name="Download" size={16} />{mobile ? "" : " Download"}</> : <><Icon name="ShoppingBag" size={16} />{mobile ? "" : " Add to cart"}</>}
          </button>
        </div>
      </div>

      {photoLive && !design.photo
        ? <div className="hand-note" style={{ position: "absolute", top: mobile ? 66 : 86, right: 24, fontSize: 20, transform: "rotate(-5deg)", zIndex: 5, opacity: mobile ? 0 : .92 }}>tap Photo to add yours →</div>
        : <div className="hand-note" style={{ position: "absolute", top: mobile ? 66 : 86, right: 26, fontSize: 21, transform: "rotate(-5deg)", zIndex: 5, opacity: mobile ? 0 : .9 }}>make it yours →</div>}

      {/* bottom: tray + dock */}
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, display: "flex", flexDirection: "column", alignItems: "center", padding: mobile ? "0" : "0 18px 18px", zIndex: 7, gap: 12 }}>
        {tool && (
          <div style={{
            width: mobile ? "100%" : "min(680px, 100%)",
            background: "var(--card)", borderRadius: mobile ? "var(--r-lg) var(--r-lg) 0 0" : "var(--r-lg)",
            boxShadow: "var(--sh-lg)", border: "1px solid var(--line)",
            padding: mobile ? "16px 16px 14px" : "20px 22px",
            animation: mobile ? "sheetUp .26s var(--ease-out)" : "riseIn .22s var(--ease-out)",
            maxHeight: mobile ? "52vh" : "auto", overflowY: "auto",
          }} className="scroll-y">
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 15 }}>
              <span style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 600 }}>{TOOL_TITLE[tool]}</span>
              <button className="btn-icon btn-ghost" style={{ width: 34, height: 34, minHeight: 34 }} onClick={() => setTool(null)} aria-label="Close"><Icon name="X" size={17} /></button>
            </div>
            <TrayBody tool={tool} design={design} update={update} lock={lockFormat} />
          </div>
        )}
        {/* dock */}
        <div className="no-scrollbar" style={{
          display: "flex", gap: mobile ? 4 : 6, padding: 7,
          background: "rgba(255,253,245,.9)", backdropFilter: "blur(12px)",
          borderRadius: mobile ? 0 : "var(--r-pill)", boxShadow: "var(--sh-lg)", border: "1px solid var(--line)",
          maxWidth: "100%", overflowX: "auto",
          width: mobile ? "100%" : "auto", justifyContent: mobile ? "space-between" : "center",
          paddingBottom: mobile ? "calc(7px + env(safe-area-inset-bottom))" : 7,
        }}>
          {TOOLS_B.map(([k, ic, lbl]) => {
            const active = tool === k;
            const locked = (lockFormat && (k === "size" || k === "frame")) || (design.custom && (k === "font" || k === "color" || (k === "photo" && !design.hasPhotoZone)));
            return (
              <button key={k} onClick={() => setTool(active ? null : k)} title={lbl}
                style={{ position: "relative", display: "flex", flexDirection: "column", alignItems: "center", gap: 4, padding: mobile ? "8px 6px" : "9px 14px", borderRadius: "var(--r-md)", border: "none", background: active ? "var(--clay)" : "transparent", color: active ? "#FFF7EF" : "var(--ink-2)", cursor: "pointer", flex: mobile ? 1 : "none", minWidth: mobile ? 0 : 56, transition: "background .15s" }}>
                <Icon name={ic} size={20} />
                <span style={{ fontSize: 10.5, fontWeight: 600 }}>{lbl}</span>
                {locked && <span style={{ position: "absolute", top: 5, right: mobile ? 8 : 10, color: active ? "#FFF7EF" : "var(--ink-3)" }}><Icon name="Lock" size={10} /></span>}
              </button>
            );
          })}
        </div>
      </div>

      {review && <ReviewSheet design={design} entry={entry} onConfirm={confirm} onClose={() => setReview(false)} />}
      {output && <OutputFlow design={design} update={update} entry={entry} bp={bp} onClose={() => setOutput(false)} onOrder={() => {}} onCheckout={openPrintCheckout} />}
      {checkout && <CheckoutFlow lineItem={checkout.lineItem} subtotal={checkout.subtotal} credit={checkout.credit} entry={entry} bp={bp} onClose={() => setCheckout(null)} onPlaced={() => {}} />}
      {done && <DoneScreen order={done} entry={entry} onRestart={restart} />}
      {showIntro && <Onboarding entry={entry} onClose={onCloseIntro} />}
    </div>
  );
}

Object.assign(window, { VariantB });
