/* capture.jsx — Capture Video screen
   Figma node-id: 13456-12303
   Layout: NavBar(111) + gap(29) + Content(712)
   PiP: draggable + shape-switchable (from original capture) */

/* ------------------------------------------------------------------ */
/*  Shape catalog                                                       */
/* ------------------------------------------------------------------ */

const SHAPES = {
  rect: { label: "Rectangle", width: 120, height: 160, radius: 18 },
  square: { label: "Square",  width: 130, height: 130, radius: 18 },
  heart: {
    label: "Heart", width: 144, height: 132,
    viewBox: "0 0 100 92",
    path: "M50 86 C 30 72, 5 56, 5 32 C 5 16, 18 6, 32 6 C 42 6, 48 12, 50 18 C 52 12, 58 6, 68 6 C 82 6, 95 16, 95 32 C 95 56, 70 72, 50 86 Z",
  },
  thinking: {
    label: "Thinking", width: 132, height: 144,
    viewBox: "0 0 100 110",
    path: "M22 28 C 22 18, 32 12, 42 14 C 46 6, 56 6, 60 12 C 70 8, 82 16, 80 28 C 92 30, 96 44, 88 52 C 96 60, 88 74, 76 72 C 72 82, 56 84, 50 74 C 42 84, 28 78, 28 68 C 14 70, 8 56, 18 48 C 8 40, 10 30, 22 28 Z M 18 86 A 6 6 0 1 1 18 86.01 Z M 8 100 A 3.5 3.5 0 1 1 8 100.01 Z",
  },
  cat: {
    label: "Cat", width: 142, height: 120,
    viewBox: "0 0 100 84",
    path: "M 50 82 C 28 82, 8 72, 5 55 C 2 40, 8 25, 18 17 C 20 15, 22 12, 24 8 C 25 5, 27 1, 29 0 C 31 -1, 33 1, 35 5 C 37 9, 38 13, 39 16 C 43 14, 46 13, 50 13 C 54 13, 57 14, 61 16 C 62 13, 63 9, 65 5 C 67 1, 69 -1, 71 0 C 73 1, 75 5, 76 8 C 78 12, 80 15, 82 17 C 92 25, 98 40, 95 55 C 92 72, 72 82, 50 82 Z",
  },
  circle: { label: "Circle", width: 130, height: 130, radius: 65 },
};

const SHAPE_ORDER = ["rect", "square", "circle", "heart", "thinking", "cat"];

/* Viewport size matches new Figma viewfinder */
const VIEWPORT = { w: 393, h: 524 };

/* ------------------------------------------------------------------ */
/*  ShapeGlyph — mini SVG icons for the picker row                    */
/* ------------------------------------------------------------------ */

function ShapeGlyph({ id, size = 26, color = "#fff", stroke = 1.8 }) {
  const com = { fill: "none", stroke: color, strokeWidth: stroke, strokeLinejoin: "round" };
  switch (id) {
    case "off":    return <svg width={size} height={size} viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke={color} strokeWidth={stroke}/><path d="M6 18 L18 6" stroke={color} strokeWidth={stroke} strokeLinecap="round"/></svg>;
    case "rect":   return <svg width={size} height={size} viewBox="0 0 24 24"><rect x="7" y="3" width="10" height="18" rx="2.5" {...com}/></svg>;
    case "square": return <svg width={size} height={size} viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2.5" {...com}/></svg>;
    case "heart":  return <svg width={size} height={size} viewBox="0 0 24 24"><path d="M12 20 C 5 14.5, 3 11, 3 8 C 3 5.5, 5 4, 7 4 C 9 4, 11 5.5, 12 7 C 13 5.5, 15 4, 17 4 C 19 4, 21 5.5, 21 8 C 21 11, 19 14.5, 12 20 Z" {...com}/></svg>;
    case "thinking": return <svg width={size} height={size} viewBox="0 0 24 24"><path d="M7 8 C 7 5.5, 9.5 4, 12 5 C 13 3, 16 3, 17 5 C 19 5, 20 7, 19.5 9 C 21 10, 20.5 13, 18 13 C 17.5 15, 14.5 15.5, 13.5 14 C 12 16, 8.5 15.5, 8.5 13 C 6 13, 5 10, 7 8 Z" {...com}/><circle cx="6.5" cy="17" r="1.4" {...com}/><circle cx="4" cy="20" r="0.8" {...com}/></svg>;
    case "cat":    return <svg width={size} height={size} viewBox="0 0 24 21"><path d="M 12 20 C 6.5 20, 1.5 17, 1 12.5 C 0.5 8.5, 2.5 5, 5.5 3.5 C 6 2.5, 6.5 1.5, 7 0.5 C 7.5 -0.2, 8.5 0, 9 1 C 9.5 2, 10 3.5, 10.5 4.5 C 11 4.2, 11.5 4, 12 4 C 12.5 4, 13 4.2, 13.5 4.5 C 14 3.5, 14.5 2, 15 1 C 15.5 0, 16.5 -0.2, 17 0.5 C 17.5 1.5, 18 2.5, 18.5 3.5 C 21.5 5, 23.5 8.5, 23 12.5 C 22.5 17, 17.5 20, 12 20 Z" {...com}/></svg>;
    case "circle": return <svg width={size} height={size} viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" {...com}/></svg>;
    default: return null;
  }
}

