/* Shell: responsive device frames + shared design state (Canvas direction) */
const { useState, useRef, useEffect, useLayoutEffect } = React;
const { PS_DATA: DS } = window;

const DEVICES = [
  { id: "desktop", w: 1280, h: 800, bp: "desktop", label: "Desktop", icon: "Monitor", chrome: "browser" },
  { id: "tablet",  w: 834,  h: 1040, bp: "tablet", label: "Tablet", icon: "Tablet", chrome: "device" },
  { id: "mobile",  w: 390,  h: 820, bp: "mobile", label: "Phone", icon: "Smartphone", chrome: "device" },
];

function BrowserChrome({ children, mode }) {
  const url = mode === "etsy" ? "bellemaison.com/personalize?order=ETSY-4827-1193" : "bellemaison.com/studio";
  return (
    <div style={{ width: "100%", height: "100%", display: "flex", flexDirection: "column", borderRadius: 14, overflow: "hidden", boxShadow: "var(--sh-lg)", background: "#fff", border: "1px solid var(--line-2)" }}>
      <div style={{ height: 42, flex: "none", display: "flex", alignItems: "center", gap: 14, padding: "0 16px", background: "#EDE4D4", borderBottom: "1px solid var(--line-2)" }}>
        <div style={{ display: "flex", gap: 7 }}>
          {["#E2A08A", "#E6C788", "#A8C194"].map((c, i) => <span key={i} style={{ width: 12, height: 12, borderRadius: "50%", background: c }} />)}
        </div>
        <div style={{ flex: 1, maxWidth: 420, margin: "0 auto", height: 26, borderRadius: 99, background: "#FBF6EC", border: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 7, padding: "0 12px", color: "var(--ink-3)", fontSize: 12.5, overflow: "hidden", whiteSpace: "nowrap" }}>
          <Icon name="Lock" size={11} style={{ flex: "none" }} /> {url}
        </div>
        <div style={{ width: 46 }} />
      </div>
      <div style={{ flex: 1, minHeight: 0 }}>{children}</div>
    </div>
  );
}
function DeviceChrome({ children, mobile }) {
  const pad = mobile ? 11 : 13;
  const sbH = mobile ? 36 : 28;
  return (
    <div style={{ width: "100%", height: "100%", borderRadius: mobile ? 46 : 40, background: "linear-gradient(150deg,#2B2620,#403930)", padding: pad, boxShadow: "var(--sh-lg)" }}>
      <div style={{ width: "100%", height: "100%", borderRadius: mobile ? 36 : 30, overflow: "hidden", position: "relative", background: "var(--paper)", display: "flex", flexDirection: "column" }}>
        <div style={{ position: "absolute", top: 9, left: "50%", transform: "translateX(-50%)", width: mobile ? 110 : 84, height: mobile ? 24 : 16, background: "#241F1A", borderRadius: 99, zIndex: 50 }} />
        <div style={{ flex: "none", height: sbH, display: "flex", alignItems: "center", justifyContent: "space-between", padding: mobile ? "0 26px 0 24px" : "0 22px", color: "var(--ink)", background: "var(--card)", position: "relative", zIndex: 40 }}>
          <span style={{ fontSize: mobile ? 13 : 12, fontWeight: 700, letterSpacing: ".02em" }}>9:41</span>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <Icon name="SignalHigh" size={mobile ? 16 : 14} stroke={2.2} />
            <Icon name="Wifi" size={mobile ? 15 : 13} stroke={2.2} />
            <Icon name="BatteryFull" size={mobile ? 17 : 15} stroke={2} />
          </div>
        </div>
        <div style={{ flex: 1, minHeight: 0 }}>{children}</div>
      </div>
    </div>
  );
}

function Toast({ show, label }) {
  return (
    <div style={{ position: "fixed", top: show ? 18 : -60, left: "50%", transform: "translateX(-50%)", zIndex: 200, transition: "top .35s var(--ease-out)", display: "flex", alignItems: "center", gap: 9, padding: "12px 20px", background: "var(--ink)", color: "#FBF4E8", borderRadius: 99, boxShadow: "var(--sh-lg)", fontSize: 14, fontWeight: 600 }}>
      <Icon name="CircleCheck" size={18} style={{ color: "#A8C194" }} /> {label}
    </div>
  );
}

