/* circle-reel.jsx — Feed / Circle Reel / You
   Pixel values from Figma Dev Mode export */

function ReelStyles() {
  return React.createElement('style', null, `
    @keyframes kenBurns {
      0%   { transform: scale(1.0) translate(0px, 0px); }
      100% { transform: scale(1.09) translate(-10px, -5px); }
    }
    @keyframes frontWobble {
      0%   { transform: translate(0px, 0px)   rotate(0deg); }
      25%  { transform: translate(-3px, -1px) rotate(-0.5deg); }
      50%  { transform: translate(0px, 0px)   rotate(0deg); }
      75%  { transform: translate(3px, 1px)   rotate(0.5deg); }
      100% { transform: translate(0px, 0px)   rotate(0deg); }
    }
    @keyframes progressPlay {
      0%   { width: 0%; }
      100% { width: 100%; }
    }
  `);
}

/* ------------------------------------------------------------------ */
/*  Data                                                                */
/* ------------------------------------------------------------------ */

const REEL_MEMBERS = [
  { id: "you",   handle: "yrcdec",  photo: "assets/avatar-you-reel-32.png",   hasNew: true  },
  { id: "lisa",  handle: "kc_lisa", photo: "assets/avatar-lisa-reel-32.png",  hasNew: true  },
  { id: "shimk", handle: "shimk",   photo: "assets/avatar-shimk-reel-32.png", hasNew: false },
];

/* Posts keyed by member id */
const MEMBER_POSTS = {
  you: [
    {
      back:     "assets/reel-you-back.png",
      front:    "assets/reel-you-front.png",
      user:     "YR.C",
      avatar:   "assets/avatar-you-reel-32.png",
      location: "Kenting, Taiwan",
      timeAgo:  "32m late",
      caption:  "Ocean 🌊",
      wobble:   false,
    },
    {
      back:     "assets/reel-you-back-2.png",
      front:    "assets/reel-you-front-2.png",
      user:     "YR.C",
      avatar:   "assets/avatar-you-reel-32.png",
      location: "Kenting, Taiwan",
      timeAgo:  "15m late",
      caption:  "Not the wind 🪶💀",
      wobble:   false,
    },
  ],
  lisa: [
    {
      back:     "assets/reel-lisa-back.png",
      front:    "assets/reel-lisa-front.png",
      user:     "Lisa",
      avatar:   "assets/avatar-lisa-reel-32.png",
      location: "Courchevel, France",
      timeAgo:  "15m late",
      caption:  "Weekend ☀️☀️☀️",
    },
  ],
  shimk: [],
};

const POST_DURATION = 5; /* seconds, all posts same duration for demo */

/* Order of members for auto-advance */
const MEMBER_ORDER = ["you", "lisa", "shimk"];

/* ------------------------------------------------------------------ */
/*  Navigation bar                                                      */
/* ------------------------------------------------------------------ */