/* ------------------------------------------------------------------ */
/*  ShapedPip — front-cam image clipped to chosen shape               */
/* ------------------------------------------------------------------ */

function ShapedPip({ shape, imageUrl }) {
  const spec = SHAPES[shape];
  if (!spec.viewBox) {
    return (
      <div style={{
        width: spec.width, height: spec.height,
        borderRadius: spec.radius,
        background: `url(${imageUrl}) center/cover no-repeat, #111`,
        border: "2px solid rgba(0,0,0,0.6)",
        pointerEvents: "none",
      }}/>
    );
  }
  const clipId = `clip-${shape}`;
  return (
    <svg width={spec.width} height={spec.height} viewBox={spec.viewBox}
      style={{ overflow: "visible", pointerEvents: "none" }}>
      <defs>
        <clipPath id={clipId}><path d={spec.path}/></clipPath>
      </defs>
      <image href={imageUrl} x="0" y="0" width="100"
        height={spec.viewBox.split(" ")[3]}
        preserveAspectRatio="xMidYMid slice"
        clipPath={`url(#${clipId})`}/>
      <path d={spec.path} fill="none" stroke="rgba(0,0,0,0.55)" strokeWidth="1.5"/>
    </svg>
  );
}

/* ------------------------------------------------------------------ */
/*  MarchingAnts — animated dashed border overlay for onboarding      */
/* ------------------------------------------------------------------ */

function MarchingAnts({ shape }) {
  const spec = SHAPES[shape];
  const w = spec.width;
  const h = spec.height;
  const dashStyle = {
    fill: "none",
    stroke: "rgba(255,255,255,0.92)",
    strokeWidth: 2.5,
    strokeDasharray: "6 4",
    strokeLinecap: "round",
    animation: "dashMove 0.4s linear infinite",
  };

  if (!spec.viewBox) {
    const rx = spec.radius ?? 0;
    return (
      <svg width={w} height={h}
        style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 2, overflow: "visible" }}>
        <rect x="2" y="2" width={w - 4} height={h - 4} rx={rx} style={dashStyle}/>
      </svg>
    );
  }

  return (
    <svg width={w} height={h} viewBox={spec.viewBox}
      style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 2, overflow: "visible" }}>
      <path d={spec.path} style={dashStyle}/>
    </svg>
  );
}

/* ------------------------------------------------------------------ */
/*  OnboardingTooltip — dismissable bubble pointing at shape button   */
/* ------------------------------------------------------------------ */

