/* posting.jsx — Post-capture preview & send
   Figma node-id: 13456-12143
   Layout: Header+Timer(141) + gap(8) + Container(570) + gap(8) + Send(101) + pb(24) = 852 */

/* ─────────────────────────────────────────── */
/*  Audience data                              */
/* ─────────────────────────────────────────── */

const POST_CIRCLES = [
  { id: "roomies", name: "Sweet Roomies 🐨", members: "YR.C, Lisa, Shimmer" },
  { id: "group3",  name: "PHOTO DUMP 📷✨",  members: "YR.C, Leo, Megan, Dora" },
];

const POST_FEED_OPTIONS = [
  { id: "my",  label: "My friends only",          sub: "Visible till next BeReal notification" },
  { id: "fof", label: "My friends + their friends", sub: "Also shared with Friends of Friends" },
  { id: "all", label: "Everyone",                  sub: "Visible to anyone on your profile" },
];

/* ─────────────────────────────────────────── */
/*  AudienceSheet — bottom sheet              */
/* ─────────────────────────────────────────── */

function AudienceSheet({ circleSel, feedChoice, onToggleCircle, onPickFeed, onDone }) {
  const [mounted, setMounted] = React.useState(false);
  React.useEffect(() => {
    const id = requestAnimationFrame(() => setMounted(true));
    return () => cancelAnimationFrame(id);
  }, []);

  const sheetStyle = {
    position: "relative",
    background: "rgb(20,20,22)",
    borderTopLeftRadius: 26, borderTopRightRadius: 26,
    padding: "12px 0 44px",
    transform: mounted ? "translateY(0)" : "translateY(110%)",
    transition: "transform .32s cubic-bezier(.22,.7,.22,1)",
    boxShadow: "0 -16px 56px rgba(0,0,0,0.75)",
  };

  const sectionLabel = {
    fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
    fontWeight: 600, fontSize: 12, letterSpacing: 0.7,
    textTransform: "uppercase", color: "rgba(255,255,255,0.38)",
    padding: "0 20px", marginBottom: 8, display: "block",
  };

  function RowItem({ children, checked, onClick }) {
    return (
      <button onClick={onClick} style={{
        display: "flex", alignItems: "center", gap: 12,
        width: "100%", boxSizing: "border-box",
        background: "rgba(255,255,255,0.07)",
        border: "none", borderRadius: 14,
        padding: "13px 16px", marginBottom: 6,
        cursor: "pointer",
      }}>
        {children}
        {/* Always circle radio style */}
        <span style={{
          width: 24, height: 24, borderRadius: 12, flexShrink: 0,
          background: checked ? "#fff" : "transparent",
          border: checked ? "none" : "1.5px solid rgba(255,255,255,0.35)",
          display: "grid", placeItems: "center",
          transition: "all .15s",
        }}>
          {checked && (
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
              <path d="M5 12l5 5 9-11" stroke="#000" strokeWidth="3.2"
                strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          )}
        </span>
      </button>
    );
  }

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 90,
      display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>

      {/* Backdrop */}
      <div onClick={onDone} style={{
        position: "absolute", inset: 0,
        background: "rgba(0,0,0,0.62)",
        opacity: mounted ? 1 : 0, transition: "opacity .22s",
      }}/>

      <div style={sheetStyle}>
        {/* Grab handle */}
        <div style={{
          width: 44, height: 4, borderRadius: 2,
          background: "rgba(255,255,255,0.22)",
          margin: "0 auto 20px",
        }}/>

        {/* Header */}
        <div style={{
          display: "flex", justifyContent: "center", alignItems: "center",
          padding: "0 20px 20px", position: "relative",
        }}>
          <span style={{
            fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
            fontWeight: 700, fontSize: 19, letterSpacing: -0.3, color: "#fff",
          }}>Select your Audience</span>
          <button onClick={onDone} style={{
            position: "absolute", right: 20,
            background: "none", border: "none", cursor: "pointer",
            fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
            fontWeight: 600, fontSize: 16, color: "#007AFF", letterSpacing: -0.2,
          }}>Apply</button>
        </div>

        {/* Circles */}
        <span style={sectionLabel}>Circles</span>
        <div style={{ padding: "0 16px", marginBottom: 16 }}>
          {POST_CIRCLES.map(c => {
            const checked = circleSel.includes(c.id);
            return (
              <RowItem key={c.id} checked={checked} onClick={() => onToggleCircle(c.id)}>
                <span style={{ flex: 1, textAlign: "left" }}>
                  <span style={{
                    display: "block",
                    fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
                    fontWeight: 600, fontSize: 16, letterSpacing: -0.2, color: "#fff",
                  }}>{c.name}</span>
                  <span style={{
                    display: "block", marginTop: 2,
                    fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
                    fontSize: 13, color: "rgba(255,255,255,0.42)", letterSpacing: -0.1,
                  }}>{c.members}</span>
                </span>
              </RowItem>
            );
          })}
        </div>

        {/* Feed */}
        <span style={sectionLabel}>Feed</span>
        <div style={{ padding: "0 16px" }}>
          {POST_FEED_OPTIONS.map(opt => {
            const checked = feedChoice === opt.id;
            const Icon = FEED_ICONS[opt.id];
            return (
              <RowItem key={opt.id} checked={checked}
                onClick={() => onPickFeed(opt.id)}>
                <span style={{
                  width: 32, height: 32, flexShrink: 0,
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}>
                  <Icon/>
                </span>
                <span style={{ flex: 1, textAlign: "left" }}>
                  <span style={{
                    display: "block",
                    fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
                    fontWeight: 600, fontSize: 16, letterSpacing: -0.2, color: "#fff",
                  }}>{opt.label}</span>
                  <span style={{
                    display: "block", marginTop: 2,
                    fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
                    fontSize: 13, color: "rgba(255,255,255,0.42)", letterSpacing: -0.1,
                  }}>{opt.sub}</span>
                </span>
              </RowItem>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ─────────────────────────────────────────── */
/*  Sheet row icons                            */
/* ─────────────────────────────────────────── */

function SheetIconLock() {
  return <img src="assets/ic_lock_fill.svg" alt="" width="24" height="24" style={{ display: "block" }}/>;
}

function SheetIconFriends() {
  return <img src="assets/ic_person_2_foreground_fill.svg" alt="" width="24" height="24" style={{ display: "block" }}/>;
}

function SheetIconGlobe() {
  return <img src="assets/ic_globe_asia_australia_fill.svg" alt="" width="24" height="24" style={{ display: "block" }}/>;
}

const FEED_ICONS = { my: SheetIconLock, fof: SheetIconFriends, all: SheetIconGlobe };

/* ─────────────────────────────────────────── */
/*  Pill icons                                 */
/* ─────────────────────────────────────────── */

function IcoPersonPlus() {
  return <img src="assets/ic_person_fill_badge_plus.svg" alt="" width="18" height="18"
    style={{ display: "block" }}/>;
}


function IcoLocationSlash() {
  return <img src="assets/ic_location_slash_fill.svg" alt="" width="16" height="16"
    style={{ display: "block" }}/>;
}

function IcoVinyl() {
  return <img src="assets/Vinyl Icon.png" alt="" width="30" height="20"
    style={{ display: "block" }}/>;
}

function IcoSendArrow() {
  return <img src="assets/Send Icon.svg" alt="" width="24" height="24"
    style={{ display: "block" }}/>;
}

/* ─────────────────────────────────────────── */
/*  Pill button                               */
/* ─────────────────────────────────────────── */

function PostPill({ children, opacity = 0.1, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "inline-flex", flexDirection: "row",
      justifyContent: "center", alignItems: "center",
      padding: "0 10px", gap: 5,
      minWidth: 36, height: 36,
      background: `linear-gradient(0deg,rgba(255,255,255,${opacity}),rgba(255,255,255,${opacity})),rgba(0,0,0,0.5)`,
      backdropFilter: "blur(40px)", WebkitBackdropFilter: "blur(40px)",
      borderRadius: 99999,
      border: "none", cursor: onClick ? "pointer" : "default",
      boxSizing: "border-box", flexShrink: 0,
    }}>
      {children}
    </button>
  );
}

function PillLabel({ children }) {
  return (
    <span style={{
      fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
      fontWeight: 590, fontSize: 14, lineHeight: "18px",
      letterSpacing: "-0.2px", color: "#fff", whiteSpace: "nowrap",
    }}>{children}</span>
  );
}

/* ─────────────────────────────────────────── */
/*  PostingScreen                             */
/* ─────────────────────────────────────────── */

function PostingScreen({ shape: initShape, pipPosition: initPos, onClose, onSend }) {
  const [caption,      setCaption]      = React.useState("");
  const [audienceOpen, setAudienceOpen] = React.useState(false);
  // Entry from group camera → Sweet Roomies pre-selected
  const [circleSel,    setCircleSel]    = React.useState(["roomies"]);
  const [feedChoice,   setFeedChoice]   = React.useState(null);
  const [sending, setSending] = React.useState(false);

  /* PiP shape + position — initialised from capture, editable here */
  const SHAPES     = window.SHAPES;
  const SHAPE_ORDER = window.SHAPE_ORDER;
  const [pipShape,    setPipShape]    = React.useState((initShape && SHAPES && SHAPES[initShape]) ? initShape : "rect");
  const [pipPos,      setPipPos]      = React.useState(initPos || { x: 12, y: 12 });
  const [pickerOpen,  setPickerOpen]  = React.useState(false);

  /* Reclamp position when shape size changes */
  React.useEffect(() => {
    if (!pipShape || !SHAPES) return;
    const spec = SHAPES[pipShape];
    const VP = { w: 393, h: 524 };
    setPipPos(p => ({
      x: Math.max(8, Math.min(VP.w - spec.width  - 8, p.x)),
      y: Math.max(8, Math.min(VP.h - spec.height - 8, p.y)),
    }));
  }, [pipShape]);

  function cycleShape() {
    if (!SHAPE_ORDER) return;
    const idx = SHAPE_ORDER.indexOf(pipShape ?? SHAPE_ORDER[0]);
    setPipShape(SHAPE_ORDER[(idx + 1) % SHAPE_ORDER.length]);
  }

  function toggleCircle(id) {
    setCircleSel(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  }

  const stateRef = React.useRef({ sending, pipShape, pipPos, onSend });
  React.useEffect(() => { stateRef.current = { sending, pipShape, pipPos, onSend }; }, [sending, pipShape, pipPos, onSend]);

  React.useEffect(() => {
    function onDemoMsg(e) {
      if (!e.data || e.data.type !== 'bereal-demo') return;
      if (e.data.action === 'openAudienceSheet') setAudienceOpen(true);
      if (e.data.action === 'applyAudience') setAudienceOpen(false);
      if (e.data.action === 'selectFeed' && e.data.id) setFeedChoice(e.data.id);
      if (e.data.action === 'toggleCircle' && e.data.id) {
        setCircleSel(s => s.includes(e.data.id) ? s.filter(x => x !== e.data.id) : [...s, e.data.id]);
      }
      if (e.data.action === 'sendPost') {
        const { sending: s, pipShape: sh, pipPos: p, onSend: fn } = stateRef.current;
        if (!s) { setSending(true); setTimeout(() => fn && fn("", sh, p), 1400); }
      }
    }
    window.addEventListener('message', onDemoMsg);
    return () => window.removeEventListener('message', onDemoMsg);
  }, []);

  /* Audience button sublabel (second line) */
  const FEED_SHORT = { my: "My friends", fof: "Friends of Friends", all: "Everyone" };
  const audienceSublabel = React.useMemo(() => {
    const hasCircles = circleSel.length > 0;
    const hasFeed = feedChoice !== null;
    const circleStr = hasCircles
      ? (circleSel.length === 1 ? "1 Circle" : `${circleSel.length} Circles`)
      : null;
    const feedStr = hasFeed ? FEED_SHORT[feedChoice] : null;
    if (circleStr && feedStr) return `${circleStr}, ${feedStr}`;
    if (circleStr) return circleStr;
    if (feedStr) return feedStr;
    return null;
  }, [circleSel, feedChoice]);

  function handleSend() {
    if (sending) return;
    setSending(true);
    setTimeout(() => { onSend && onSend(caption, pipShape, pipPos); }, 1400);
  }

  const DraggablePip = window.DraggablePip;
  const ShapePicker  = window.ShapePicker;
  const ShapeGlyph   = window.ShapeGlyph;

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: "#000", borderRadius: "inherit",
      display: "flex", flexDirection: "column",
      alignItems: "center",
      padding: "0 0 24px", gap: 8,
      overflow: "hidden", boxSizing: "border-box",
    }}>

      {/* ══ Header  111px ══ */}
      <div style={{
        width: 393, height: 111, flexShrink: 0,
        display: "flex", flexDirection: "column", gap: 2,
      }}>
        {/* NavBar: 111px */}
        <div style={{ width: 393, height: 111, flexShrink: 0, display: "flex", flexDirection: "column" }}>
          <img src="assets/Status Bar.png" alt=""
            style={{ width: 393, height: 59, display: "block" }}/>
          <div style={{
            position: "relative",
            display: "flex", justifyContent: "center", alignItems: "center",
            padding: "0 16px 8px",
            width: 393, height: 52, boxSizing: "border-box",
          }}>
            <button onClick={onClose} style={{
              position: "absolute", left: 16,
              width: 44, height: 44, borderRadius: 99999,
              background: "transparent", border: "none", cursor: "pointer",
              display: "flex", justifyContent: "center", alignItems: "center",
            }}>
              <img src="assets/ic_chevron_down.svg" alt=""
                style={{ width: 24, height: 24 }}/>
            </button>
            <img src="assets/Logo-bereal.svg" alt="BeReal."
              style={{ width: 74.67, height: 16 }}/>

            {/* Shape picker toggle — right side, matches capture toolbar */}
            {ShapeGlyph && (
              <button
                onClick={() => setPickerOpen(o => !o)}
                style={{
                  position: "absolute", right: 16,
                  width: 44, height: 44, borderRadius: 99999,
                  background: pickerOpen ? "rgba(255,255,255,0.2)" : "rgba(255,255,255,0.1)",
                  border: "none", cursor: "pointer",
                  display: "flex", justifyContent: "center", alignItems: "center",
                }}
              >
                <ShapeGlyph id={pipShape ?? "rect"} size={18} color="#fff" stroke={1.7}/>
              </button>
            )}
          </div>
        </div>

      </div>

      {/* Shape picker dropdown — top-level, same position as capture (right:16, top:108) */}
      {ShapePicker && (
        <ShapePicker
          open={pickerOpen}
          current={pipShape}
          onPick={id => { setPipShape(id || "rect"); setPickerOpen(false); }}
          onClose={() => setPickerOpen(false)}
        />
      )}

      {/* ══ Container  570px ══ */}
      <div style={{ width: 393, height: 570, flexShrink: 0, display: "flex", flexDirection: "column" }}>

        {/* Caption: 46px */}
        <div style={{
          width: 393, height: 46, flexShrink: 0,
          display: "flex", alignItems: "center",
          padding: "16px 16px 8px", boxSizing: "border-box",
        }}>
          <input
            className="post-caption-input"
            value={caption}
            onChange={e => setCaption(e.target.value)}
            placeholder="Add a caption..."
            style={{
              background: "transparent", border: "none", outline: "none",
              fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
              fontWeight: 590, fontSize: 17, lineHeight: "22px",
              letterSpacing: "-0.43px",
              color: "#fff", caretColor: "#fff", width: "100%",
            }}
          />
        </div>

        {/* Preview: 393×524 */}
        <div style={{
          position: "relative",
          width: 393, height: 524,
          borderRadius: 16, overflow: "hidden", flexShrink: 0,
          isolation: "isolate",
        }}>
          {/* Back camera */}
          <img src="assets/reel-you-back-3.png?v=2" alt="" style={{
            position: "absolute", inset: 0,
            width: "100%", height: "100%", objectFit: "cover",
          }}/>

          {/* Front PiP — draggable + tap-to-cycle shape */}
          {DraggablePip && pipShape && (
            <DraggablePip
              shape={pipShape}
              imageUrl="assets/reel-you-front-3.png"
              position={pipPos}
              setPosition={setPipPos}
              onTap={cycleShape}
            />
          )}

          {/* × Retake button: 32×32 top-right */}
          <button onClick={onClose} style={{
            position: "absolute", right: 12, top: 12,
            width: 32, height: 32, borderRadius: 99999,
            background: "linear-gradient(0deg,rgba(255,255,255,0.1),rgba(255,255,255,0.1)),rgba(0,0,0,0.5)",
            backdropFilter: "blur(35px)", WebkitBackdropFilter: "blur(35px)",
            border: "none", cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
            zIndex: 2,
          }}>
            <img src="assets/Container-close.svg" alt="×" width="16" height="16"
              style={{ display: "block" }}/>
          </button>

          {/* Control pills — bottom */}
          <div style={{
            position: "absolute", left: 0, right: 0, bottom: 0,
            height: 52,
            display: "flex", flexDirection: "row",
            justifyContent: "center", alignItems: "center",
            padding: "0 0 16px", gap: 8, zIndex: 2,
          }}>
            {/* Tag */}
            <PostPill>
              <IcoPersonPlus/>
              <PillLabel>1</PillLabel>
            </PostPill>

            {/* Location */}
            <PostPill>
              <IcoLocationSlash/>
              <PillLabel>No</PillLabel>
            </PostPill>

            {/* Music */}
            <PostPill>
              <IcoVinyl/>
            </PostPill>

          </div>
        </div>
      </div>

      {/* ══ AUDIENCE + SEND  flex-grow → ~101px ══ */}
      <div style={{
        width: 393, flexGrow: 1,
        display: "flex", alignItems: "center",
        padding: "0 16px", gap: 8, boxSizing: "border-box",
      }}>
        {/* AUDIENCE button */}
        <button onClick={() => !sending && setAudienceOpen(true)} style={{
          flex: 1, height: 56, borderRadius: 99999,
          background: "#2C2C2E", border: "none",
          cursor: sending ? "default" : "pointer",
          display: "flex", alignItems: "center", justifyContent: "center",
          gap: 6, padding: "0 20px", boxSizing: "border-box",
          flexDirection: "column",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{
              fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
              fontWeight: 590, fontSize: 17, letterSpacing: "-0.4px",
              color: "#fff", lineHeight: "22px",
            }}>AUDIENCE</span>
            {/* chevron-up: rotate the down chevron */}
            <img src="assets/ic_chevron_down.svg" alt="" width="20" height="20"
              style={{ display: "block", transform: "rotate(180deg)", opacity: 0.7 }}/>
          </div>
          {audienceSublabel && (
            <span style={{
              fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
              fontWeight: 500, fontSize: 12, letterSpacing: "-0.1px",
              color: "rgba(255,255,255,0.55)", lineHeight: "14px",
              marginTop: -2,
            }}>{audienceSublabel}</span>
          )}
        </button>

        {/* SEND button */}
        <button onClick={handleSend} disabled={sending} style={{
          flex: 1, height: 56, borderRadius: 99999,
          background: "#fff", border: "none",
          cursor: sending ? "default" : "pointer",
          display: "flex", alignItems: "center", justifyContent: "center",
          gap: 8, padding: "0 24px", boxSizing: "border-box",
          opacity: sending ? 0.55 : 1, transition: "opacity .2s",
        }}>
          <span style={{
            fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
            fontWeight: 590, fontSize: 17, letterSpacing: "-0.4px",
            color: "#000", lineHeight: "22px",
          }}>
            {sending ? "Sending…" : "SEND"}
          </span>
          {!sending && (
            <img src="assets/Send Icon.svg" alt="" width="20" height="20"
              style={{ display: "block", filter: "brightness(0)" }}/>
          )}
          {sending && (
            <svg width="20" height="20" viewBox="0 0 20 20"
              style={{ animation: "postSpin .75s linear infinite", flexShrink: 0 }}>
              <circle cx="10" cy="10" r="7" stroke="#000" strokeWidth="2"
                strokeDasharray="30 16" strokeLinecap="round" fill="none"/>
            </svg>
          )}
        </button>
      </div>

      {/* Audience sheet */}
      {audienceOpen && (
        <AudienceSheet
          circleSel={circleSel}
          feedChoice={feedChoice}
          onToggleCircle={toggleCircle}
          onPickFeed={setFeedChoice}
          onDone={() => setAudienceOpen(false)}
        />
      )}

      <style>{`
        .post-caption-input::placeholder { color: #99999C; }
        @keyframes postSpin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

window.PostingScreen = PostingScreen;
