// WORTH platform sweep — single-screen viewer.
// One screen, one page. A quiet toolbar lets you switch device (Mac · iPad ·
// iPhone), platform (iOS / Android — Windows/Android parity is the same
// layout), and theme. The selected frame is scaled to fit the viewport so you
// can design each screen per-device at full size, then iterate.

function frameSize(device, os, orientation) {
  const D = window.DEVICE;
  if (device === "mac") return { w: D.desktop.abW, h: D.desktop.abH };
  if (device === "iphone") return os === "android" ? { w: D.phoneAndroid.abW, h: D.phoneAndroid.abH } : { w: D.phoneIOS.abW, h: D.phoneIOS.abH };
  return orientation === "portrait" ? { w: D.tabletPortrait.abW, h: D.tabletPortrait.abH } : { w: D.tabletLandscape.abW, h: D.tabletLandscape.abH };
}

function Segmented({ value, onChange, options }) {
  return (
    <div style={{ display: "flex", gap: 2, padding: 3, background: "var(--panel-soft)", border: "1px solid var(--line)", borderRadius: 999 }}>
      {options.map((o) => {
        const on = o.id === value;
        return (
          <button key={o.id} onClick={() => onChange(o.id)} style={{
            display: "flex", alignItems: "center", gap: 6, border: "none", cursor: "pointer",
            padding: "6px 13px", borderRadius: 999, fontFamily: "var(--font-text)", fontSize: 12.5, fontWeight: on ? 700 : 500,
            background: on ? "var(--charcoal)" : "transparent", color: on ? "var(--charcoal-fg)" : "var(--muted)",
            transition: "background .15s, color .15s",
          }}>
            {o.icon && <Icon name={o.icon} size={14} color={on ? "var(--charcoal-fg)" : "var(--muted)"} />}
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

function ScreenViewer({ title, subtitle, renderScreen, devices = ["mac", "ipad", "iphone"], ipadOrientation = "landscape", lightLocked = false, noTheme = false, hasPlatform = true }) {
  const KEY = "worth-viewer:" + location.pathname;
  const saved = (() => { try { return JSON.parse(localStorage.getItem(KEY) || "{}"); } catch { return {}; } })();
  const [device, setDevice] = React.useState(saved.device && devices.includes(saved.device) ? saved.device : devices[0]);
  const [os, setOs] = React.useState(saved.os || "ios");
  const [theme, setTheme] = React.useState(lightLocked || noTheme ? "light" : (saved.theme || "light"));
  const [vp, setVp] = React.useState({ w: window.innerWidth, h: window.innerHeight });

  React.useEffect(() => {
    const r = () => setVp({ w: window.innerWidth, h: window.innerHeight });
    window.addEventListener("resize", r); return () => window.removeEventListener("resize", r);
  }, []);
  React.useEffect(() => {
    try { localStorage.setItem(KEY, JSON.stringify({ device, os, theme })); } catch {}
  }, [device, os, theme]);

  const showPlatform = hasPlatform && device !== "mac";
  const effOs = device === "mac" ? "ios" : os;
  const size = frameSize(device, effOs, ipadOrientation);
  const toolbarH = 60;
  const padV = 40, padH = 48;
  const scale = Math.min((vp.w - padH * 2) / size.w, (vp.h - toolbarH - padV * 2) / size.h, 1);

  const deviceOpts = devices.map((d) => ({
    mac: { id: "mac", label: "Mac", icon: "command" },
    ipad: { id: "ipad", label: "iPad", icon: "layers" },
    iphone: { id: "iphone", label: "iPhone", icon: "message-circle" },
  }[d]));

  return (
    <div style={{ width: "100vw", height: "100vh", display: "flex", flexDirection: "column", background: "var(--paper)", overflow: "hidden" }}>
      {/* toolbar */}
      <div style={{ height: toolbarH, flexShrink: 0, display: "flex", alignItems: "center", gap: 16, padding: "0 22px", borderBottom: "1px solid var(--line)", background: "var(--panel)" }}>
        <a href="./index.html" style={{ display: "flex", alignItems: "center", gap: 8, textDecoration: "none", color: "var(--muted)" }}>
          <Icon name="arrow-left" size={17} color="var(--muted)" />
          <span style={{ fontFamily: "var(--font-wordmark)", fontWeight: 900, letterSpacing: "0.06em", textTransform: "uppercase", fontSize: 13, color: "var(--ink)" }}>WORTH</span>
        </a>
        <div style={{ width: 1, height: 22, background: "var(--line)" }} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-text)", fontSize: 14, fontWeight: 700, color: "var(--ink)", lineHeight: 1.1 }}>{title}</div>
          {subtitle && <div style={{ fontFamily: "var(--font-text)", fontSize: 11.5, color: "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{subtitle}</div>}
        </div>
        <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", justifyContent: "flex-end" }}>
          <Segmented value={device} onChange={setDevice} options={deviceOpts} />
          {showPlatform && <Segmented value={os} onChange={setOs} options={[{ id: "ios", label: "iOS" }, { id: "android", label: "Android" }]} />}
          {!noTheme && !lightLocked && <Segmented value={theme} onChange={setTheme} options={[{ id: "light", label: "Light", icon: "sun" }, { id: "dark", label: "Dark", icon: "moon" }]} />}
          {lightLocked && <span style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--font-text)", fontSize: 11.5, fontWeight: 600, color: "var(--muted)", padding: "5px 11px", borderRadius: 999, background: "var(--panel-soft)", border: "1px solid var(--line)" }}><Icon name="lock" size={13} color="var(--muted)" /> Light-locked</span>}
          {noTheme && <span style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: "var(--font-text)", fontSize: 11.5, fontWeight: 600, color: "var(--muted)", padding: "5px 11px", borderRadius: 999, background: "var(--panel-soft)", border: "1px solid var(--line)" }}>Night reveal</span>}
        </div>
      </div>
      {/* stage */}
      <div style={{ flex: 1, minHeight: 0, display: "grid", placeItems: "center", padding: padV + "px " + padH + "px", background: "radial-gradient(1200px 700px at 50% -10%, #efece1, #e7e2d5 65%, #ddd7c8)" }}>
        <div style={{ width: size.w * scale, height: size.h * scale, flexShrink: 0 }}>
          <div style={{ width: size.w, height: size.h, transform: `scale(${scale})`, transformOrigin: "top left", borderRadius: 18, overflow: "hidden", boxShadow: "0 30px 90px rgba(31,28,20,0.22)" }}>
            {renderScreen({ device, os: effOs, theme, orientation: ipadOrientation })}
          </div>
        </div>
      </div>
    </div>
  );
}

// Map viewer device names → screen component's device prop, then mount.
// Comp may be a component OR a global name string (resolved live, so script
// load-order races can't strand the mount).
function mountScreen(Comp, opts) {
  const resolve = () => (typeof Comp === "string" ? window[Comp] : Comp);
  const renderScreen = ({ device, os, theme, orientation }) => {
    const C = resolve();
    const d = device === "mac" ? "desktop" : device === "iphone" ? "phone" : (orientation === "portrait" ? "tabletP" : "tabletL");
    return <C device={d} os={os} theme={theme} />;
  };
  function go() {
    if (!window.WORTHDesignSystem_70d33b || !window.DEVICE || !resolve()) { setTimeout(go, 40); return; }
    const el = document.getElementById("root");
    // Reuse our own root if this exact element already owns one; otherwise
    // swap in a fresh node so a stale React root (e.g. persisted across an
    // in-realm navigation) can't keep rendering old content into it.
    if (el.__worthMounted) {
      el.__worthMounted.render(<ScreenViewer renderScreen={renderScreen} {...opts} />);
      return;
    }
    const fresh = el.cloneNode(false);
    el.parentNode.replaceChild(fresh, el);
    const root = ReactDOM.createRoot(fresh);
    fresh.__worthMounted = root;
    root.render(<ScreenViewer renderScreen={renderScreen} {...opts} />);
  }
  go();
}

Object.assign(window, { ScreenViewer, mountScreen, frameSize });