function ReelNavBar({ onBack, activeMember, onMemberClick, onCalendar, memberPosts }) {
  return (
    <div style={{
      position: "absolute", left: 0, right: 0, top: 0, height: 127, zIndex: 10,
      background: "#000",
    }}>
      <img src="assets/Status Bar.png" alt=""
        style={{ width: 393, height: 59, display: "block", position: "relative", zIndex: 1 }}/>

      <div style={{
        position: "relative", zIndex: 1,
        display: "flex", flexDirection: "row",
        justifyContent: "center", alignItems: "center",
        padding: "0 16px 8px",
        width: 393, height: 68, boxSizing: "border-box",
      }}>

        {/* Back button */}
        <button onClick={onBack} style={{
          position: "absolute", left: 16,
          width: 44, height: 44, borderRadius: 99999,
          background: "rgba(255,255,255,0.12)",
          border: "none", cursor: "pointer",
          display: "flex", justifyContent: "center", alignItems: "center",
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M15 18L9 12L15 6" stroke="white" strokeWidth="2.5"
              strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>

        {/* Avatar stack — clicking switches member */}
        <div style={{
          display: "flex", flexDirection: "row", alignItems: "flex-start", gap: 10,
        }}>
          {REEL_MEMBERS.map(m => {
            const isActive = m.id === activeMember;
            const hasPosts = ((memberPosts || MEMBER_POSTS)[m.id] || []).length > 0;
            return (
              <div
                key={m.id}
                onClick={() => hasPosts && onMemberClick(m.id)}
                style={{
                  display: "flex", flexDirection: "column", alignItems: "center",
                  gap: 4, width: 46, height: 52,
                  cursor: hasPosts ? "pointer" : "default",
                }}
              >
                <div style={{
                  width: 32, height: 32, borderRadius: "50%",
                  border: isActive
                    ? "2px solid #fff"
                    : m.hasNew
                      ? "2px solid #0EC03B"
                      : "2px solid rgba(255,255,255,0.2)",
                  boxSizing: "border-box", overflow: "hidden", flexShrink: 0,
                }}>
                  <img src={m.photo} alt={m.handle}
                    style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
                </div>
                <span style={{
                  fontFamily: '"SF Pro", -apple-system, sans-serif',
                  fontWeight: isActive ? 590 : 400,
                  fontSize: 13, lineHeight: "16px",
                  letterSpacing: -0.08,
                  color: isActive ? "#fff" : "#99999C",
                  textAlign: "center", whiteSpace: "nowrap",
                }}>{m.handle}</span>
              </div>
            );
          })}
        </div>

        {/* Calendar button */}
        <button onClick={onCalendar} style={{
          position: "absolute", right: 16,
          width: 44, height: 44, borderRadius: 99999,
          background: "rgba(255,255,255,0.12)",
          border: "none", cursor: "pointer",
          display: "flex", justifyContent: "center", alignItems: "center",
        }}>
          <img src="assets/ic-calendar.svg" alt="" style={{ width: 24, height: 24, display: "block" }}/>
        </button>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Interactions sidebar                                                */
/* ------------------------------------------------------------------ */

function ReelInteractions() {
  return (
    <div style={{
      display: "flex", flexDirection: "column",
      justifyContent: "flex-end", alignItems: "center",
      padding: "12px 0", gap: 24,
      position: "absolute", width: 48, height: 144, boxSizing: "border-box",
      right: 4, bottom: 120,
      zIndex: 6,
    }}>
      <img src="assets/ic-Send.svg" alt="" style={{ width: 24, height: 24 }}/>
      <img src="assets/ic-Comments.svg" alt="" style={{ width: 24, height: 24 }}/>
      <img src="assets/ic-Smile.svg" alt="" style={{ width: 24, height: 24 }}/>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Bottom info + pagination                                            */
/* ------------------------------------------------------------------ */

function ReelBottomInfo({ post, activeMember, activeIdx, total, paused, onDotClick, onAdvance }) {
  return (
    <div style={{
      position: "absolute", left: 0, right: 0, bottom: 0,
      height: 120, zIndex: 5,
    }}>
      {/* Blur layer */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0,
        height: 220,
        backdropFilter: "blur(20px)", WebkitBackdropFilter: "blur(20px)",
        WebkitMaskImage: "linear-gradient(to top, black 0%, black 30%, transparent 100%)",
        maskImage: "linear-gradient(to top, black 0%, black 30%, transparent 100%)",
        pointerEvents: "none",
      }}/>
      {/* Dark gradient */}
      <div style={{
        position: "absolute", left: 0, right: 0, bottom: 0,
        height: 220,
        background: "linear-gradient(to top, rgba(0,0,0,0.72) 0%, rgba(0,0,0,0.25) 50%, rgba(0,0,0,0) 100%)",
        pointerEvents: "none",
      }}/>

      <div style={{ position: "relative", zIndex: 1, paddingBottom: 8 }}>

        {/* User info row */}
        <div style={{
          display: "flex", flexDirection: "row", alignItems: "center",
          padding: "8px 16px 8px 8px", gap: 8,
          width: 393, height: 52, boxSizing: "border-box",
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: "50%",
            border: "1px solid rgba(255,255,255,0.1)",
            overflow: "hidden", flexShrink: 0, boxSizing: "border-box",
          }}>
            <img src={post.avatar} alt=""
              style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
          </div>
          <div style={{
            display: "flex", flexDirection: "column",
            justifyContent: "center", alignItems: "flex-start",
            flex: 1, minWidth: 0,
          }}>
            <span style={{
              fontFamily: '"SF Pro", -apple-system, sans-serif',
              fontWeight: 590, fontSize: 15, lineHeight: "20px",
              letterSpacing: -0.2, color: "#fff",
            }}>{post.user}</span>
            <span style={{
              fontFamily: '"SF Pro", -apple-system, sans-serif',
              fontWeight: 400, fontSize: 13, lineHeight: "16px",
              letterSpacing: -0.08, color: "#99999C",
            }}>{post.location} · {post.timeAgo}</span>
          </div>
          <button style={{
            background: "transparent", border: "none", cursor: "pointer",
            padding: 0, display: "flex", alignItems: "center", justifyContent: "center",
            width: 24, height: 24, flexShrink: 0,
          }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
              <circle cx="5" cy="12" r="1.5"/>
              <circle cx="12" cy="12" r="1.5"/>
              <circle cx="19" cy="12" r="1.5"/>
            </svg>
          </button>
        </div>

        {/* Caption */}
        <div style={{ padding: "0 16px 8px 8px", width: 393, boxSizing: "border-box" }}>
          <span style={{
            fontFamily: '"SF Pro", -apple-system, sans-serif',
            fontWeight: 590, fontSize: 17, lineHeight: "22px",
            letterSpacing: -0.4, color: "#fff",
          }}>{post.caption}</span>
        </div>

        {/* Pagination */}
        <div style={{
          display: "flex", flexDirection: "row", alignItems: "center",
          padding: "4px 8px", gap: 4,
          width: 393, boxSizing: "border-box",
        }}>
          {Array.from({ length: total }).map((_, i) => (
            <div
              key={i}
              onClick={() => onDotClick(i)}
              style={{
                flex: 1, height: 2, borderRadius: 100,
                background: "rgba(255,255,255,0.35)",
                overflow: "hidden", cursor: "pointer",
              }}
            >
              {i < activeIdx && (
                <div style={{ height: "100%", width: "100%", background: "#fff", borderRadius: 100 }}/>
              )}
              {i === activeIdx && (
                <div
                  key={`fill-${activeMember}-${activeIdx}`}
                  onAnimationEnd={onAdvance}
                  style={{
                    height: "100%", background: "#fff", borderRadius: 100,
                    animation: `progressPlay ${post.duration || POST_DURATION}s linear forwards`,
                    animationPlayState: paused ? "paused" : "running",
                  }}
                />
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Circle Reel Page                                                    */
/* ------------------------------------------------------------------ */

/* ------------------------------------------------------------------ */
/*  Memory Calendar — static image screen                              */
/* ------------------------------------------------------------------ */

function MemoryCalendarScreen({ onBack }) {
  return (
    <div style={{
      position: "absolute", inset: 0,
      borderRadius: "inherit", overflow: "hidden",
      background: "#000", zIndex: 50,
    }}>
      <img
        src="archive/UI%20examples/Circle-Calendar.png"
        alt="Memory Calendar"
        style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
      />
      <button onClick={onBack} style={{
        position: "absolute", top: 62, left: 16,
        width: 44, height: 44, borderRadius: 99999,
        background: "rgba(0,0,0,0.45)",
        backdropFilter: "blur(12px)", WebkitBackdropFilter: "blur(12px)",
        border: "none", cursor: "pointer",
        display: "flex", justifyContent: "center", alignItems: "center",
        zIndex: 10,
      }}>
        <img src="assets/ic_chevron_down.svg" alt="back"
          style={{ width: 24, height: 24, display: "block", transform: "rotate(90deg)" }}/>
      </button>
    </div>
  );
}

function CircleReelPage({ onBack, onComplete, singleMember, showNewPost, newCaption, newShape, newPipPos }) {
  /* Build dynamic post list — inject cat post when user has posted */
  const allPosts = React.useMemo(() => {
    if (!showNewPost) return MEMBER_POSTS;
    return {
      ...MEMBER_POSTS,
      you: [
        ...MEMBER_POSTS.you,
        {
          back:     "assets/reel-you-back-3.png",
          front:    "assets/reel-you-front-3.png",
          user:     "YR.C",
          avatar:   "assets/avatar-you-reel-32.png",
          location: "Sweet Roomies 🐨",
          timeAgo:  "just now",
          caption:  newCaption || "",
          wobble:   false,
          pipShape: newShape  || "rect",
          pipPos:   { x: 185, y: 310 },
          duration: 8,
        },
      ],
    };
  }, [showNewPost, newCaption, newShape, newPipPos]);

  /* Start on the new post if just posted */
  const [activeMember, setActiveMember] = React.useState("you");
  const [activeIdx, setActiveIdx]       = React.useState(
    showNewPost ? (MEMBER_POSTS.you.length) : 0   /* index of the new post */
  );
  const [paused, setPaused]             = React.useState(false);
  const [showCalendar, setShowCalendar] = React.useState(false);

  /* Keep refs so keyboard handler always has fresh values */
  const stateRef = React.useRef({ activeMember, activeIdx });
  React.useEffect(() => {
    stateRef.current = { activeMember, activeIdx };
  }, [activeMember, activeIdx]);

  /* Switch to a different member (reset post index) */
  function switchMember(memberId) {
    setActiveMember(memberId);
    setActiveIdx(0);
  }

  /* Step forward one post; if at end of member, go to next member */
  function stepForward(member, idx) {
    const posts = allPosts[member] || [];
    if (idx < posts.length - 1) {
      setActiveIdx(idx + 1);
    } else if (singleMember) {
      /* Single-member mode: stay on last post */
      setPaused(true);
    } else {
      const memberIdx = MEMBER_ORDER.indexOf(member);
      for (let m = memberIdx + 1; m < MEMBER_ORDER.length; m++) {
        const nextId = MEMBER_ORDER[m];
        if ((allPosts[nextId] || []).length > 0) {
          switchMember(nextId);
          return;
        }
      }
      setPaused(true);
    }
  }

  /* Step backward one post; if at start of member, go to prev member's last post */
  function stepBack(member, idx) {
    if (idx > 0) {
      setActiveIdx(idx - 1);
    } else {
      const memberIdx = MEMBER_ORDER.indexOf(member);
      for (let m = memberIdx - 1; m >= 0; m--) {
        const prevId = MEMBER_ORDER[m];
        const prevPosts = allPosts[prevId] || [];
        if (prevPosts.length > 0) {
          setActiveMember(prevId);
          setActiveIdx(prevPosts.length - 1);
          return;
        }
      }
    }
  }

  /* Keyboard navigation */
  React.useEffect(() => {
    function onKey(e) {
      const { activeMember: m, activeIdx: i } = stateRef.current;
      if (e.key === "ArrowRight") stepForward(m, i);
      if (e.key === "ArrowLeft")  stepBack(m, i);
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  /* Demo control via postMessage */
  React.useEffect(() => {
    function onDemoMsg(e) {
      if (!e.data || e.data.type !== 'bereal-demo') return;
      if (e.data.action === 'openCalendar') setShowCalendar(true);
      if (e.data.action === 'closeCalendar') setShowCalendar(false);
      if (e.data.action === 'goToMember' && e.data.member) switchMember(e.data.member);
      if (e.data.action === 'goToPost' && e.data.member) {
        setActiveMember(e.data.member);
        setActiveIdx(e.data.idx || 0);
      }
    }
    window.addEventListener('message', onDemoMsg);
    return () => window.removeEventListener('message', onDemoMsg);
  }, []);

  const posts      = allPosts[activeMember] || [];
  const post       = posts[activeIdx];
  const showWobble = post.wobble ?? false;

  if (!post) return null;

  return (
    <div
      style={{
        position: "absolute", inset: 0,
        background: "#000", overflow: "hidden",
        borderRadius: "inherit",
        userSelect: "none",
      }}
      onMouseDown={() => setPaused(true)}
      onMouseUp={() => setPaused(false)}
      onMouseLeave={() => setPaused(false)}
    >
      <ReelStyles/>

      {/* Back camera */}
      <div style={{
        position: "absolute", top: 127, left: 0, right: 0, bottom: 0,
        borderRadius: "16px 16px 0 0", overflow: "hidden",
      }}>
        <img key={`back-${activeMember}-${activeIdx}`} src={post.back} alt=""
          style={{
            width: "100%", height: "100%", objectFit: "cover", display: "block",
            animation: "kenBurns 12s ease-out forwards",
            animationPlayState: (paused || showCalendar) ? "paused" : "running",
            transformOrigin: "center center",
          }}/>
      </div>

      {/* Front camera — shaped if post carries pipShape, else default rect */}
      {post.pipShape && window.ShapedPip ? (
        <div style={{
          position: "absolute",
          left: (post.pipPos || { x: 16 }).x,
          top:  (post.pipPos || { y: 143 }).y,
          zIndex: 5,
        }}>
          <window.ShapedPip shape={post.pipShape} imageUrl={post.front}/>
        </div>
      ) : (
        <div style={{
          position: "absolute", top: 143, left: 16,
          width: 120, height: 159,
          borderRadius: 12,
          border: "2px solid #000",
          boxSizing: "border-box",
          zIndex: 5,
        }}>
          <div style={{ width: "100%", height: "100%", borderRadius: 10, overflow: "hidden" }}>
            <img key={`front-${activeMember}-${activeIdx}`} src={post.front} alt=""
              style={{
                width: "105%", height: "105%",
                objectFit: "cover", display: "block",
                marginLeft: "-2.5%", marginTop: "-2.5%",
                animation: showWobble ? "frontWobble 1.4s ease-in-out 1 forwards" : "none",
                transformOrigin: "center center",
              }}/>
          </div>
        </div>
      )}

      {/* Memory calendar overlay */}
      {showCalendar && <MemoryCalendarScreen onBack={() => setShowCalendar(false)}/>}

      {/* Navigation bar */}
      {singleMember ? (
        <div style={{ position: "absolute", top: 59, left: 0, right: 0, zIndex: 10,
                      display: "flex", alignItems: "center", justifyContent: "space-between",
                      padding: "8px 16px" }}>
          <button onClick={onBack} style={{
            width: 44, height: 44, borderRadius: 99999,
            background: "rgba(255,255,255,0.12)",
            border: "none", cursor: "pointer",
            display: "flex", justifyContent: "center", alignItems: "center",
          }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
              <path d="M15 18L9 12L15 6" stroke="white" strokeWidth="2.5"
                strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
          <button onClick={() => setShowCalendar(true)} style={{
            width: 44, height: 44, borderRadius: 99999,
            background: "rgba(255,255,255,0.12)",
            border: "none", cursor: "pointer",
            display: "flex", justifyContent: "center", alignItems: "center",
          }}>
            <img src="assets/ic-calendar.svg" alt="" style={{ width: 24, height: 24, display: "block" }}/>
          </button>
        </div>
      ) : (
        <ReelNavBar
          onBack={onBack}
          activeMember={activeMember}
          onMemberClick={switchMember}
          onCalendar={() => setShowCalendar(true)}
          memberPosts={allPosts}
        />
      )}

      {/* Interactions sidebar */}
      <ReelInteractions/>

      {/* Bottom info */}
      <ReelBottomInfo
        post={post}
        activeMember={activeMember}
        activeIdx={activeIdx}
        total={posts.length}
        paused={paused || showCalendar}
        onDotClick={setActiveIdx}
        onAdvance={() => stepForward(activeMember, activeIdx)}
      />
    </div>
  );
}

window.CircleReelPage = CircleReelPage;
