/* KitRate — video showcase: interactive reel-card slider.
   Auto-imports the creator's best short-form by KPI (mocked from profile.reels).
   Centered active card, scaled/dimmed neighbours, eased transitions,
   pointer-drag / swipe / arrows / click-to-focus. */

function rankReels(reels, kpi) {
  const arr = [...(reels || [])];
  if (!arr.length) return arr;
  const maxV = Math.max(...arr.map(r => r.views), 1);
  const maxE = Math.max(...arr.map(r => r.er), 1);
  const score = (r) =>
    kpi === "views" ? r.views :
    kpi === "engagement" ? r.er :
    kpi === "recent" ? Date.parse(r.posted) :
    0.6 * (r.views / maxV) + 0.4 * (r.er / maxE);   /* smart blend */
  return arr.sort((a, b) => score(b) - score(a)).slice(0, 6);
}

const REEL_KPI_OPTIONS = [
  { value: "smart", label: "Smart blend" },
  { value: "views", label: "Views" },
  { value: "engagement", label: "Engagement" },
  { value: "recent", label: "Newest" }
];

function ReelSlider({ reels, t, compact, eyebrowStyle }) {
  const E = KitRateEngine;
  const [active, setActive] = useState(0);
  const [dx, setDx] = useState(0);
  const dragRef = useRef(null);
  const movedRef = useRef(false);
  const n = reels.length;

  useEffect(() => { if (active > n - 1) setActive(0); }, [n]);

  const cardW = compact ? 168 : 188;
  const cardH = Math.round(cardW * 16 / 9);
  const gap = Math.round(cardW * 0.74);
  const stageH = cardH + 24;

  const go = (i) => setActive(Math.max(0, Math.min(n - 1, i)));

  const onPointerDown = (e) => {
    dragRef.current = { x0: e.clientX, moved: false };
    movedRef.current = false;
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e) => {
    const d = dragRef.current;
    if (!d) return;
    const delta = e.clientX - d.x0;
    if (Math.abs(delta) > 5) d.moved = true;
    /* resist at the ends */
    const atEnd = (delta > 0 && active === 0) || (delta < 0 && active === n - 1);
    setDx(atEnd ? delta * 0.3 : delta);
  };
  const onPointerUp = (e) => {
    const d = dragRef.current;
    dragRef.current = null;
    movedRef.current = !!(d && d.moved);
    if (d && Math.abs(dx) > cardW * 0.28) go(active + (dx < 0 ? 1 : -1));
    setDx(0);
  };

  const reel = reels[active];
  const dragging = dragRef.current != null;

  const Arrow = ({ dir }) => (
    <button aria-label={dir < 0 ? "Previous reel" : "Next reel"}
      onClick={() => go(active + dir)}
      disabled={dir < 0 ? active === 0 : active === n - 1}
      style={{
        width: 34, height: 34, borderRadius: "50%", border: "1px solid " + t.line,
        background: "transparent", color: t.ink, display: "inline-flex",
        alignItems: "center", justifyContent: "center", flexShrink: 0,
        opacity: (dir < 0 ? active === 0 : active === n - 1) ? 0.3 : 1,
        cursor: "pointer", transition: "opacity 0.2s"
      }}>
      <KrIcon d={dir < 0 ? ICONS.arrowLeft : ICONS.arrowRight} size={14} />
    </button>
  );

  return (
    <div>
      {/* stage */}
      <div
        onPointerDown={onPointerDown} onPointerMove={onPointerMove}
        onPointerUp={onPointerUp} onPointerCancel={onPointerUp}
        style={{ position: "relative", height: stageH, overflow: "hidden", touchAction: "pan-y", cursor: dragging ? "grabbing" : "grab", userSelect: "none" }}>
        {reels.map((r, i) => {
          const off = i - active;
          if (Math.abs(off) > 2) return null;
          const isActive = off === 0;
          const x = off * gap + dx;
          return (
            <div key={r.id}
              onClick={() => { if (!isActive && !movedRef.current) go(i); }}
              style={{
                position: "absolute", left: "50%", top: 12,
                width: cardW, height: cardH, marginLeft: -cardW / 2,
                transform: "translateX(" + x + "px) scale(" + (isActive ? 1 : 0.85) + ")",
                transformOrigin: "center center",
                transition: dragging ? "none" : "transform 0.45s cubic-bezier(0.22, 0.61, 0.21, 1), opacity 0.45s ease, box-shadow 0.45s ease",
                opacity: isActive ? 1 : Math.abs(off) === 1 ? 0.55 : 0.22,
                zIndex: 10 - Math.abs(off),
                borderRadius: 12, overflow: "hidden",
                background: t.coverMode === "dark" ? "#23201A" : t.ink,
                boxShadow: isActive ? "0 16px 40px rgba(20,16,8,0.28)" : "0 4px 14px rgba(20,16,8,0.12)",
                cursor: isActive ? "grab" : "pointer"
              }}>
              <image-slot id={"kitrate-reel-" + r.id} shape="rect" placeholder="Reel frame"
                style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}></image-slot>
              {/* overlays — pointer-events none so image drops reach the slot */}
              <div style={{ position: "absolute", inset: 0, pointerEvents: "none", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: 9 }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.1em", textTransform: "uppercase", color: "#FFFFFF", background: "rgba(18,15,10,0.55)", borderRadius: 99, padding: "3px 8px", backdropFilter: "blur(4px)" }}>
                    {{ instagram: "IG Reel", tiktok: "TikTok", youtube: "Short" }[r.platform] || r.platform}
                  </span>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 9, color: "#FFFFFF", background: "rgba(18,15,10,0.55)", borderRadius: 99, padding: "3px 7px" }}>{r.dur}</span>
                </div>
                <div style={{ padding: "26px 11px 10px", background: "linear-gradient(180deg, rgba(15,12,7,0) 0%, rgba(15,12,7,0.78) 60%)", color: "#FFFFFF" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 3 }}>
                    {/* play glyph */}
                    <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 1.5l8 4.5-8 4.5z" fill="#FFFFFF"></path></svg>
                    <span style={{ fontFamily: t.serif, fontSize: 17, lineHeight: 1 }}>{E.fmtCompact(r.views)}</span>
                  </div>
                  <div style={{ fontFamily: "var(--mono)", fontSize: 8.5, letterSpacing: "0.12em", textTransform: "uppercase", opacity: 0.75 }}>views · {r.er}% ER</div>
                </div>
              </div>
              {/* rank chip */}
              <span style={{ position: "absolute", top: -1, left: "50%", transform: "translateX(-50%)", pointerEvents: "none", fontFamily: "var(--mono)", fontSize: 8.5, letterSpacing: "0.1em", color: t.accentInk, background: t.accent, borderRadius: "0 0 6px 6px", padding: "2px 8px 3px" }}>
                #{i + 1}
              </span>
            </div>
          );
        })}
      </div>

      {/* caption + controls */}
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: compact ? 14 : 20 }}>
        <Arrow dir={-1} />
        <div style={{ flex: 1, textAlign: "center", minWidth: 0 }}>
          <div style={{ fontFamily: t.serif, fontSize: compact ? 16 : 18, color: t.ink, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            “{reel ? reel.title : ""}”
          </div>
          <div style={{ ...eyebrowStyle, marginTop: 5 }}>
            {reel ? E.fmtCompact(reel.views) + " views · " + reel.er + "% ER · " + E.fmtCompact(reel.likes) + " likes · " + reel.posted : ""}
          </div>
        </div>
        <Arrow dir={1} />
      </div>

      {/* dots */}
      <div style={{ display: "flex", gap: 6, justifyContent: "center", marginTop: 12 }}>
        {reels.map((r, i) => (
          <button key={r.id} aria-label={"Go to reel " + (i + 1)} onClick={() => go(i)} style={{
            width: i === active ? 18 : 6, height: 6, borderRadius: 99, border: "none", padding: 0,
            background: i === active ? t.accent : t.line, cursor: "pointer",
            transition: "width 0.3s cubic-bezier(0.22, 0.61, 0.21, 1), background 0.3s"
          }}></button>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ReelSlider, rankReels, REEL_KPI_OPTIONS });
