// DeviceDuo: laptop + phone frames showing a live site that auto-scrolls.
// The site loads automatically when the frames scroll into view (IntersectionObserver,
// so the page still opens fast), then the iframe is panned up/down inside the clipped
// screen to simulate continuous live scrolling — cross-origin means we cannot script
// scroll inside the site itself, so we translate the whole rendered page instead.
const NS_LIVE = window.AnsysDigitalDesignSystem_4543d7;

if (!document.getElementById("ls-scroll-kf")) {
  const st = document.createElement("style");
  st.id = "ls-scroll-kf";
  st.textContent =
    "@keyframes lsScroll{0%,6%{transform:translateY(0)}50%,56%{transform:translateY(var(--ls-shift))}100%{transform:translateY(0)}}" +
    "@keyframes lsPan{0%,6%{object-position:center 0%}50%,56%{object-position:center 100%}100%{object-position:center 0%}}" +
    "@media (prefers-reduced-motion:reduce){.ls-shot{animation:none!important}}" +
    "@keyframes spin{to{transform:rotate(360deg)}}" +
    "@media (prefers-reduced-motion:reduce){.ls-pan{animation:none!important}}";
  document.head.appendChild(st);
}

// Render order: `shot` screenshot (best) > live iframe when `liveFrame` is explicitly
// enabled for a store confirmed to allow framing > branded "Visit store" panel.
// Most Shopify storefronts send X-Frame-Options / CSP frame-ancestors, and a refused
// frame still fires `load`, so framing cannot be feature-detected — hence the opt-in.
function DeviceDuo({ url, name, shot, liveFrame = false }) {
  const [live, setLive] = React.useState(false);
  const [shotFailed, setShotFailed] = React.useState(false);
  // Client storefronts refuse to be framed (X-Frame-Options / CSP frame-ancestors) and a
  // refused frame still fires load, so framing can't be detected. Real screenshots are
  // rendered instead: a local `shot` file when supplied, otherwise WordPress mShots.
  const [src2, setSrc2] = React.useState(false);
  const bare = url.replace(/^https?:\/\//, "").replace(/\/$/, "");
  const autoShot = (w, h) => src2
    ? "https://image.thum.io/get/width/" + w + (h ? "/crop/" + h : "") + "/noanimate/https://" + bare
    : "https://s.wordpress.com/mshots/v1/" + encodeURIComponent(url) + "?w=" + w + (h ? "&h=" + h : "");
  const [lapScale, setLapScale] = React.useState(0.34);
  const [phScale, setPhScale] = React.useState(0.34);
  const rootRef = React.useRef(null);
  const lapRef = React.useRef(null);
  const phRef = React.useRef(null);

  // Load the live site only once the frames are on screen.
  React.useEffect(() => {
    if (!rootRef.current || live) return;
    const io = new IntersectionObserver((entries) => {
      if (entries.some((e) => e.isIntersecting)) { setLive(true); io.disconnect(); }
    }, { rootMargin: "200px" });
    io.observe(rootRef.current);
    return () => io.disconnect();
  }, [live]);

  React.useEffect(() => {
    let raf = 0;
    const measure = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        if (lapRef.current) { const n = lapRef.current.clientWidth / 1280; setLapScale((p) => Math.abs(n - p) < 0.002 ? p : n); }
        if (phRef.current) { const n = phRef.current.clientWidth / 390; setPhScale((p) => Math.abs(n - p) < 0.002 ? p : n); }
      });
    };
    measure();
    window.addEventListener("resize", measure);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", measure); };
  }, [live]);

  const host = url.replace(/^https?:\/\//, "").replace(/\/$/, "");
  const Loading = ({ small }) => (
    <div style={{ position: "absolute", inset: 0, background: "linear-gradient(160deg,var(--blue-50),var(--neutral-100))", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: small ? 6 : 10, padding: 8, textAlign: "center" }}>
      <span style={{ width: small ? 22 : 30, height: small ? 22 : 30, borderRadius: "50%", border: "2.5px solid var(--brand)", borderTopColor: "transparent", animation: "spin 0.9s linear infinite" }} />
      <span style={{ fontFamily: "var(--font-mono)", fontSize: small ? 8 : 11, color: "var(--text-muted)", wordBreak: "break-all", maxWidth: "90%" }}>{host}</span>
    </div>
  );

  const Fallback = ({ small }) => (
    <a href={url} target="_blank" rel="noopener" style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: small ? 5 : 10, padding: small ? 6 : 16, textAlign: "center", textDecoration: "none", background: "linear-gradient(155deg,var(--blue-50),color-mix(in oklab,var(--blue-50),#fff 55%))" }}>
      <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: small ? 11 : 22, letterSpacing: "var(--tracking-tight)", color: "var(--brand)", lineHeight: 1.15 }}>{name}</span>
      {!small ? <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-muted)", wordBreak: "break-all", maxWidth: "88%" }}>{host}</span> : null}
      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, marginTop: small ? 2 : 6, padding: small ? "3px 7px" : "7px 14px", borderRadius: 99, background: "var(--brand)", color: "#fff", fontFamily: "var(--font-display)", fontWeight: 700, fontSize: small ? 7.5 : 12.5 }}>Visit store</span>
    </a>
  );

  const Chrome = () => (
    <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 22, zIndex: 4, display: "flex", alignItems: "center", gap: 6, padding: "0 8px", background: "rgba(248,250,253,.96)", borderBottom: "1px solid rgba(14,23,42,.08)", backdropFilter: "blur(6px)" }}>
      <span style={{ display: "flex", gap: 3 }}>
        {["#f96058", "#fbbe3c", "#3cc84a"].map((c) => <span key={c} style={{ width: 5, height: 5, borderRadius: 99, background: c }} />)}
      </span>
      <span style={{ flex: 1, height: 12, borderRadius: 99, background: "#fff", border: "1px solid rgba(14,23,42,.1)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontSize: 7, color: "var(--text-muted)", letterSpacing: ".01em", overflow: "hidden", whiteSpace: "nowrap" }}>{host}</span>
    </div>
  );

  const Shot = ({ w, h, dur, chrome }) => (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden", background: "#fff" }}>
      {chrome ? <Chrome /> : null}
      <img className="ls-shot" src={shot || autoShot(w, h)} alt={name + " storefront"} loading="lazy"
        onError={() => { if (!src2) setSrc2(true); else setShotFailed(true); }}
        style={{ display: "block", width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 0%", animation: "lsPan " + (dur || 26) + "s ease-in-out infinite" }} />
    </div>
  );

  // laptop: render tall page (2600) and pan it; screen shows ~800 local px
  const lapRender = 2600, lapShift = -(lapRender - 800);
  const phRender = 2600, phShift = -(phRender - 823);

  return (
    <div ref={rootRef} className="devices" style={{ position: "relative", width: "100%", paddingBottom: 6 }}>
      {/* Laptop */}
      <div className="laptop" style={{ width: "84%" }}>
        <div style={{ background: "#1E2434", borderRadius: "14px 14px 5px 5px", padding: 8, boxShadow: "var(--shadow-lg)" }}>
          <div ref={lapRef} style={{ position: "relative", borderRadius: 6, overflow: "hidden", background: "#fff", aspectRatio: "16/10" }}>
            {liveFrame && live ? (
              <div style={{ position: "absolute", top: 0, left: 0, width: 1280, transformOrigin: "top left", transform: "scale(" + lapScale + ")" }}>
                <div className="ls-pan" style={{ "--ls-shift": lapShift + "px", animation: "lsScroll 26s ease-in-out infinite" }}>
                  <iframe src={url} title={name + " desktop"} loading="lazy" scrolling="no"
                    referrerPolicy="no-referrer-when-downgrade"
                    style={{ display: "block", width: 1280, height: lapRender, border: 0 }} />
                </div>
              </div>
            ) : shotFailed ? <Fallback /> : <Shot w={1280} h={800} dur={26} chrome />}
          </div>
        </div>
        <div style={{ height: 11, background: "linear-gradient(#c7ccd8,#9aa2b4)", borderRadius: "0 0 10px 10px", margin: "0 -6%", boxShadow: "var(--shadow-sm)" }}>
          <div style={{ width: 70, height: 5, background: "rgba(0,0,0,.18)", borderRadius: "0 0 7px 7px", margin: "0 auto" }} />
        </div>
      </div>
      {/* Phone */}
      <div className="phone" style={{ position: "absolute", right: 0, bottom: 0, width: "31%", maxWidth: 150, minWidth: 104 }}>
        <div style={{ background: "#1E2434", borderRadius: 26, padding: 6, boxShadow: "var(--shadow-lg)" }}>
          <div ref={phRef} style={{ position: "relative", borderRadius: 20, overflow: "hidden", background: "#fff", aspectRatio: "9/19" }}>
            <div style={{ position: "absolute", top: 0, left: "50%", transform: "translateX(-50%)", width: 48, height: 13, background: "#1E2434", borderRadius: "0 0 10px 10px", zIndex: 3 }} />
            {liveFrame && live ? (
              <div style={{ position: "absolute", top: 0, left: 0, width: 390, transformOrigin: "top left", transform: "scale(" + phScale + ")" }}>
                <div className="ls-pan" style={{ "--ls-shift": phShift + "px", animation: "lsScroll 26s ease-in-out infinite" }}>
                  <iframe src={url} title={name + " mobile"} loading="lazy" scrolling="no"
                    referrerPolicy="no-referrer-when-downgrade"
                    style={{ display: "block", width: 390, height: phRender, border: 0 }} />
                </div>
              </div>
            ) : shotFailed ? <Fallback small /> : <Shot w={420} h={900} dur={30} />}
          </div>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { DeviceDuo });