function OnboardingTooltip({ onDismiss }) {
  return (
    <div style={{
      position: "absolute", right: 8, top: 112,
      zIndex: 22, maxWidth: 208,
      filter: "drop-shadow(0 4px 16px rgba(0,0,0,0.5))",
    }}>
      {/* Tail pointing up-right toward shape button */}
      <div style={{
        position: "absolute", right: 22, top: -7,
        width: 0, height: 0,
        borderLeft: "7px solid transparent",
        borderRight: "7px solid transparent",
        borderBottom: "8px solid rgba(28,28,30,0.93)",
      }}/>
      <div style={{
        background: "rgba(28,28,30,0.93)",
        backdropFilter: "blur(24px)", WebkitBackdropFilter: "blur(24px)",
        borderRadius: 13,
        border: "1px solid rgba(255,255,255,0.12)",
        padding: "10px 36px 10px 12px",
        position: "relative",
      }}>
        <button onClick={onDismiss} style={{
          position: "absolute", right: 8, top: 8,
          background: "transparent", border: "none", cursor: "pointer",
          color: "rgba(255,255,255,0.55)", fontSize: 18, lineHeight: 1,
          width: 22, height: 22, padding: 0,
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>×</button>
        <p style={{
          margin: 0,
          fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
          fontSize: 13, lineHeight: "18px", color: "#fff", fontWeight: 400,
        }}>
          Switch shapes &amp; drag to reposition your selfie
        </p>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  DraggablePip — wraps ShapedPip with pointer drag + tap-to-cycle  */
/* ------------------------------------------------------------------ */

function DraggablePip({ shape, imageUrl, position, setPosition, onTap, onboarding }) {
  const [dragging, setDragging] = React.useState(false);
  const ref = React.useRef({});
  const spec = SHAPES[shape];

  function onPointerDown(e) {
    e.preventDefault();
    e.target.setPointerCapture && e.target.setPointerCapture(e.pointerId);
    ref.current = { startX: e.clientX, startY: e.clientY, origX: position.x, origY: position.y, moved: false };
    setDragging(true);
  }

  function onPointerMove(e) {
    if (!dragging) return;
    const dx = e.clientX - ref.current.startX;
    const dy = e.clientY - ref.current.startY;
    if (Math.hypot(dx, dy) > 5) ref.current.moved = true;
    const wrap = document.getElementById("stage-wrap");
    const scale = wrap ? wrap.getBoundingClientRect().width / 393 : 1;
    const nx = Math.max(8, Math.min(VIEWPORT.w - spec.width  - 8, ref.current.origX + dx / scale));
    const ny = Math.max(8, Math.min(VIEWPORT.h - spec.height - 8, ref.current.origY + dy / scale));
    setPosition({ x: nx, y: ny });
  }

  function onPointerUp() {
    if (!dragging) return;
    setDragging(false);
    if (!ref.current.moved) onTap && onTap();
  }

  return (
    <div
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      onPointerCancel={onPointerUp}
      style={{
        position: "absolute", left: position.x, top: position.y,
        width: spec.width, height: spec.height,
        touchAction: "none",
        cursor: dragging ? "grabbing" : "grab",
        transition: dragging ? "none" : "left .35s cubic-bezier(.2,.7,.2,1), top .35s cubic-bezier(.2,.7,.2,1)",
        zIndex: 5, userSelect: "none",
      }}
    >
      <ShapedPip shape={shape} imageUrl={imageUrl}/>
      {/* {onboarding && <MarchingAnts shape={shape}/>} */}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  ShapePicker — dropdown from trailing nav button                   */
/* ------------------------------------------------------------------ */

function ShapePicker({ open, current, onPick, onClose }) {
  if (!open) return null;
  const items = ["off", ...SHAPE_ORDER];
  return (
    <React.Fragment>
      <span onClick={onClose} style={{ position: "absolute", inset: 0, zIndex: 16 }}/>
      <div style={{
        position: "absolute", right: 16, top: 108,
        zIndex: 18,
        background: "rgba(20,20,22,0.75)",
        backdropFilter: "blur(22px)", WebkitBackdropFilter: "blur(22px)",
        borderRadius: 99,
        border: "1px solid rgba(255,255,255,0.1)",
        padding: 4,
      }}>
        <div style={{ display: "flex", gap: 2, alignItems: "center" }}>
          {items.map(id => {
            const active = id === "off" ? current === null : current === id;
            return (
              <button key={id}
                onClick={() => { onPick(id === "off" ? null : id); }}
                style={{
                  background: "transparent", border: "none", padding: 0, cursor: "pointer",
                  width: 34, height: 34, borderRadius: "50%",
                  display: "grid", placeItems: "center",
                  backgroundColor: active ? "rgba(255,255,255,0.2)" : "transparent",
                }}
              >
                <ShapeGlyph id={id} size={20} color={active ? "#fff" : "rgba(255,255,255,0.75)"} stroke={1.6}/>
              </button>
            );
          })}
        </div>
      </div>
    </React.Fragment>
  );
}

/* ------------------------------------------------------------------ */
/*  CaptureScreen — main component                                     */
/* ------------------------------------------------------------------ */

function CaptureScreen({ onClose, onShutter }) {
  const [mode, setMode]           = React.useState("photo");
  const [shape, setShape]         = React.useState("rect");   /* null = PiP hidden */
  const [onboarding, setOnboarding] = React.useState(true);
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const [position, setPosition]   = React.useState({ x: 12, y: 12 });
  const [recording, setRecording] = React.useState(false);
  const [recMs, setRecMs]         = React.useState(0);

  /* Recording timer — setInterval every 500ms to avoid 60fps re-renders */
  React.useEffect(() => {
    if (!recording) { setRecMs(0); return; }
    const t0 = Date.now();
    const id = setInterval(() => {
      const ms = Date.now() - t0;
      if (ms >= 60000) {
        clearInterval(id);
        setRecording(false);
        onShutter && onShutter(shape, position);
        return;
      }
      setRecMs(ms);
    }, 500);
    return () => clearInterval(id);
  }, [recording]);

  /* Reclamp PiP when shape size changes */
  React.useEffect(() => {
    if (!shape) return;
    const spec = SHAPES[shape];
    setPosition(p => ({
      x: Math.max(8, Math.min(VIEWPORT.w - spec.width  - 8, p.x)),
      y: Math.max(8, Math.min(VIEWPORT.h - spec.height - 8, p.y)),
    }));
  }, [shape]);

  function cycleShape() {
    const idx = SHAPE_ORDER.indexOf(shape ?? SHAPE_ORDER[0]);
    setShape(SHAPE_ORDER[(idx + 1) % SHAPE_ORDER.length]);
  }

  function handleShutter() {
    if (mode === "photo") { onShutter && onShutter(shape, position); return; }
    if (recording) { setRecording(false); onShutter && onShutter(shape, position); }
    else setRecording(true);
  }

  /* Keep fresh refs so postMessage handler sees latest state */
  const stateRef = React.useRef({ shape, position });
  React.useEffect(() => { stateRef.current = { shape, position }; }, [shape, position]);

  /* Demo control via postMessage */
  React.useEffect(() => {
    function onDemoMsg(e) {
      if (!e.data || e.data.type !== 'bereal-demo') return;
      if (e.data.action === 'dismissOnboarding') setOnboarding(false);
      if (e.data.action === 'openShapePicker') { setOnboarding(false); setPickerOpen(true); }
      if (e.data.action === 'selectShape' && e.data.shape) { setShape(e.data.shape); setPickerOpen(false); }
      if (e.data.action === 'movePip') setPosition({ x: e.data.x, y: e.data.y });
      if (e.data.action === 'takePhoto') { const { shape: s, position: p } = stateRef.current; onShutter && onShutter(s, p); }
    }
    window.addEventListener('message', onDemoMsg);
    return () => window.removeEventListener('message', onDemoMsg);
  }, []);

  const recSec = Math.floor(recMs / 1000);
  const recDisplay = `${Math.floor(recSec / 60).toString().padStart(2, "0")}:${(recSec % 60).toString().padStart(2, "0")}`;

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: "#000", overflow: "hidden",
      borderRadius: "inherit",
      display: "flex", flexDirection: "column",
      alignItems: "center", gap: 29,
    }}>

      {/* ══ Navigation Bar ══ 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", flexDirection: "row",
          justifyContent: "center", alignItems: "center",
          padding: "0 16px 8px",
          width: 393, height: 52, boxSizing: "border-box",
        }}>
          {/* Chevron down */}
          <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>

          {/* BeReal. logo */}
          <img src="assets/Logo-bereal.svg" alt="BeReal." style={{ width: 74.67, height: 16 }}/>

          {/* Shape picker toggle — trailing right */}
          <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={shape ?? "off"} size={18} color="#fff" stroke={1.7}/>
          </button>
        </div>
      </div>

      {/* Shape picker dropdown */}
      <ShapePicker open={pickerOpen} current={shape}
        onPick={setShape} onClose={() => setPickerOpen(false)}/>

      {/* Onboarding tooltip — absolute so it sits just below the NavBar, pointing up at the shape button */}
      {onboarding && <OnboardingTooltip onDismiss={() => setOnboarding(false)}/>}

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

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

          {/* Recording indicator */}
          {recording && (
            <div style={{
              position: "absolute", top: 14, left: "50%", transform: "translateX(-50%)",
              display: "flex", alignItems: "center", gap: 6,
              background: "rgba(0,0,0,0.55)", padding: "5px 12px", borderRadius: 99, zIndex: 10,
            }}>
              <span style={{ width: 8, height: 8, borderRadius: 4, background: "#FF3B30", animation: "recPulse 1s ease-in-out infinite" }}/>
              <span style={{ fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif', fontWeight: 590, fontSize: 13, color: "#fff", fontVariantNumeric: "tabular-nums" }}>{recDisplay}</span>
            </div>
          )}

          {/* Draggable PiP */}
          {shape && (
            <DraggablePip
              shape={shape}
              imageUrl="assets/reel-you-front-3.png"
              position={position}
              setPosition={setPosition}
              onboarding={onboarding}
              onTap={() => { if (onboarding) { setOnboarding(false); } else { cycleShape(); } }}
            />
          )}

          {/* Camera controls at bottom */}
          <div style={{
            position: "absolute", left: 0, right: 0, bottom: 0,
            display: "flex", flexDirection: "row",
            justifyContent: "space-between", alignItems: "center",
            padding: "4px 20px", height: 52, boxSizing: "border-box",
          }}>
            <button style={{ width: 26, height: 26, background: "transparent", border: "none", cursor: "pointer", padding: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <img src="assets/Flash Icon.svg" alt="Flash" style={{ width: 26, height: 26 }}/>
            </button>
            <div style={{ width: 36, height: 36, borderRadius: 99999, background: "#000", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif', fontWeight: 590, fontSize: 15, letterSpacing: -0.2, color: "#fff" }}>1x</span>
            </div>
            <button style={{ width: 26, height: 26, background: "transparent", border: "none", cursor: "pointer", padding: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <img src="assets/Rotate Icon.svg" alt="Rotate" style={{ width: 26, height: 26 }}/>
            </button>
          </div>
        </div>

        {/* ── Media type ── 393×32 ── */}
        <div style={{ width: 393, height: 32, flexShrink: 0, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", padding: "8px 0", boxSizing: "border-box" }}>
          <div style={{ width: 192, height: 16, display: "flex", flexDirection: "row", justifyContent: "flex-start", alignItems: "center", gap: 24 }}>
            {[{ key: "video", label: "VIDEO" }, { key: "photo", label: "PHOTO" }].map(({ key, label }) => (
              <button key={key} onClick={() => setMode(key)} style={{
                width: 48, minWidth: 48, height: 16,
                background: "transparent", border: "none", cursor: "pointer", padding: 0,
                fontFamily: '-apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", sans-serif',
                fontWeight: 590, fontSize: 13, lineHeight: "16px",
                letterSpacing: -0.08, textTransform: "uppercase", textAlign: "center",
                color: mode === key ? "#FFCC00" : "#99999C", transition: "color .15s",
              }}>{label}</button>
            ))}
          </div>
        </div>

        {/* ── Shutter ── 393×156 ── */}
        <div style={{ width: 393, height: 156, flexShrink: 0, display: "flex", justifyContent: "center", alignItems: "center", paddingBottom: 32, boxSizing: "border-box" }}>
          <button onClick={handleShutter} style={{ background: "transparent", border: "none", cursor: "pointer", padding: 0, outline: "none" }}>
            <div style={{ width: 76, height: 76, borderRadius: "50%", border: "4px solid #fff", boxSizing: "border-box", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <div style={{
                width: recording ? 28 : 60,
                height: recording ? 28 : 60,
                borderRadius: recording ? 7 : "50%",
                background: recording ? "#FF3B30" : "#fff",
                transition: "width .2s ease, height .2s ease, border-radius .2s ease, background .2s ease",
              }}/>
            </div>
          </button>
        </div>
      </div>

      <style>{`
        @keyframes recPulse { 0%,100%{opacity:1} 50%{opacity:0.3} }
        @keyframes dashMove { to { stroke-dashoffset: -10; } }
      `}</style>
    </div>
  );
}

window.CaptureScreen = CaptureScreen;
window.SHAPES = SHAPES;
window.SHAPE_ORDER = SHAPE_ORDER;
window.ShapedPip = ShapedPip;
window.ShapeGlyph = ShapeGlyph;
window.DraggablePip = DraggablePip;
window.ShapePicker = ShapePicker;
