/* ============================================================
   <AppPhonePeek /> — an iPhone 17 Pro Max mockup that peeks from
   the top of a card, with the app's screens auto-sliding inside.
   <AppPeekCard />  — the full app card built around that peek.

   The peek shows only the TOP portion of the phone (a "half-screen
   from the top" shot), clipped by the card. Screens slide left
   to reveal each page of the app.

   Real screenshots: pass app.shots = ["assets/x.png", …] and they
   render in place of the synthetic <AppScreen> mockups.
   ============================================================ */

function AppPhonePeek({ app, displayWidth = 234, interval = 2800 }) {
  // Render the phone at native iPhone size, then scale the whole thing
  // down — so the app screen's internal proportions stay realistic.
  const NATIVE_W = 402;
  const NATIVE_H = 872;
  const scale = displayWidth / NATIVE_W;

  const shots = Array.isArray(app.shots) ? app.shots : null;
  const screens =
    shots && shots.length
      ? shots.map((src) => ({ src }))
      : (app.screens && app.screens.length ? app.screens : [{ kind: "dashboard" }]);
  const n = screens.length;

  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    if (n <= 1) return undefined;
    const id = setInterval(() => setActive((a) => (a + 1) % n), interval);
    return () => clearInterval(id);
  }, [n, interval]);

  return (
    <div className="phone-peek">
      <div
        className="phone-peek__device"
        style={{ width: displayWidth, height: Math.round(NATIVE_H * scale) }}
      >
        <div
          className="phone-peek__scaler"
          style={{ width: NATIVE_W, height: NATIVE_H, transform: `scale(${scale})` }}
        >
          <IOSDevice width={NATIVE_W} height={NATIVE_H} dark={false} statusBar={false}>
            <div className="phone-peek__view">
              <div
                className="phone-peek__track"
                style={{
                  width: `${n * 100}%`,
                  transform: `translateX(-${active * (100 / n)}%)`,
                }}
              >
                {screens.map((s, i) => (
                  <div
                    className="phone-peek__slide"
                    key={i}
                    style={{ width: `${100 / n}%` }}
                    aria-hidden={i !== active}
                  >
                    {s.src ? (
                      <img
                        className="phone-peek__shot"
                        src={s.src}
                        alt={`${app.name} screen ${i + 1}`}
                        loading="lazy"
                      />
                    ) : (
                      <AppScreen kind={s.kind} app={app} />
                    )}
                  </div>
                ))}
              </div>
            </div>
          </IOSDevice>
        </div>
      </div>

      {n > 1 && (
        <div className="phone-peek__dots" aria-hidden="true">
          {screens.map((_, i) => (
            <span
              key={i}
              className={`phone-peek__dot ${i === active ? "is-active" : ""}`}
            ></span>
          ))}
        </div>
      )}
    </div>
  );
}

function AppPeekCard({ app, showStatus = true, showMetric = true }) {
  const hue = app.cover?.hue ?? app.icon?.hue ?? 250;
  const hue2 = app.cover?.hue2 ?? app.icon?.hue2 ?? hue;
  return (
    <a
      href={`app.html?slug=${app.slug}`}
      className="app-card app-card--peek"
      style={{ "--card-tint": `oklch(0.85 0.12 ${hue} / 0.5)` }}
      data-cursor-preview={app.name}
      data-cursor-meta={`${app.category}${app.status ? " · " + app.status : ""}`}
    >
      <div
        className="app-card__peek"
        style={{
          background: `radial-gradient(120% 100% at 50% 0%, oklch(0.93 0.07 ${hue}) 0%, oklch(0.97 0.025 ${hue2}) 70%)`,
        }}
      >
        <AppPhonePeek app={app} />
      </div>

      <div className="app-card__body">
        <div className="app-card__head">
          <AppIcon app={app} size={50} />
          <div className="app-card__id">
            <div className="app-card__name">{app.name}</div>
            <div className="app-card__cat">{app.category}</div>
          </div>
          {showStatus && app.status && (
            <div className="app-card__badges">
              <StatusBadge status={app.status} />
            </div>
          )}
        </div>

        <p className="app-card__tagline">{app.tagline}</p>

        <div className="app-card__foot">
          {showMetric && app.metric ? (
            <div className="app-card__metric">
              <span className="app-card__metric-val">{app.metric.value}</span>
              <span className="app-card__metric-label">{app.metric.label}</span>
            </div>
          ) : (
            <span></span>
          )}
          <PlatformChips platforms={app.platforms} />
        </div>
      </div>
    </a>
  );
}

Object.assign(window, { AppPhonePeek, AppPeekCard });
