/* ============================================================
   PhoneMockup — iPhone-style frame with a live Instagram profile
   view of @kscosmeticos_ofc. Reads data from
   window.KS_INSTAGRAM_DATA (set by ks-instagram-data.js), then
   layers "live feel" animations on top: rolling follower counter,
   heart popups, a pulsing LIVE badge, and a ticking timestamp.

   Static base data + fake liveness — no backend required. To
   sync with reality, just edit ks-instagram-data.js.
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ------- utilities ------- */
function formatCount(n) {
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, "") + "M";
  if (n >= 1_000)     return (n / 1_000).toFixed(1).replace(/\.0$/, "") + "K";
  return String(n);
}
function useNow(tickMs = 1000) {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), tickMs);
    return () => clearInterval(id);
  }, [tickMs]);
  return now;
}

/* ============================================================
   Main component

   The screen renders a single stitched screenshot of the KS
   Cosméticos Instagram profile (top block + grid), auto-scrolling
   slowly from top to bottom on a loop. No LIVE badge, no heart
   stream, no follower pulse — just a calm playback of a real
   captured screen.
   ============================================================ */
function PhoneMockup() {
  const sessionStart = useRef(Date.now());
  const trackRef = useRef(null);
  const [contentH, setContentH] = useState(0);
  const [viewportH, setViewportH] = useState(0);

  // Measure once the image loads so we can compute the scroll distance.
  useEffect(() => {
    const el = trackRef.current;
    if (!el) return;
    const img = el.querySelector("img");
    const measure = () => {
      setContentH(el.scrollHeight);
      setViewportH(el.parentElement ? el.parentElement.clientHeight : 0);
    };
    if (img && !img.complete) {
      img.addEventListener("load", measure, { once: true });
    }
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, []);

  // Slow ambient scroll — full loop every ~24s, pauses at each end.
  const distance = Math.max(0, contentH - viewportH);

  return (
    <div className="phone-mockup" aria-hidden="true">
      <div className="phone-frame">
        <span className="phone-btn phone-btn--power" aria-hidden="true" />
        <span className="phone-btn phone-btn--volup"  aria-hidden="true" />
        <span className="phone-btn phone-btn--voldn"  aria-hidden="true" />
        <span className="phone-btn phone-btn--mute"   aria-hidden="true" />

        <div className="phone-screen">
          {/* Dynamic Island — plain, no LIVE badge */}
          <div className="phone-island" aria-hidden="true" />

          {/* iOS status bar overlays the top of the screenshot */}
          <div className="ios-statusbar" aria-hidden="true">
            <StatusBarClock start={sessionStart.current} />
            <div className="ios-statusbar-icons">
              <svg viewBox="0 0 18 12" width="17" height="11"><g fill="currentColor"><rect x="0"  y="8" width="3" height="4" rx="0.6"/><rect x="5"  y="5" width="3" height="7" rx="0.6"/><rect x="10" y="2" width="3" height="10" rx="0.6"/><rect x="15" y="0" width="3" height="12" rx="0.6"/></g></svg>
              <span className="ios-wifi" aria-label="wifi">
                <svg viewBox="0 0 16 12" width="15" height="11"><path d="M8 11.5a1.1 1.1 0 100-2.2 1.1 1.1 0 000 2.2zm3.9-3.2a5.5 5.5 0 00-7.8 0l-1.4-1.4a7.5 7.5 0 0110.6 0l-1.4 1.4zm2.8-2.8a9.5 9.5 0 00-13.4 0L0 4.1a11.5 11.5 0 0116 0l-1.3 1.4z" fill="currentColor"/></svg>
              </span>
              <span className="ios-battery" aria-label="battery">
                <span className="ios-battery-inner" />
              </span>
            </div>
          </div>

          {/* Scrolling screenshot content */}
          <div className="ks-shot-viewport">
            <div
              className="ks-shot-track"
              ref={trackRef}
              style={{
                "--scroll-distance": `${distance}px`,
                animationPlayState: distance > 0 ? "running" : "paused",
              }}
            >
              <img
                src={(window.__DSMADE_ASSET_BASE || "") + "assets/ks-profile-combined.webp"}
                alt="KS Cosméticos Instagram profile"
                draggable="false"
                loading="lazy"
                decoding="async"
              />
            </div>
          </div>

          {/* Home indicator */}
          <div className="ios-home-indicator" aria-hidden="true" />
        </div>
      </div>
    </div>
  );
}

/* ------- iOS status bar clock that ticks live ------- */
function StatusBarClock() {
  const now = useNow(30_000);
  const d = new Date(now);
  const hh = String(d.getHours()).padStart(2, "0");
  const mm = String(d.getMinutes()).padStart(2, "0");
  return <span className="ios-statusbar-time">{hh}:{mm}</span>;
}

window.PhoneMockup = PhoneMockup;