function Seg({ items, value, onChange, getIcon, getLabel, getId }) {
  return (
    <div style={{ display: "inline-flex", padding: 4, gap: 3, background: "var(--paper-2)", borderRadius: "var(--r-pill)", border: "1px solid var(--line)" }}>
      {items.map(it => {
        const id = getId(it), active = value === id;
        return (
          <button key={id} onClick={() => onChange(id)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 15px", borderRadius: "var(--r-pill)", border: "none", cursor: "pointer", fontSize: 13.5, fontWeight: 600, background: active ? "var(--card)" : "transparent", color: active ? "var(--ink)" : "var(--ink-3)", boxShadow: active ? "var(--sh-sm)" : "none", transition: "background .15s, color .15s" }}>
            {getIcon && <Icon name={getIcon(it)} size={15} />}{getLabel(it)}
          </button>
        );
      })}
    </div>
  );
}

const MODES = [
  { id: "shop", label: "Direct shop", icon: "Store" },
  { id: "etsy", label: "Etsy order", icon: "ShoppingBag" },
];
function loadDesign(mode) {
  const base = DS.defaultDesign(DS.ENTRIES[mode]);
  try {
    const raw = localStorage.getItem("ps_design_" + mode);
    if (raw) return { ...base, ...JSON.parse(raw) };
  } catch (e) {}
  return base;
}

function App() {
  const [mode, setMode] = useState("shop");
  const { design, update, reset, undo, redo, canUndo, canRedo } = useHistory(() => loadDesign("shop"));
  const [intro, setIntro] = useState(true);
  const [verified, setVerified] = useState(false);
  const [etsyEntry, setEtsyEntry] = useState(null);
  const entry = mode === "etsy" ? (etsyEntry || DS.ENTRIES.etsy) : DS.ENTRIES[mode];
  const [device, setDevice] = useState("desktop");
  const [scale, setScale] = useState(1);
  const [toast, setToast] = useState(null);
  const stageRef = useRef(null);
  const toastT = useRef(null);

  const showToast = label => { setToast(label); clearTimeout(toastT.current); toastT.current = setTimeout(() => setToast(null), 2400); };
  const resetDesign = () => reset(DS.defaultDesign(entry));

  // persist current design per mode
  useEffect(() => {
    try { localStorage.setItem("ps_design_" + mode, JSON.stringify(design)); } catch (e) {}
  }, [design, mode]);

  // load a shared design from the URL hash on first mount
  useEffect(() => {
    const shared = window.PS_SHARE && window.PS_SHARE.readSharedDesign();
    if (shared) { reset({ ...DS.defaultDesign(DS.ENTRIES.shop), ...shared }); setIntro(false); showToast("Opened a shared design"); }
  }, []);

  // keyboard: Cmd/Ctrl+Z undo, Shift+Cmd/Ctrl+Z (or Ctrl+Y) redo
  useEffect(() => {
    const onKey = e => {
      const meta = e.metaKey || e.ctrlKey;
      if (!meta) return;
      const k = e.key.toLowerCase();
      if (k === "z" && !e.shiftKey) { e.preventDefault(); undo(); }
      else if ((k === "z" && e.shiftKey) || k === "y") { e.preventDefault(); redo(); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [undo, redo]);

  const switchMode = m => {
    if (m === mode) return;
    setMode(m);
    reset(loadDesign(m));
    setIntro(true);
    setVerified(false);
    setEtsyEntry(null);
  };

  const onVerified = e => {
    setEtsyEntry(e);
    // re-seed the design from the verified order's locked size/frame + template
    reset({ ...DS.defaultDesign(e), ...loadDesign("etsy"), size: e.lockSize, frame: e.lockFrame });
    setVerified(true);
  };

  const doShare = () => {
    const url = window.PS_SHARE.shareURL(design);
    const finish = ok => showToast(ok ? "Share link copied!" : "Link ready — copy from the address bar");
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(url).then(() => finish(true)).catch(() => { try { location.hash = "d=" + window.PS_SHARE.encodeDesign(design); } catch (e) {} finish(false); });
    } else { try { location.hash = "d=" + window.PS_SHARE.encodeDesign(design); } catch (e) {} finish(false); }
  };

  const dev = DEVICES.find(d => d.id === device);

  useLayoutEffect(() => {
    const fit = () => {
      const el = stageRef.current; if (!el) return;
      const availW = el.clientWidth - 48, availH = el.clientHeight - 48;
      setScale(Math.min(availW / dev.w, availH / dev.h, 1));
    };
    fit();
    const ro = new ResizeObserver(fit);
    if (stageRef.current) ro.observe(stageRef.current);
    window.addEventListener("resize", fit);
    return () => { ro.disconnect(); window.removeEventListener("resize", fit); };
  }, [device]);

  const needsVerify = mode === "etsy" && !verified;
  const inner = needsVerify
    ? <VerifyGate onVerified={onVerified} />
    : <VariantB design={design} update={update} bp={dev.bp} entry={entry}
        showIntro={intro} onCloseIntro={() => setIntro(false)} onResetDesign={resetDesign}
        undo={undo} redo={redo} canUndo={canUndo} canRedo={canRedo} onShare={doShare} />;
  const framed = dev.chrome === "browser"
    ? <BrowserChrome mode={mode}>{inner}</BrowserChrome>
    : <DeviceChrome mobile={dev.id === "mobile"}>{inner}</DeviceChrome>;

  return (
    <div style={{ height: "100vh", display: "flex", flexDirection: "column", background: "var(--paper)", overflow: "hidden" }}>
      <Toast show={!!toast} label={toast || ""} />
      {/* top toolbar */}
      <div style={{ flex: "none", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "12px 20px", borderBottom: "1px solid var(--line)", background: "var(--card)", flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 13, minWidth: 0 }}>
          <div style={{ width: 34, height: 34, borderRadius: 9, background: "var(--ink)", color: "#FBF4E8", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="Frame" size={19} /></div>
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, minWidth: 0 }}>
            <span style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 600, whiteSpace: "nowrap" }}>Poster Studio</span>
            <span style={{ fontSize: 12, color: "var(--ink-3)", whiteSpace: "nowrap" }}>Working editor · responsive</span>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <Seg items={MODES} value={mode} onChange={switchMode} getId={m => m.id} getIcon={m => m.icon} getLabel={m => m.label} />
          <Seg items={DEVICES} value={device} onChange={setDevice} getId={d => d.id} getIcon={d => d.icon} getLabel={d => d.label} />
          <button onClick={() => setIntro(true)} title="Show intro" className="btn-icon btn-ghost" style={{ width: 40, height: 40, minHeight: 40 }}><Icon name="CircleHelp" size={17} /></button>
          <a href="Admin.html" title="Admin orders" style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 15px", borderRadius: "var(--r-pill)", border: "1.5px solid var(--line-2)", color: "var(--ink-2)", textDecoration: "none", fontSize: 13.5, fontWeight: 600 }}><Icon name="LayoutDashboard" size={15} /> Admin</a>
          <a href="Proof.html" title="Customer proof page" style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 15px", borderRadius: "var(--r-pill)", border: "1.5px solid var(--line-2)", color: "var(--ink-2)", textDecoration: "none", fontSize: 13.5, fontWeight: 600 }}><Icon name="BadgeCheck" size={15} /> Proof</a>
          <a href="Plan & Report.html" style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 15px", borderRadius: "var(--r-pill)", border: "1.5px solid var(--line-2)", color: "var(--ink-2)", textDecoration: "none", fontSize: 13.5, fontWeight: 600 }}><Icon name="FileText" size={15} /> Report</a>
        </div>
      </div>

      {/* caption */}
      <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 10, padding: "9px 22px", background: "var(--card-warm)", borderBottom: "1px solid var(--line)", fontSize: 13 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "4px 11px", borderRadius: 99, background: "var(--clay-tint)", color: "var(--clay-dark)", fontWeight: 700, fontSize: 12 }}><Icon name={mode === "etsy" ? "ShoppingBag" : "Store"} size={13} /> {mode === "etsy" ? "Etsy order completion" : "Direct shop"}</span>
        <span style={{ color: "var(--ink-2)" }}>{mode === "etsy"
          ? "Customer already paid on Etsy — size & frame are locked; they personalize and submit their design."
          : "Live sale on the poster site — full choice of size & frame, running price, add to cart."}</span>
      </div>

      {/* stage */}
      <div ref={stageRef} style={{ flex: 1, minHeight: 0, position: "relative", display: "flex", alignItems: "center", justifyContent: "center", padding: 24, background: "repeating-linear-gradient(45deg, var(--paper), var(--paper) 11px, var(--paper-2) 11px, var(--paper-2) 22px)" }}>
        <div style={{ width: dev.w, height: dev.h, flex: "none", transform: `scale(${scale})`, transformOrigin: "center center" }}>
          {framed}
        </div>
      </div>
    </div>
  );
}

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