/* La3ib Game Platform - Responsive UI Overhaul */
/* Babel-safe: no backticks, no arrow, no const/let, no optional chaining, no JSX spread, no for...of, no raw Arabic */

var React = window.React || require("react");
var useState = React.useState;
var useEffect = React.useEffect;
var useRef = React.useRef;
var useCallback = React.useCallback;
var useMemo = React.useMemo;

/* ============================================ */
/*  RESPONSIVE SYSTEM                           */
/* ============================================ */

function useResponsive() {
  var getLayout = function() {
    var w = window.innerWidth;
    if (w >= 1200) return "desktop-lg";
    if (w >= 900) return "desktop";
    if (w >= 600) return "tablet";
    return "mobile";
  };
  var state = useState(getLayout());
  var layout = state[0];
  var setLayout = state[1];

  useEffect(function() {
    var handler = function() { setLayout(getLayout()); };
    window.addEventListener("resize", handler);
    return function() { window.removeEventListener("resize", handler); };
  }, []);

  return {
    layout: layout,
    isMobile: layout === "mobile",
    isTablet: layout === "tablet",
    isDesktop: layout === "desktop" || layout === "desktop-lg",
    isDesktopLg: layout === "desktop-lg",
    containerStyle: function() {
      if (layout === "mobile") return { maxWidth: 480, margin: "0 auto", width: "100%" };
      if (layout === "tablet") return { maxWidth: 768, margin: "0 auto", width: "100%" };
      return { maxWidth: 1400, margin: "0 auto", width: "100%", padding: "0 24px" };
    }
  };
}

/* ============================================ */
/*  PERSIST HELPER (fragile - do not remove)    */
/* ============================================ */

function usePersist(key, defaultVal) {
  var fullKey = "la3ib_" + key;
  var initial = function() {
    try {
      var stored = localStorage.getItem(fullKey);
      if (stored !== null) return JSON.parse(stored);
    } catch(e) {}
    return defaultVal;
  };
  var state = useState(initial);
  var val = state[0];
  var setVal = state[1];

  useEffect(function() {
    try { localStorage.setItem(fullKey, JSON.stringify(val)); } catch(e) {}
  }, [val, fullKey]);

  return [val, setVal];
}

/* ============================================ */
/*  THEME & COLORS                              */
/* ============================================ */

var THEME = {
  bg: "#0a0e17",
  bgCard: "#141b2d",
  bgCardHover: "#1a2340",
  bgSurface: "#0f1525",
  accent: "#c8a044",
  accentLight: "#dbb85c",
  accentDim: "#8a6e2f",
  blue: "#3b7dd8",
  blueLight: "#5a9cf0",
  red: "#d84040",
  redLight: "#f06060",
  green: "#40b860",
  greenLight: "#60d880",
  text: "#e8e8f0",
  textDim: "#8890a8",
  textMuted: "#505870",
  border: "#1e2844",
  borderLight: "#2a3558",
  felt: "#1a5c30",
  feltDark: "#0e3d1e",
  feltLight: "#228840",
  shadow: "0 4px 24px rgba(0,0,0,0.4)",
  shadowSm: "0 2px 8px rgba(0,0,0,0.3)",
  radius: 12,
  radiusSm: 8,
  radiusLg: 16
};

/* ============================================ */
/*  SOUND EFFECTS SYSTEM                        */
/* ============================================ */

var SoundManager = {
  ctx: null,
  enabled: true,
  _getCtx: function() {
    if (!this.ctx) {
      try { this.ctx = new (window.AudioContext || window.webkitAudioContext)(); } catch(e) {}
    }
    return this.ctx;
  },
  play: function(type) {
    if (!this.enabled) return;
    var ctx = this._getCtx();
    if (!ctx) return;
    try {
      var osc = ctx.createOscillator();
      var gain = ctx.createGain();
      osc.connect(gain);
      gain.connect(ctx.destination);

      if (type === "cardPlay") {
        osc.frequency.value = 800;
        osc.type = "sine";
        gain.gain.setValueAtTime(0.08, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.12);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.12);
      } else if (type === "cardDeal") {
        osc.frequency.value = 600;
        osc.type = "sine";
        gain.gain.setValueAtTime(0.04, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.06);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.06);
      } else if (type === "trickWin") {
        osc.frequency.value = 523;
        osc.type = "triangle";
        gain.gain.setValueAtTime(0.1, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.4);
        /* Second note */
        var osc2 = ctx.createOscillator();
        var gain2 = ctx.createGain();
        osc2.connect(gain2); gain2.connect(ctx.destination);
        osc2.frequency.value = 659;
        osc2.type = "triangle";
        gain2.gain.setValueAtTime(0.1, ctx.currentTime + 0.15);
        gain2.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.5);
        osc2.start(ctx.currentTime + 0.15);
        osc2.stop(ctx.currentTime + 0.5);
      } else if (type === "bid") {
        osc.frequency.value = 440;
        osc.type = "square";
        gain.gain.setValueAtTime(0.05, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.15);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.15);
      } else if (type === "yourTurn") {
        osc.frequency.value = 880;
        osc.type = "sine";
        gain.gain.setValueAtTime(0.08, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.2);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.2);
        var osc3 = ctx.createOscillator();
        var gain3 = ctx.createGain();
        osc3.connect(gain3); gain3.connect(ctx.destination);
        osc3.frequency.value = 1100;
        osc3.type = "sine";
        gain3.gain.setValueAtTime(0.08, ctx.currentTime + 0.12);
        gain3.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.3);
        osc3.start(ctx.currentTime + 0.12);
        osc3.stop(ctx.currentTime + 0.3);
      } else if (type === "taunt") {
        osc.frequency.value = 500;
        osc.type = "sine";
        gain.gain.setValueAtTime(0.06, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.1);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.1);
      } else if (type === "click") {
        osc.frequency.value = 1200;
        osc.type = "sine";
        gain.gain.setValueAtTime(0.03, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.04);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.04);
      } else if (type === "win") {
        var notes = [523, 659, 784, 1047];
        var ni = 0;
        while (ni < notes.length) {
          var o = ctx.createOscillator();
          var g = ctx.createGain();
          o.connect(g); g.connect(ctx.destination);
          o.frequency.value = notes[ni];
          o.type = "triangle";
          g.gain.setValueAtTime(0.08, ctx.currentTime + ni * 0.15);
          g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + ni * 0.15 + 0.3);
          o.start(ctx.currentTime + ni * 0.15);
          o.stop(ctx.currentTime + ni * 0.15 + 0.3);
          ni++;
        }
      } else if (type === "lose") {
        osc.frequency.value = 300;
        osc.type = "sawtooth";
        gain.gain.setValueAtTime(0.06, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.5);
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.5);
      }
    } catch(e) {}
  }
};

/* ============================================ */
/*  ANIMATION HELPERS                           */
/* ============================================ */

/* Hook for deal animation - returns className for each card index */
function useDealAnimation(cardCount) {
  var dealt = useState(false); var isDealt = dealt[0]; var setDealt = dealt[1];

  useEffect(function() {
    setDealt(false);
    var timer = setTimeout(function() { setDealt(true); }, 50);
    return function() { clearTimeout(timer); };
  }, [cardCount]);

  return {
    isDealt: isDealt,
    getCardClass: function(idx) {
      if (!isDealt) return "";
      return "la3ib-deal la3ib-d" + (idx + 1);
    }
  };
}

/* Confetti burst component for wins */
function ConfettiBurst(props) {
  if (!props.show) return null;
  var colors = [THEME.accent, THEME.blue, THEME.red, THEME.green, "#9050d0"];
  var pieces = [];
  var i = 0;
  while (i < 5) {
    pieces.push(
      React.createElement("div", {
        key: i,
        style: {
          position: "absolute",
          width: 8, height: 8,
          borderRadius: i % 2 === 0 ? "50%" : 0,
          background: colors[i % colors.length],
          animation: "la3ib-confetti-" + (i + 1) + " 0.8s ease-out forwards",
          top: "50%", left: "50%"
        }
      })
    );
    i++;
  }
  return React.createElement("div", {
    style: {
      position: "absolute", top: 0, left: 0, right: 0, bottom: 0,
      pointerEvents: "none", zIndex: 100,
      display: "flex", alignItems: "center", justifyContent: "center"
    }
  }, pieces);
}

/* Score animation component */
function AnimatedScore(props) {
  var prevVal = useRef(props.value);
  var animating = useState(false); var isAnim = animating[0]; var setAnim = animating[1];

  useEffect(function() {
    if (prevVal.current !== props.value) {
      setAnim(true);
      SoundManager.play("trickWin");
      var timer = setTimeout(function() { setAnim(false); }, 500);
      prevVal.current = props.value;
      return function() { clearTimeout(timer); };
    }
  }, [props.value]);

  return React.createElement("div", {
    style: Object.assign({
      animation: isAnim ? "la3ib-score-bump 0.5s ease" : "none",
      display: "inline-block"
    }, props.style || {})
  }, props.value);
}

/* Staggered list wrapper */
function StaggeredList(props) {
  var children = React.Children.toArray(props.children);
  return React.createElement("div", { style: props.style },
    children.map(function(child, idx) {
      return React.createElement("div", {
        key: idx,
        style: {
          animation: "la3ib-fadeIn 0.4s ease " + (idx * 0.06) + "s both"
        }
      }, child);
    })
  );
}

/* ============================================ */
/*  ICONS (SVG components)                      */
/* ============================================ */

function IconHome(props) {
  return React.createElement("svg", {width: props.size || 24, height: props.size || 24, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round"},
    React.createElement("path", {d: "M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"}),
    React.createElement("polyline", {points: "9 22 9 12 15 12 15 22"})
  );
}

function IconGames(props) {
  return React.createElement("svg", {width: props.size || 24, height: props.size || 24, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round"},
    React.createElement("rect", {x: 2, y: 4, width: 20, height: 16, rx: 3}),
    React.createElement("circle", {cx: 8, cy: 12, r: 2}),
    React.createElement("circle", {cx: 16, cy: 12, r: 2})
  );
}

function IconStore(props) {
  return React.createElement("svg", {width: props.size || 24, height: props.size || 24, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round"},
    React.createElement("path", {d: "M6 2L3 7v13a2 2 0 002 2h14a2 2 0 002-2V7l-3-5z"}),
    React.createElement("line", {x1: 3, y1: 7, x2: 21, y2: 7}),
    React.createElement("path", {d: "M16 11a4 4 0 01-8 0"})
  );
}

function IconTrophy(props) {
  return React.createElement("svg", {width: props.size || 24, height: props.size || 24, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round"},
    React.createElement("path", {d: "M6 9H4a2 2 0 01-2-2V5a2 2 0 012-2h2"}),
    React.createElement("path", {d: "M18 9h2a2 2 0 002-2V5a2 2 0 00-2-2h-2"}),
    React.createElement("path", {d: "M6 3h12v7a6 6 0 01-12 0V3z"}),
    React.createElement("path", {d: "M12 16v4"}),
    React.createElement("path", {d: "M8 22h8"})
  );
}

function IconProfile(props) {
  return React.createElement("svg", {width: props.size || 24, height: props.size || 24, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round"},
    React.createElement("circle", {cx: 12, cy: 8, r: 4}),
    React.createElement("path", {d: "M4 20c0-4 4-7 8-7s8 3 8 7"})
  );
}

function IconCards(props) {
  return React.createElement("svg", {width: props.size || 24, height: props.size || 24, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.text, strokeWidth: 2},
    React.createElement("rect", {x: 3, y: 2, width: 12, height: 17, rx: 2, transform: "rotate(-8 9 10.5)"}),
    React.createElement("rect", {x: 8, y: 3, width: 12, height: 17, rx: 2, transform: "rotate(5 14 11.5)"})
  );
}

function IconCoin(props) {
  var s = props.size || 20;
  return React.createElement("svg", {width: s, height: s, viewBox: "0 0 20 20"},
    React.createElement("circle", {cx: 10, cy: 10, r: 9, fill: THEME.accent, stroke: THEME.accentDim, strokeWidth: 1.5}),
    React.createElement("circle", {cx: 10, cy: 10, r: 6, fill: "none", stroke: THEME.accentDim, strokeWidth: 1}),
    React.createElement("text", {x: 10, y: 14, textAnchor: "middle", fill: THEME.bgCard, fontSize: 11, fontWeight: "bold"}, "C")
  );
}

function IconChevron(props) {
  return React.createElement("svg", {width: props.size || 16, height: props.size || 16, viewBox: "0 0 16 16", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round"},
    React.createElement("polyline", {points: props.direction === "left" ? "10 3 5 8 10 13" : "6 3 11 8 6 13"})
  );
}

function IconX(props) {
  return React.createElement("svg", {width: props.size || 20, height: props.size || 20, viewBox: "0 0 20 20", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round"},
    React.createElement("line", {x1: 4, y1: 4, x2: 16, y2: 16}),
    React.createElement("line", {x1: 16, y1: 4, x2: 4, y2: 16})
  );
}

function IconStar(props) {
  return React.createElement("svg", {width: props.size || 16, height: props.size || 16, viewBox: "0 0 16 16", fill: props.filled ? THEME.accent : "none", stroke: THEME.accent, strokeWidth: 1.5},
    React.createElement("path", {d: "M8 1l2.2 4.4L15 6.1l-3.5 3.4.8 4.9L8 12.1 3.7 14.4l.8-4.9L1 6.1l4.8-.7z"})
  );
}

/* ============================================ */
/*  COMMON COMPONENTS                           */
/* ============================================ */

function Button(props) {
  var hState = useState(false); var bHov = hState[0]; var setBHov = hState[1];
  var baseStyle = {
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    gap: 8,
    padding: props.size === "sm" ? "8px 16px" : props.size === "lg" ? "14px 28px" : "10px 22px",
    fontSize: props.size === "sm" ? 13 : props.size === "lg" ? 16 : 14,
    fontWeight: 600,
    borderRadius: THEME.radiusSm,
    border: "none",
    cursor: props.disabled ? "not-allowed" : "pointer",
    opacity: props.disabled ? 0.5 : 1,
    transition: "all 0.15s ease",
    fontFamily: "inherit",
    filter: bHov && !props.disabled ? "brightness(1.15)" : "none",
    transform: bHov && !props.disabled ? "translateY(-1px)" : "none"
  };

  var variants = {
    primary: { background: THEME.accent, color: THEME.bg },
    secondary: { background: THEME.bgCardHover, color: THEME.text, border: "1px solid " + THEME.border },
    danger: { background: THEME.red, color: "#fff" },
    ghost: { background: "transparent", color: THEME.textDim }
  };

  var variant = variants[props.variant || "primary"] || variants.primary;
  var style = Object.assign({}, baseStyle, variant, props.style || {});

  return React.createElement("button", {
    style: style,
    onClick: props.disabled ? undefined : props.onClick,
    onMouseEnter: function() { setBHov(true); },
    onMouseLeave: function() { setBHov(false); },
    title: props.title || ""
  }, props.children);
}

function Card(props) {
  var hoverState = useState(false);
  var isHovered = hoverState[0]; var setHovered = hoverState[1];
  var isClickable = !!props.onClick;

  var style = Object.assign({
    background: isHovered && isClickable ? THEME.bgCardHover : THEME.bgCard,
    borderRadius: THEME.radius,
    border: "1px solid " + (isHovered && isClickable ? THEME.borderLight : THEME.border),
    padding: props.padding !== undefined ? props.padding : 20,
    transition: "all 0.2s ease",
    transform: isHovered && isClickable ? "translateY(-2px)" : "none",
    boxShadow: isHovered && isClickable ? "0 8px 24px rgba(0,0,0,0.3)" : "none"
  }, props.style || {});

  return React.createElement("div", {
    style: style,
    onClick: props.onClick,
    onMouseEnter: isClickable ? function() { setHovered(true); } : undefined,
    onMouseLeave: isClickable ? function() { setHovered(false); } : undefined,
    className: props.className || ""
  }, props.children);
}

function Avatar(props) {
  var s = props.size || 40;
  var colors = ["#3b7dd8", "#d84040", "#c8a044", "#40b860", "#9050d0", "#d07030"];
  var colorIdx = 0;
  if (props.name) {
    var i = 0;
    while (i < props.name.length) { colorIdx = colorIdx + props.name.charCodeAt(i); i++; }
  }
  var bg = colors[colorIdx % colors.length];

  return React.createElement("div", {
    style: {
      width: s, height: s, borderRadius: "50%",
      background: bg, display: "flex", alignItems: "center", justifyContent: "center",
      color: "#fff", fontSize: s * 0.4, fontWeight: 700, flexShrink: 0
    }
  }, props.name ? props.name.charAt(0).toUpperCase() : "?");
}

function Badge(props) {
  var colors = {
    gold: { bg: THEME.accent, text: THEME.bg },
    blue: { bg: THEME.blue, text: "#fff" },
    red: { bg: THEME.red, text: "#fff" },
    green: { bg: THEME.green, text: "#fff" },
    dim: { bg: THEME.bgCardHover, text: THEME.textDim }
  };
  var c = colors[props.color || "dim"] || colors.dim;

  return React.createElement("span", {
    style: Object.assign({
      display: "inline-flex", alignItems: "center", gap: 4,
      padding: "3px 10px", borderRadius: 20,
      fontSize: 11, fontWeight: 600,
      background: c.bg, color: c.text
    }, props.style || {})
  }, props.children);
}

function TabBar(props) {
  var resp = useResponsive();
  return React.createElement("div", {
    style: {
      display: "flex",
      gap: resp.isDesktop ? 8 : 0,
      background: resp.isDesktop ? "transparent" : THEME.bgCard,
      borderTop: resp.isDesktop ? "none" : "1px solid " + THEME.border,
      padding: resp.isDesktop ? "0" : "8px 0 4px",
      justifyContent: resp.isDesktop ? "flex-start" : "space-around",
      position: resp.isDesktop ? "relative" : "fixed",
      bottom: resp.isDesktop ? "auto" : 0,
      left: 0, right: 0,
      zIndex: 100
    }
  }, props.tabs.map(function(tab, idx) {
    var active = props.activeTab === tab.id;
    return React.createElement("button", {
      key: tab.id,
      onClick: function() { props.onTabChange(tab.id); },
      style: {
        display: "flex",
        flexDirection: resp.isDesktop ? "row" : "column",
        alignItems: "center",
        gap: resp.isDesktop ? 8 : 2,
        padding: resp.isDesktop ? "10px 20px" : "4px 8px",
        background: active && resp.isDesktop ? THEME.bgCard : "transparent",
        border: active && resp.isDesktop ? "1px solid " + THEME.border : "1px solid transparent",
        borderRadius: resp.isDesktop ? THEME.radiusSm : 0,
        color: active ? THEME.accent : THEME.textDim,
        fontSize: resp.isDesktop ? 14 : 10,
        fontWeight: active ? 600 : 400,
        cursor: "pointer",
        transition: "all 0.2s",
        fontFamily: "inherit",
        flex: resp.isDesktop ? "none" : 1
      }
    },
      React.createElement(tab.icon, { size: resp.isDesktop ? 18 : 22, color: active ? THEME.accent : THEME.textDim }),
      React.createElement("span", null, tab.label)
    );
  }));
}

function SectionHeader(props) {
  return React.createElement("div", {
    style: Object.assign({
      display: "flex", alignItems: "center", justifyContent: "space-between",
      marginBottom: 16
    }, props.style || {})
  },
    React.createElement("h2", {
      style: { margin: 0, fontSize: 18, fontWeight: 700, color: THEME.text }
    }, props.title),
    props.action && React.createElement("button", {
      onClick: props.action.onClick,
      style: {
        background: "none", border: "none", color: THEME.accent,
        fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit"
      }
    }, props.action.label)
  );
}

function ResponsiveGrid(props) {
  var resp = useResponsive();
  var cols = props.cols || {};
  var colCount = resp.isMobile ? (cols.mobile || 1)
    : resp.isTablet ? (cols.tablet || 2)
    : resp.isDesktopLg ? (cols.desktopLg || cols.desktop || 3)
    : (cols.desktop || 3);

  return React.createElement("div", {
    style: Object.assign({
      display: "grid",
      gridTemplateColumns: "repeat(" + colCount + ", 1fr)",
      gap: props.gap || 16
    }, props.style || {})
  }, props.children);
}

/* ============================================ */
/*  LOGO                                        */
/* ============================================ */

function La3ibLogo(props) {
  var s = props.size || 32;

  /* Each card: dark card body with colored border + large colored suit shape in center */
  /* Using only basic SVG primitives: circle, polygon, rect - no path commands */
  function makeCard(tx, angle, borderColor, suitElements) {
    return React.createElement("g", { transform: "translate(" + tx + ", 24) rotate(" + angle + ")" },
      /* Card body */
      React.createElement("rect", { x: -11, y: -16, width: 22, height: 32, rx: 3, fill: "#0c1628", stroke: borderColor, strokeWidth: 1.8 }),
      /* Inner border */
      React.createElement("rect", { x: -8, y: -13, width: 16, height: 26, rx: 2, fill: "none", stroke: borderColor, strokeWidth: 0.5, opacity: 0.3 }),
      /* Suit shapes */
      suitElements
    );
  }

  /* Spade: upward triangle + circle base */
  var spade = React.createElement("g", null,
    React.createElement("polygon", { points: "0,-8 6,2 -6,2", fill: THEME.blue }),
    React.createElement("circle", { cx: -3, cy: 2, r: 3, fill: THEME.blue }),
    React.createElement("circle", { cx: 3, cy: 2, r: 3, fill: THEME.blue }),
    React.createElement("rect", { x: -1, y: 2, width: 2, height: 5, fill: THEME.blue })
  );

  /* Heart: two circles + downward triangle */
  var heart = React.createElement("g", null,
    React.createElement("circle", { cx: -3, cy: -3, r: 4, fill: THEME.red }),
    React.createElement("circle", { cx: 3, cy: -3, r: 4, fill: THEME.red }),
    React.createElement("polygon", { points: "-7,-1 7,-1 0,8", fill: THEME.red })
  );

  /* Diamond: rotated square */
  var diamond = React.createElement("g", null,
    React.createElement("rect", { x: -5, y: -5, width: 10, height: 10, fill: THEME.accent, transform: "rotate(45)" })
  );

  return React.createElement("div", {
    style: { display: "flex", alignItems: "center", gap: 10 }
  },
    React.createElement("svg", { width: s * 1.6, height: s * 1.2, viewBox: "0 0 76 48", overflow: "visible" },
      makeCard(26, -15, THEME.blue, spade),
      makeCard(38, 0, THEME.red, heart),
      makeCard(50, 15, THEME.accent, diamond)
    ),
    props.showText !== false && React.createElement("span", {
      style: { fontSize: s * 0.7, fontWeight: 800, color: THEME.text, letterSpacing: "-0.5px" }
    },
      "La",
      React.createElement("span", { style: { color: THEME.accent } }, "3"),
      "ib"
    )
  );
}

/* ============================================ */
/*  HEADER                                      */
/* ============================================ */

function AppHeader(props) {
  var resp = useResponsive();

  return React.createElement("div", {
    style: {
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      padding: resp.isDesktop ? "16px 0" : "12px 16px",
      borderBottom: "1px solid " + THEME.border,
      marginBottom: 16
    }
  },
    React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 16 } },
      React.createElement(La3ibLogo, { size: resp.isDesktop ? 36 : 28 }),
      resp.isDesktop && React.createElement(TabBar, {
        tabs: props.tabs,
        activeTab: props.activeTab,
        onTabChange: props.onTabChange
      })
    ),
    React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
      React.createElement("div", {
        style: {
          display: "flex", alignItems: "center", gap: 6,
          background: THEME.bgCardHover, padding: "6px 14px",
          borderRadius: 20, cursor: "pointer"
        },
        onClick: function() { if (props.onNavigate) props.onNavigate("store"); }
      },
        React.createElement(IconCoin, { size: 16 }),
        React.createElement("span", {
          style: { color: THEME.accent, fontSize: 14, fontWeight: 700 }
        }, props.coins || 0)
      ),
      React.createElement(NotificationBell, {
        onViewAll: function() { if (props.onNavigate) props.onNavigate("settings"); }
      }),
      React.createElement("button", {
        onClick: function() { if (props.onNavigate) props.onNavigate("settings"); },
        style: {
          display: "flex", alignItems: "center", justifyContent: "center",
          width: 34, height: 34, borderRadius: "50%",
          background: "transparent", border: "none", cursor: "pointer"
        }
      }, React.createElement(IconSettings, { size: 18, color: THEME.textDim })),
      React.createElement(Avatar, { name: props.username || "Player", size: 32 })
    )
  );
}

/* ============================================ */
/*  LOGIN SCREEN                                */
/* ============================================ */

function LoginScreen(props) {
  var resp = useResponsive();
  var formState = useState({ username: "", password: "", isRegister: false });
  var form = formState[0];
  var setForm = formState[1];
  var error = useState(""); var errorVal = error[0]; var setError = error[1];
  var loading = useState(false); var isLoading = loading[0]; var setLoading = loading[1];

  var apiBase = window.location.origin;

  var handleSubmit = function() {
    if (!form.username || !form.password) {
      setError("Please fill in all fields");
      return;
    }
    if (form.password.length < 4) {
      setError("Password must be at least 4 characters");
      return;
    }
    setLoading(true);
    setError("");
    var endpoint = form.isRegister ? "/api/auth/register" : "/api/auth/login";
    var body = { username: form.username, password: form.password };
    fetch(apiBase + endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
      setLoading(false);
      if (data.error) {
        setError(data.error);
        return;
      }
      if (data.token) {
        localStorage.setItem("la3ib_token", data.token);
        props.onLogin({ username: data.user.username, token: data.token, user: data.user });
      }
    })
    .catch(function(err) {
      setLoading(false);
      setError("Connection failed. Please try again.");
    });
  };

  var handleGuest = function() {
    setLoading(true);
    setError("");
    fetch(apiBase + "/api/auth/guest", {
      method: "POST",
      headers: { "Content-Type": "application/json" }
    })
    .then(function(res) { return res.json(); })
    .then(function(data) {
      setLoading(false);
      if (data.error) {
        setError(data.error);
        return;
      }
      if (data.token) {
        localStorage.setItem("la3ib_token", data.token);
        props.onLogin({ username: data.user.username, token: data.token, user: data.user, isGuest: true });
      }
    })
    .catch(function(err) {
      setLoading(false);
      setError("Connection failed. Please try again.");
    });
  };

  var inputStyle = {
    width: "100%",
    padding: "12px 16px",
    background: THEME.bgSurface,
    border: "1px solid " + THEME.border,
    borderRadius: THEME.radiusSm,
    color: THEME.text,
    fontSize: 15,
    outline: "none",
    fontFamily: "inherit",
    boxSizing: "border-box"
  };

  return React.createElement("div", {
    style: {
      minHeight: "100vh",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      background: THEME.bg,
      padding: 20
    }
  },
    React.createElement("div", {
      style: {
        width: "100%",
        maxWidth: resp.isDesktop ? 420 : 360,
        padding: 32,
        background: THEME.bgCard,
        borderRadius: THEME.radiusLg,
        border: "1px solid " + THEME.border,
        boxShadow: THEME.shadow
      }
    },
      React.createElement("div", { style: { textAlign: "center", marginBottom: 32 } },
        React.createElement("div", { style: { display: "flex", justifyContent: "center", marginBottom: 16 } },
          React.createElement(La3ibLogo, { size: 48 })
        ),
        React.createElement("p", { style: { color: THEME.textDim, margin: 0, fontSize: 14 } },
          form.isRegister ? "Create your account" : "Welcome back"
        )
      ),
      errorVal && React.createElement("div", {
        style: {
          padding: "10px 14px", background: "rgba(216,64,64,0.15)",
          border: "1px solid rgba(216,64,64,0.3)", borderRadius: THEME.radiusSm,
          color: THEME.redLight, fontSize: 13, marginBottom: 16
        }
      }, errorVal),
      React.createElement("div", { style: { marginBottom: 16 } },
        React.createElement("label", { style: { color: THEME.textDim, fontSize: 13, marginBottom: 6, display: "block" } }, "Username"),
        React.createElement("input", {
          type: "text",
          value: form.username,
          onChange: function(e) { setForm(Object.assign({}, form, { username: e.target.value })); setError(""); },
          style: inputStyle,
          placeholder: "Enter username"
        })
      ),
      React.createElement("div", { style: { marginBottom: 24 } },
        React.createElement("label", { style: { color: THEME.textDim, fontSize: 13, marginBottom: 6, display: "block" } }, "Password"),
        React.createElement("input", {
          type: "password",
          value: form.password,
          onChange: function(e) { setForm(Object.assign({}, form, { password: e.target.value })); setError(""); },
          style: inputStyle,
          placeholder: "Enter password"
        })
      ),
      React.createElement(Button, {
        variant: "primary",
        size: "lg",
        onClick: handleSubmit,
        disabled: isLoading,
        style: { width: "100%", marginBottom: 12 }
      }, isLoading ? "Connecting..." : (form.isRegister ? "Create Account" : "Sign In")),
      /* Divider */
      React.createElement("div", {
        style: { display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }
      },
        React.createElement("div", { style: { flex: 1, height: 1, background: THEME.border } }),
        React.createElement("span", { style: { color: THEME.textMuted, fontSize: 12 } }, "or"),
        React.createElement("div", { style: { flex: 1, height: 1, background: THEME.border } })
      ),
      /* Guest login */
      React.createElement(Button, {
        variant: "secondary",
        size: "lg",
        onClick: handleGuest,
        disabled: isLoading,
        style: { width: "100%", marginBottom: 16 }
      }, isLoading ? "Connecting..." : "Play as Guest"),
      React.createElement("div", { style: { textAlign: "center" } },
        React.createElement("button", {
          onClick: function() { setForm(Object.assign({}, form, { isRegister: !form.isRegister })); setError(""); },
          style: {
            background: "none", border: "none", color: THEME.accent,
            fontSize: 13, cursor: "pointer", fontFamily: "inherit"
          }
        }, form.isRegister ? "Already have an account? Sign In" : "New player? Create Account")
      )
    )
  );
}

/* ============================================ */
/*  HOME SCREEN                                 */
/* ============================================ */

function HomeScreen(props) {
  var resp = useResponsive();

  var featuredGames = [
    { id: "tarneeb", name: "Tarneeb", players: "4 Players", desc: "Classic Egyptian trick-taking", color: THEME.blue, badge: "Popular" },
    { id: "estimation", name: "Estimation", players: "4 Players", desc: "Bid and win tricks", color: THEME.green, badge: "New" },
    { id: "basra", name: "Basra", players: "2-4 Players", desc: "Capture cards from the floor", color: THEME.red, badge: "Coming Soon" }
  ];

  var quickActions = [
    { label: "Quick Match", sub: "Find a game now", color: THEME.accent, action: function() { if (props.onPlay) props.onPlay("tarneeb"); } },
    { label: "Play vs AI", sub: "Practice mode", color: THEME.blue, action: function() { if (props.onPlay) props.onPlay("tarneeb"); } },
    { label: "Create Room", sub: "Invite friends", color: THEME.green, action: function() { if (props.onPlay) props.onPlay("tarneeb"); } },
    { label: "Join Room", sub: "Enter code", color: THEME.red, action: function() { if (props.onPlay) props.onPlay("tarneeb"); } }
  ];

  var leaderboard = [
    { rank: 1, name: "KingOfTarneeb", rating: 2450, wins: 342 },
    { rank: 2, name: "CardMaster99", rating: 2380, wins: 298 },
    { rank: 3, name: "TarneebPro", rating: 2340, wins: 276 },
    { rank: 4, name: "AhwaChamp", rating: 2290, wins: 254 },
    { rank: 5, name: "DakkakElKart", rating: 2250, wins: 241 }
  ];

  /* Desktop: two-column layout. Mobile: single column */
  var mainContent = React.createElement("div", {
    style: {
      display: resp.isDesktop ? "grid" : "block",
      gridTemplateColumns: resp.isDesktop ? "1fr 340px" : "1fr",
      gap: 24
    }
  },
    /* Left column */
    React.createElement("div", null,
      /* Featured Games */
      React.createElement(SectionHeader, { title: "Featured Games", action: { label: "See All", onClick: function() { if (props.onNavigate) props.onNavigate("games"); } } }),
      React.createElement(ResponsiveGrid, {
        cols: { mobile: 1, tablet: 2, desktop: 2, desktopLg: 3 },
        gap: 14,
        style: { marginBottom: 24 }
      },
        featuredGames.map(function(game) {
          return React.createElement(Card, {
            key: game.id,
            style: { cursor: "pointer", position: "relative", overflow: "hidden" },
            onClick: function() { if (props.onPlay) props.onPlay(game.id); }
          },
            React.createElement("div", {
              style: {
                position: "absolute", top: 0, left: 0, right: 0, height: 4,
                background: game.color
              }
            }),
            React.createElement("div", { style: { display: "flex", alignItems: "flex-start", justifyContent: "space-between" } },
              React.createElement("div", null,
                React.createElement("h3", { style: { margin: "0 0 4px", color: THEME.text, fontSize: 16 } }, game.name),
                React.createElement("p", { style: { margin: "0 0 8px", color: THEME.textDim, fontSize: 13 } }, game.desc),
                React.createElement("span", { style: { color: THEME.textMuted, fontSize: 12 } }, game.players)
              ),
              React.createElement(Badge, { color: game.badge === "Popular" ? "gold" : game.badge === "New" ? "green" : "dim" }, game.badge)
            )
          );
        })
      ),

      /* Quick Actions */
      React.createElement(SectionHeader, { title: "Quick Play" }),
      React.createElement(ResponsiveGrid, {
        cols: { mobile: 2, tablet: 4, desktop: 4 },
        gap: 12,
        style: { marginBottom: 24 }
      },
        quickActions.map(function(action, idx) {
          return React.createElement(Card, {
            key: idx,
            style: { cursor: "pointer", textAlign: "center", padding: 16 },
            onClick: action.action
          },
            React.createElement("div", {
              style: {
                width: 40, height: 40, borderRadius: "50%",
                background: action.color + "22",
                display: "flex", alignItems: "center", justifyContent: "center",
                margin: "0 auto 10px"
              }
            },
              React.createElement(IconCards, { size: 20, color: action.color })
            ),
            React.createElement("div", { style: { fontWeight: 600, fontSize: 14, color: THEME.text, marginBottom: 2 } }, action.label),
            React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, action.sub)
          );
        })
      )
    ),

    /* Right column (sidebar on desktop, inline on mobile) */
    React.createElement("div", null,
      /* Mini Leaderboard */
      React.createElement(SectionHeader, { title: "Top Players", action: { label: "Full Board", onClick: function() { if (props.onNavigate) props.onNavigate("leaderboard"); } } }),
      React.createElement(Card, { padding: 0, style: { overflow: "hidden", marginBottom: 24 } },
        leaderboard.map(function(player, idx) {
          var rankColors = ["#FFD700", "#C0C0C0", "#CD7F32", THEME.textDim, THEME.textDim];
          return React.createElement("div", {
            key: idx,
            style: {
              display: "flex", alignItems: "center", gap: 12,
              padding: "12px 16px",
              borderBottom: idx < leaderboard.length - 1 ? "1px solid " + THEME.border : "none"
            }
          },
            React.createElement("div", {
              style: {
                width: 28, height: 28, borderRadius: "50%",
                background: idx < 3 ? rankColors[idx] + "22" : THEME.bgSurface,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: rankColors[idx], fontWeight: 700, fontSize: 13, flexShrink: 0
              }
            }, player.rank),
            React.createElement(Avatar, { name: player.name, size: 32 }),
            React.createElement("div", { style: { flex: 1, minWidth: 0 } },
              React.createElement("div", { style: { fontWeight: 600, fontSize: 14, color: THEME.text, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, player.name),
              React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, player.wins + " wins")
            ),
            React.createElement("div", {
              style: { fontWeight: 700, fontSize: 14, color: THEME.accent }
            }, player.rating)
          );
        })
      ),

      /* Online Friends */
      React.createElement(SectionHeader, {
        title: "Friends Online",
        action: { label: "See All", onClick: function() { if (props.onNavigate) props.onNavigate("social"); } }
      }),
      React.createElement(Card, { padding: 0, style: { overflow: "hidden" } },
        SAMPLE_FRIENDS.filter(function(f) { return f.status === "online"; }).length > 0
          ? SAMPLE_FRIENDS.filter(function(f) { return f.status === "online"; }).slice(0, 3).map(function(friend, idx, arr) {
              return React.createElement("div", {
                key: friend.id,
                style: {
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "10px 16px",
                  borderBottom: idx < arr.length - 1 ? "1px solid " + THEME.border : "none"
                }
              },
                React.createElement("div", { style: { position: "relative" } },
                  React.createElement(Avatar, { name: friend.name, size: 28 }),
                  React.createElement("div", {
                    style: {
                      position: "absolute", bottom: -1, right: -1,
                      width: 10, height: 10, borderRadius: "50%",
                      background: THEME.green, border: "2px solid " + THEME.bgCard
                    }
                  })
                ),
                React.createElement("div", { style: { flex: 1, minWidth: 0 } },
                  React.createElement("div", {
                    style: { fontWeight: 600, fontSize: 13, color: THEME.text, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }
                  }, friend.name),
                  React.createElement("div", { style: { fontSize: 11, color: THEME.textDim } },
                    friend.inGame ? "Playing " + friend.gameName : "Online"
                  )
                ),
                !friend.inGame && React.createElement(Button, { variant: "primary", size: "sm" }, "Invite")
              );
            })
          : React.createElement("div", { style: { textAlign: "center", padding: "16px", color: THEME.textDim, fontSize: 13 } },
              "No friends online right now"
            )
      )
    )
  );

  return mainContent;
}

/* ============================================ */
/*  GAMES SCREEN                                */
/* ============================================ */

function GamesScreen(props) {
  var resp = useResponsive();
  var filter = useState("all"); var activeFilter = filter[0]; var setFilter = filter[1];

  var games = [
    { id: "tarneeb", name: "Tarneeb", players: "4", type: "trick", desc: "Classic Egyptian trick-taking card game. Bid, call trump, and win tricks with your partner.", status: "available", color: THEME.blue, rating: 4.8, matches: "12.4K" },
    { id: "estimation", name: "Estimation", players: "4", type: "trick", desc: "Predict exactly how many tricks you will win each round.", status: "available", color: THEME.green, rating: 4.6, matches: "8.2K" },
    { id: "basra", name: "Basra", players: "2-4", type: "capture", desc: "Capture cards from the floor. Score points with special basra captures.", status: "coming", color: THEME.red, rating: 0, matches: "0" },
    { id: "trix", name: "Trix", players: "4", type: "trick", desc: "Four rounds with different objectives. Avoid cards or collect them.", status: "coming", color: "#9050d0", rating: 0, matches: "0" },
    { id: "hand", name: "Hand", players: "4", type: "trick", desc: "Egyptian variant of Whist with unique scoring rules.", status: "coming", color: "#d07030", rating: 0, matches: "0" },
    { id: "konkan", name: "Konkan", players: "2-4", type: "rummy", desc: "Form melds and runs to go out. Egyptian rummy variant.", status: "coming", color: "#30a0a0", rating: 0, matches: "0" }
  ];

  var filters = ["all", "available", "coming"];
  var filtered = activeFilter === "all" ? games : games.filter(function(g) { return g.status === activeFilter; });

  return React.createElement("div", null,
    React.createElement(SectionHeader, { title: "Games", style: { marginBottom: 8 } }),
    React.createElement("div", {
      style: { display: "flex", gap: 8, marginBottom: 20, flexWrap: "wrap" }
    },
      filters.map(function(f) {
        return React.createElement("button", {
          key: f,
          onClick: function() { setFilter(f); },
          style: {
            padding: "7px 18px",
            borderRadius: 20,
            border: "1px solid " + (activeFilter === f ? THEME.accent : THEME.border),
            background: activeFilter === f ? THEME.accent + "22" : "transparent",
            color: activeFilter === f ? THEME.accent : THEME.textDim,
            fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit",
            textTransform: "capitalize"
          }
        }, f === "coming" ? "Coming Soon" : f === "all" ? "All Games" : "Available");
      })
    ),
    React.createElement(ResponsiveGrid, {
      cols: { mobile: 1, tablet: 2, desktop: 3, desktopLg: 3 },
      gap: 16
    },
      filtered.map(function(game) {
        return React.createElement(Card, {
          key: game.id,
          style: {
            cursor: game.status === "available" ? "pointer" : "default",
            opacity: game.status === "coming" ? 0.7 : 1,
            position: "relative", overflow: "hidden"
          },
          onClick: game.status === "available" ? function() { if (props.onPlay) props.onPlay(game.id); } : undefined
        },
          React.createElement("div", {
            style: {
              position: "absolute", top: 0, left: 0, right: 0, height: 4,
              background: game.color
            }
          }),
          React.createElement("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 } },
            React.createElement("div", null,
              React.createElement("h3", { style: { margin: "0 0 4px", fontSize: 18, fontWeight: 700, color: THEME.text } }, game.name),
              React.createElement("span", { style: { fontSize: 12, color: THEME.textMuted } }, game.players + " Players")
            ),
            React.createElement(Badge, {
              color: game.status === "available" ? "green" : "dim"
            }, game.status === "available" ? "Play Now" : "Coming Soon")
          ),
          React.createElement("p", { style: { margin: "0 0 16px", fontSize: 13, color: THEME.textDim, lineHeight: 1.5 } }, game.desc),
          game.status === "available" && React.createElement("div", {
            style: { display: "flex", justifyContent: "space-between", alignItems: "center" }
          },
            React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 4 } },
              React.createElement(IconStar, { filled: true, size: 14 }),
              React.createElement("span", { style: { fontSize: 13, color: THEME.accent, fontWeight: 600 } }, game.rating)
            ),
            React.createElement("span", { style: { fontSize: 12, color: THEME.textMuted } }, game.matches + " matches")
          )
        );
      })
    )
  );
}

/* ============================================ */
/*  STORE SCREEN                                */
/* ============================================ */

function StoreScreen(props) {
  var resp = useResponsive();
  var tab = useState("coins"); var storeTab = tab[0]; var setStoreTab = tab[1];

  var coinPacks = [
    { id: 1, coins: 500, price: "$0.99", bonus: null, color: "#cd7f32" },
    { id: 2, coins: 1200, price: "$1.99", bonus: "+200", color: "#c0c0c0" },
    { id: 3, coins: 3000, price: "$4.99", bonus: "+500", color: THEME.accent },
    { id: 4, coins: 7000, price: "$9.99", bonus: "+1500", color: THEME.accent },
    { id: 5, coins: 15000, price: "$19.99", bonus: "+4000", color: "#b050ff" },
    { id: 6, coins: 35000, price: "$39.99", bonus: "+10000", color: "#ff5050" }
  ];

  var subscriptions = [
    { id: "free", name: "Free", price: "Free", features: ["3 games/day", "Basic avatars", "Ads shown"], current: true },
    { id: "silver", name: "Silver", price: "$4.99/mo", features: ["Unlimited games", "Silver badge", "No ads", "Custom taunts"], current: false },
    { id: "gold", name: "Gold", price: "$9.99/mo", features: ["Everything in Silver", "Gold badge", "Priority matchmaking", "Exclusive avatars", "Club creation"], current: false }
  ];

  var storeTabs = ["coins", "subscriptions", "cosmetics"];

  return React.createElement("div", null,
    /* Header */
    React.createElement("div", {
      style: {
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 20
      }
    },
      React.createElement("h2", { style: { margin: 0, fontSize: 22, fontWeight: 700, color: THEME.text } }, "Store"),
      React.createElement("div", {
        style: {
          display: "flex", alignItems: "center", gap: 8,
          background: THEME.bgCard, padding: "8px 16px",
          borderRadius: 20, border: "1px solid " + THEME.border
        }
      },
        React.createElement(IconCoin, { size: 18 }),
        React.createElement("span", { style: { color: THEME.accent, fontWeight: 700, fontSize: 16 } }, props.coins || 0)
      )
    ),

    /* Store Tabs */
    React.createElement("div", {
      style: { display: "flex", gap: 8, marginBottom: 24 }
    },
      storeTabs.map(function(t) {
        return React.createElement("button", {
          key: t,
          onClick: function() { setStoreTab(t); },
          style: {
            padding: "8px 20px", borderRadius: 20,
            border: "1px solid " + (storeTab === t ? THEME.accent : THEME.border),
            background: storeTab === t ? THEME.accent + "22" : "transparent",
            color: storeTab === t ? THEME.accent : THEME.textDim,
            fontSize: 13, fontWeight: 600, cursor: "pointer",
            fontFamily: "inherit", textTransform: "capitalize"
          }
        }, t);
      })
    ),

    /* Coin Packs */
    storeTab === "coins" && React.createElement(ResponsiveGrid, {
      cols: { mobile: 2, tablet: 3, desktop: 3, desktopLg: 4 },
      gap: 14
    },
      coinPacks.map(function(pack) {
        return React.createElement(Card, {
          key: pack.id,
          style: { textAlign: "center", cursor: "pointer", padding: 20, position: "relative", overflow: "hidden" }
        },
          pack.bonus && React.createElement("div", {
            style: {
              position: "absolute", top: 8, right: -20,
              background: THEME.green, color: "#fff",
              padding: "2px 28px", fontSize: 11, fontWeight: 700,
              transform: "rotate(35deg)"
            }
          }, pack.bonus),
          React.createElement("div", {
            style: {
              width: 56, height: 56, borderRadius: "50%",
              background: pack.color + "22", margin: "0 auto 12px",
              display: "flex", alignItems: "center", justifyContent: "center"
            }
          }, React.createElement(IconCoin, { size: 28 })),
          React.createElement("div", {
            style: { fontSize: 22, fontWeight: 800, color: THEME.text, marginBottom: 4 }
          }, pack.coins.toLocaleString()),
          React.createElement("div", {
            style: { fontSize: 12, color: THEME.textDim, marginBottom: 12 }
          }, "coins"),
          React.createElement(Button, { variant: "primary", size: "sm", style: { width: "100%" } }, pack.price)
        );
      })
    ),

    /* Subscriptions */
    storeTab === "subscriptions" && React.createElement(ResponsiveGrid, {
      cols: { mobile: 1, tablet: 3, desktop: 3 },
      gap: 16
    },
      subscriptions.map(function(sub) {
        var isGold = sub.id === "gold";
        return React.createElement(Card, {
          key: sub.id,
          style: {
            position: "relative",
            overflow: "hidden",
            border: isGold ? "2px solid " + THEME.accent : "1px solid " + THEME.border
          }
        },
          isGold && React.createElement("div", {
            style: {
              position: "absolute", top: 0, left: 0, right: 0, height: 4,
              background: "linear-gradient(90deg, " + THEME.accent + ", " + THEME.accentLight + ")"
            }
          }),
          React.createElement("div", { style: { marginBottom: 16 } },
            React.createElement("h3", { style: { margin: "0 0 4px", fontSize: 20, fontWeight: 700, color: isGold ? THEME.accent : THEME.text } }, sub.name),
            React.createElement("div", { style: { fontSize: 24, fontWeight: 800, color: THEME.text } }, sub.price)
          ),
          React.createElement("div", { style: { marginBottom: 20 } },
            sub.features.map(function(f, i) {
              return React.createElement("div", {
                key: i,
                style: { display: "flex", alignItems: "center", gap: 8, padding: "6px 0", color: THEME.textDim, fontSize: 13 }
              },
                React.createElement("span", { style: { color: THEME.green } }, "\u2713"),
                f
              );
            })
          ),
          React.createElement(Button, {
            variant: sub.current ? "secondary" : "primary",
            style: { width: "100%" },
            disabled: sub.current
          }, sub.current ? "Current Plan" : "Upgrade")
        );
      })
    ),

    /* Cosmetics placeholder */
    storeTab === "cosmetics" && React.createElement(Card, { style: { textAlign: "center", padding: 40 } },
      React.createElement("div", { style: { fontSize: 40, marginBottom: 12 } }, "\uD83C\uDFA8"),
      React.createElement("h3", { style: { margin: "0 0 8px", color: THEME.text } }, "Cosmetics Coming Soon"),
      React.createElement("p", { style: { margin: 0, color: THEME.textDim, fontSize: 14 } }, "Custom card backs, table themes, and avatar items")
    )
  );
}

/* ============================================ */
/*  LEADERBOARD SCREEN                          */
/* ============================================ */

function LeaderboardScreen(props) {
  var resp = useResponsive();
  var tab = useState("rating"); var activeTab = tab[0]; var setActiveTab = tab[1];

  var players = [
    { rank: 1, name: "KingOfTarneeb", rating: 2450, wins: 342, losses: 98, winRate: 77 },
    { rank: 2, name: "CardMaster99", rating: 2380, wins: 298, losses: 112, winRate: 73 },
    { rank: 3, name: "TarneebPro", rating: 2340, wins: 276, losses: 94, winRate: 75 },
    { rank: 4, name: "AhwaChamp", rating: 2290, wins: 254, losses: 126, winRate: 67 },
    { rank: 5, name: "DakkakElKart", rating: 2250, wins: 241, losses: 109, winRate: 69 },
    { rank: 6, name: "ShadyCards", rating: 2210, wins: 228, losses: 132, winRate: 63 },
    { rank: 7, name: "TrumpKing", rating: 2180, wins: 215, losses: 105, winRate: 67 },
    { rank: 8, name: "KabootMaster", rating: 2150, wins: 202, losses: 118, winRate: 63 },
    { rank: 9, name: "BluffWizard", rating: 2120, wins: 196, losses: 124, winRate: 61 },
    { rank: 10, name: "CardShark2024", rating: 2090, wins: 188, losses: 132, winRate: 59 }
  ];

  var tabs = ["rating", "wins", "win rate"];
  var rankColors = ["#FFD700", "#C0C0C0", "#CD7F32"];

  return React.createElement("div", null,
    React.createElement(SectionHeader, { title: "Leaderboard" }),

    /* Tabs */
    React.createElement("div", {
      style: { display: "flex", gap: 8, marginBottom: 24 }
    },
      tabs.map(function(t) {
        return React.createElement("button", {
          key: t,
          onClick: function() { setActiveTab(t); },
          style: {
            padding: "8px 20px", borderRadius: 20,
            border: "1px solid " + (activeTab === t ? THEME.accent : THEME.border),
            background: activeTab === t ? THEME.accent + "22" : "transparent",
            color: activeTab === t ? THEME.accent : THEME.textDim,
            fontSize: 13, fontWeight: 600, cursor: "pointer",
            fontFamily: "inherit", textTransform: "capitalize"
          }
        }, t);
      })
    ),

    /* Top 3 podium on desktop */
    resp.isDesktop && React.createElement("div", {
      style: {
        display: "grid", gridTemplateColumns: "1fr 1fr 1fr",
        gap: 16, marginBottom: 24
      }
    },
      [1, 0, 2].map(function(podIdx) {
        var p = players[podIdx];
        if (!p) return null;
        var isFirst = podIdx === 0;
        return React.createElement(Card, {
          key: podIdx,
          style: {
            textAlign: "center",
            padding: 24,
            border: isFirst ? "2px solid " + THEME.accent : "1px solid " + THEME.border,
            transform: isFirst ? "scale(1.05)" : "none"
          }
        },
          React.createElement("div", {
            style: {
              width: 48, height: 48, borderRadius: "50%",
              background: rankColors[podIdx] + "33",
              display: "flex", alignItems: "center", justifyContent: "center",
              margin: "0 auto 12px", fontSize: 20, fontWeight: 800,
              color: rankColors[podIdx]
            }
          }, p.rank),
          React.createElement(Avatar, { name: p.name, size: 56 }),
          React.createElement("div", { style: { fontWeight: 700, fontSize: 16, color: THEME.text, marginTop: 12 } }, p.name),
          React.createElement("div", { style: { fontSize: 24, fontWeight: 800, color: THEME.accent, margin: "8px 0" } }, p.rating),
          React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, p.wins + "W / " + p.losses + "L (" + p.winRate + "%)")
        );
      })
    ),

    /* Full table */
    React.createElement(Card, { padding: 0, style: { overflow: "hidden" } },
      /* Table header */
      resp.isDesktop && React.createElement("div", {
        style: {
          display: "grid",
          gridTemplateColumns: "60px 1fr 100px 100px 100px 100px",
          gap: 8, padding: "12px 20px",
          background: THEME.bgSurface,
          borderBottom: "1px solid " + THEME.border,
          color: THEME.textMuted, fontSize: 12, fontWeight: 600, textTransform: "uppercase"
        }
      },
        React.createElement("span", null, "Rank"),
        React.createElement("span", null, "Player"),
        React.createElement("span", { style: { textAlign: "right" } }, "Rating"),
        React.createElement("span", { style: { textAlign: "right" } }, "Wins"),
        React.createElement("span", { style: { textAlign: "right" } }, "Losses"),
        React.createElement("span", { style: { textAlign: "right" } }, "Win %")
      ),

      /* Rows */
      players.map(function(p, idx) {
        return React.createElement("div", {
          key: idx,
          style: {
            display: resp.isDesktop ? "grid" : "flex",
            gridTemplateColumns: resp.isDesktop ? "60px 1fr 100px 100px 100px 100px" : undefined,
            gap: 8,
            alignItems: "center",
            padding: resp.isDesktop ? "14px 20px" : "12px 16px",
            borderBottom: idx < players.length - 1 ? "1px solid " + THEME.border : "none"
          }
        },
          React.createElement("div", {
            style: {
              width: 32, height: 32, borderRadius: "50%",
              background: idx < 3 ? rankColors[idx] + "22" : THEME.bgSurface,
              display: "flex", alignItems: "center", justifyContent: "center",
              color: idx < 3 ? rankColors[idx] : THEME.textDim,
              fontWeight: 700, fontSize: 14, flexShrink: 0
            }
          }, p.rank),
          React.createElement("div", {
            style: { display: "flex", alignItems: "center", gap: 10, flex: resp.isDesktop ? undefined : 1, minWidth: 0 }
          },
            React.createElement(Avatar, { name: p.name, size: 32 }),
            React.createElement("span", {
              style: { fontWeight: 600, fontSize: 14, color: THEME.text, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }
            }, p.name)
          ),
          React.createElement("span", { style: { textAlign: "right", fontWeight: 700, color: THEME.accent, fontSize: 15 } }, p.rating),
          resp.isDesktop && React.createElement("span", { style: { textAlign: "right", color: THEME.green, fontSize: 14 } }, p.wins),
          resp.isDesktop && React.createElement("span", { style: { textAlign: "right", color: THEME.red, fontSize: 14 } }, p.losses),
          resp.isDesktop && React.createElement("span", { style: { textAlign: "right", color: THEME.textDim, fontSize: 14 } }, p.winRate + "%")
        );
      })
    )
  );
}

/* ============================================ */
/*  PROFILE SCREEN                              */
/* ============================================ */

function ProfileScreen(props) {
  var resp = useResponsive();
  var user = props.user || {};

  var stats = [
    { label: "Games Played", value: "247" },
    { label: "Win Rate", value: "64%" },
    { label: "Rating", value: "1850" },
    { label: "Coins", value: (props.coins || 0).toLocaleString() }
  ];

  return React.createElement("div", null,
    /* Profile Header */
    React.createElement(Card, {
      style: {
        display: resp.isDesktop ? "flex" : "block",
        alignItems: "center",
        gap: 24,
        padding: 24,
        marginBottom: 24
      }
    },
      React.createElement("div", {
        style: { textAlign: resp.isDesktop ? "left" : "center", marginBottom: resp.isDesktop ? 0 : 16 }
      },
        React.createElement(Avatar, { name: user.username || "Player", size: resp.isDesktop ? 80 : 64 }),
        React.createElement("h2", {
          style: { margin: "12px 0 4px", fontSize: 22, fontWeight: 700, color: THEME.text }
        }, user.username || "Player"),
        React.createElement("div", { style: { display: "flex", gap: 8, justifyContent: resp.isDesktop ? "flex-start" : "center" } },
          React.createElement(Badge, { color: "gold" }, "Silver"),
          React.createElement(Badge, { color: "dim" }, "Member since 2024")
        )
      ),
      React.createElement("div", { style: { flex: 1 } },
        React.createElement(ResponsiveGrid, {
          cols: { mobile: 2, tablet: 4, desktop: 4 },
          gap: 12
        },
          stats.map(function(s, i) {
            return React.createElement("div", {
              key: i,
              style: {
                textAlign: "center",
                padding: 16,
                background: THEME.bgSurface,
                borderRadius: THEME.radiusSm
              }
            },
              React.createElement("div", { style: { fontSize: 24, fontWeight: 800, color: THEME.accent } }, s.value),
              React.createElement("div", { style: { fontSize: 12, color: THEME.textDim, marginTop: 4 } }, s.label)
            );
          })
        )
      )
    ),

    /* Settings */
    resp.isDesktop ? React.createElement("div", {
      style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }
    },
      React.createElement(Card, null,
        React.createElement("h3", { style: { margin: "0 0 16px", color: THEME.text } }, "Account Settings"),
        React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 12 } },
          ["Edit Profile", "Change Password", "Notification Settings", "Privacy Settings"].map(function(item, i) {
            return React.createElement("button", {
              key: i,
              style: {
                display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "12px 16px", background: THEME.bgSurface,
                borderRadius: THEME.radiusSm, border: "none",
                color: THEME.text, fontSize: 14, cursor: "pointer",
                fontFamily: "inherit", textAlign: "left"
              }
            },
              item,
              React.createElement(IconChevron, { direction: "right" })
            );
          })
        )
      ),
      React.createElement(Card, null,
        React.createElement("h3", { style: { margin: "0 0 16px", color: THEME.text } }, "Game Settings"),
        React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 12 } },
          ["Card Style", "Table Theme", "Sound Settings", "Auto-Play Rules"].map(function(item, i) {
            return React.createElement("button", {
              key: i,
              style: {
                display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "12px 16px", background: THEME.bgSurface,
                borderRadius: THEME.radiusSm, border: "none",
                color: THEME.text, fontSize: 14, cursor: "pointer",
                fontFamily: "inherit", textAlign: "left"
              }
            },
              item,
              React.createElement(IconChevron, { direction: "right" })
            );
          })
        )
      )
    ) : React.createElement(Card, null,
      React.createElement("h3", { style: { margin: "0 0 16px", color: THEME.text } }, "Settings"),
      React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
        ["Edit Profile", "Change Password", "Card Style", "Sound Settings", "Privacy"].map(function(item, i) {
          return React.createElement("button", {
            key: i,
            style: {
              display: "flex", alignItems: "center", justifyContent: "space-between",
              padding: "12px 16px", background: THEME.bgSurface,
              borderRadius: THEME.radiusSm, border: "none",
              color: THEME.text, fontSize: 14, cursor: "pointer",
              fontFamily: "inherit", textAlign: "left"
            }
          },
            item,
            React.createElement(IconChevron, { direction: "right" })
          );
        })
      )
    ),

    /* Sign Out */
    React.createElement("div", { style: { marginTop: 24, textAlign: "center" } },
      React.createElement(Button, {
        variant: "danger",
        onClick: props.onLogout
      }, "Sign Out")
    )
  );
}

/* ============================================ */
/*  NOTIFICATIONS SYSTEM                        */
/* ============================================ */

function IconBellNav(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("path", { d: "M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9" }),
    React.createElement("path", { d: "M13.73 21a2 2 0 01-3.46 0" })
  );
}

function IconSettings(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("circle", { cx: 12, cy: 12, r: 3 }),
    React.createElement("path", { d: "M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09a1.65 1.65 0 00-1.08-1.51 1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09a1.65 1.65 0 001.51-1.08 1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001.08 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1.08z" })
  );
}

function IconCheck(props) {
  return React.createElement("svg", { width: props.size || 16, height: props.size || 16, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.green, strokeWidth: 3, strokeLinecap: "round" },
    React.createElement("polyline", { points: "20 6 9 17 4 12" })
  );
}

/* Sample notifications */
var SAMPLE_NOTIFICATIONS = [
  { id: 1, type: "friend_request", title: "Friend Request", message: "LuckyAce wants to be your friend", time: "2m ago", read: false, icon: "user" },
  { id: 2, type: "game_invite", title: "Game Invite", message: "CardMaster99 invited you to Tarneeb", time: "5m ago", read: false, icon: "cards" },
  { id: 3, type: "achievement", title: "Achievement Unlocked!", message: "Won 10 games in a row", time: "1h ago", read: false, icon: "trophy" },
  { id: 4, type: "system", title: "Welcome to La3ib!", message: "Start by playing a quick match or adding friends", time: "1d ago", read: true, icon: "info" },
  { id: 5, type: "friend_online", title: "Friend Online", message: "TarneebPro is now online", time: "3m ago", read: true, icon: "user" },
  { id: 6, type: "coins", title: "Daily Reward", message: "You received 50 coins!", time: "6h ago", read: true, icon: "coin" }
];

/* Notification Bell with dropdown */
function NotificationBell(props) {
  var isOpen = useState(false); var open = isOpen[0]; var setOpen = isOpen[1];
  var notifs = useState(SAMPLE_NOTIFICATIONS); var items = notifs[0]; var setItems = notifs[1];

  var unreadCount = 0;
  var ui = 0;
  while (ui < items.length) { if (!items[ui].read) unreadCount++; ui++; }

  var markAllRead = function() {
    setItems(items.map(function(n) { return Object.assign({}, n, { read: true }); }));
  };

  var markRead = function(id) {
    setItems(items.map(function(n) {
      if (n.id === id) return Object.assign({}, n, { read: true });
      return n;
    }));
  };

  var dismissNotif = function(id) {
    setItems(items.filter(function(n) { return n.id !== id; }));
  };

  var getNotifColor = function(type) {
    if (type === "friend_request") return THEME.blue;
    if (type === "game_invite") return THEME.green;
    if (type === "achievement") return THEME.accent;
    if (type === "coins") return THEME.accent;
    if (type === "friend_online") return THEME.green;
    return THEME.textDim;
  };

  var getNotifIcon = function(type) {
    if (type === "friend_request" || type === "friend_online") return React.createElement(IconProfile, { size: 16, color: THEME.blue });
    if (type === "game_invite") return React.createElement(IconCards, { size: 16, color: THEME.green });
    if (type === "achievement") return React.createElement(IconTrophy, { size: 16, color: THEME.accent });
    if (type === "coins") return React.createElement(IconCoin, { size: 14 });
    return React.createElement(IconBellNav, { size: 16, color: THEME.textDim });
  };

  return React.createElement("div", { style: { position: "relative" } },
    /* Bell button */
    React.createElement("button", {
      onClick: function() { SoundManager.play("click"); setOpen(!open); },
      style: {
        position: "relative",
        display: "flex", alignItems: "center", justifyContent: "center",
        width: 38, height: 38, borderRadius: "50%",
        background: open ? THEME.bgCardHover : "transparent",
        border: "1px solid " + (open ? THEME.border : "transparent"),
        cursor: "pointer", transition: "all 0.2s"
      }
    },
      React.createElement(IconBellNav, { size: 20, color: open ? THEME.accent : THEME.textDim }),
      unreadCount > 0 && React.createElement("div", {
        style: {
          position: "absolute", top: 2, right: 2,
          minWidth: 16, height: 16, borderRadius: 8,
          background: THEME.red, color: "#fff",
          fontSize: 10, fontWeight: 700,
          display: "flex", alignItems: "center", justifyContent: "center",
          padding: "0 4px",
          animation: "la3ib-badge-bounce 0.5s ease"
        }
      }, unreadCount)
    ),

    /* Dropdown */
    open && React.createElement("div", {
      style: {
        position: "absolute", top: "100%", right: 0,
        width: 360, maxHeight: 480,
        background: THEME.bgCard, border: "1px solid " + THEME.border,
        borderRadius: THEME.radius, boxShadow: THEME.shadow,
        marginTop: 8, zIndex: 200, overflow: "hidden",
        animation: "la3ib-fadeIn 0.2s ease"
      }
    },
      /* Header */
      React.createElement("div", {
        style: {
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "14px 16px", borderBottom: "1px solid " + THEME.border
        }
      },
        React.createElement("div", { style: { fontWeight: 700, fontSize: 15, color: THEME.text } }, "Notifications"),
        unreadCount > 0 && React.createElement("button", {
          onClick: markAllRead,
          style: {
            background: "none", border: "none", color: THEME.accent,
            fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "inherit"
          }
        }, "Mark all read")
      ),

      /* List */
      React.createElement("div", { style: { maxHeight: 400, overflowY: "auto" } },
        items.length === 0
          ? React.createElement("div", { style: { padding: 32, textAlign: "center", color: THEME.textDim, fontSize: 13 } }, "No notifications")
          : items.map(function(notif, idx) {
              return React.createElement("div", {
                key: notif.id,
                style: {
                  display: "flex", gap: 12, padding: "12px 16px",
                  background: notif.read ? "transparent" : THEME.bgSurface + "88",
                  borderBottom: idx < items.length - 1 ? "1px solid " + THEME.border : "none",
                  cursor: "pointer",
                  transition: "background 0.15s"
                },
                onClick: function() { markRead(notif.id); }
              },
                /* Icon */
                React.createElement("div", {
                  style: {
                    width: 36, height: 36, borderRadius: "50%",
                    background: getNotifColor(notif.type) + "18",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    flexShrink: 0
                  }
                }, getNotifIcon(notif.type)),
                /* Content */
                React.createElement("div", { style: { flex: 1, minWidth: 0 } },
                  React.createElement("div", {
                    style: { fontSize: 13, fontWeight: notif.read ? 400 : 600, color: THEME.text, marginBottom: 2 }
                  }, notif.title),
                  React.createElement("div", {
                    style: { fontSize: 12, color: THEME.textDim, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }
                  }, notif.message),
                  React.createElement("div", { style: { fontSize: 11, color: THEME.textMuted, marginTop: 4 } }, notif.time)
                ),
                /* Unread dot + dismiss */
                React.createElement("div", { style: { display: "flex", flexDirection: "column", alignItems: "center", gap: 6 } },
                  !notif.read && React.createElement("div", {
                    style: { width: 8, height: 8, borderRadius: "50%", background: THEME.accent }
                  }),
                  React.createElement("button", {
                    onClick: function(e) { e.stopPropagation(); dismissNotif(notif.id); },
                    style: {
                      background: "none", border: "none", cursor: "pointer", padding: 2
                    }
                  }, React.createElement(IconX, { size: 12, color: THEME.textMuted }))
                )
              );
            })
      ),

      /* Footer */
      React.createElement("div", {
        style: {
          padding: "10px 16px", borderTop: "1px solid " + THEME.border,
          textAlign: "center"
        }
      },
        React.createElement("button", {
          onClick: function() { setOpen(false); if (props.onViewAll) props.onViewAll(); },
          style: {
            background: "none", border: "none", color: THEME.accent,
            fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit"
          }
        }, "View All Notifications")
      )
    ),

    /* Click outside to close */
    open && React.createElement("div", {
      style: { position: "fixed", top: 0, left: 0, right: 0, bottom: 0, zIndex: 199 },
      onClick: function() { setOpen(false); }
    })
  );
}

/* ============================================ */
/*  SETTINGS SCREEN                             */
/* ============================================ */

function ToggleSwitch(props) {
  return React.createElement("button", {
    onClick: function() { SoundManager.play("click"); if (props.onChange) props.onChange(!props.value); },
    style: {
      width: 48, height: 26, borderRadius: 13,
      background: props.value ? THEME.accent : THEME.bgSurface,
      border: "2px solid " + (props.value ? THEME.accent : THEME.border),
      cursor: "pointer", position: "relative",
      transition: "all 0.2s ease", flexShrink: 0
    }
  },
    React.createElement("div", {
      style: {
        width: 18, height: 18, borderRadius: "50%",
        background: "#fff",
        position: "absolute", top: 2,
        left: props.value ? 24 : 2,
        transition: "left 0.2s ease",
        boxShadow: "0 1px 3px rgba(0,0,0,0.3)"
      }
    })
  );
}

function SettingsScreen(props) {
  var resp = useResponsive();
  var soundEnabled = usePersist("sound_enabled", true);
  var soundOn = soundEnabled[0]; var setSoundOn = soundEnabled[1];
  var musicEnabled = usePersist("music_enabled", false);
  var musicOn = musicEnabled[0]; var setMusicOn = musicEnabled[1];
  var vibrationEnabled = usePersist("vibration_enabled", true);
  var vibrationOn = vibrationEnabled[0]; var setVibrationOn = vibrationEnabled[1];
  var notifEnabled = usePersist("notif_enabled", true);
  var notifOn = notifEnabled[0]; var setNotifOn = notifEnabled[1];
  var friendNotif = usePersist("friend_notif", true);
  var friendNotifOn = friendNotif[0]; var setFriendNotifOn = friendNotif[1];
  var gameNotif = usePersist("game_notif", true);
  var gameNotifOn = gameNotif[0]; var setGameNotifOn = gameNotif[1];
  var autoPlay = usePersist("auto_play", false);
  var autoPlayOn = autoPlay[0]; var setAutoPlayOn = autoPlay[1];
  var showRating = usePersist("show_rating", true);
  var showRatingOn = showRating[0]; var setShowRatingOn = showRating[1];
  var cardStyle = usePersist("card_style", "classic");
  var cardStyleVal = cardStyle[0]; var setCardStyle = cardStyle[1];
  var tableTheme = usePersist("table_theme", "green");
  var tableThemeVal = tableTheme[0]; var setTableTheme = tableTheme[1];

  /* Sync sound toggle */
  useEffect(function() { SoundManager.enabled = soundOn; }, [soundOn]);

  function settingRow(label, description, control) {
    return React.createElement("div", {
      style: {
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "14px 0", borderBottom: "1px solid " + THEME.border
      }
    },
      React.createElement("div", { style: { flex: 1, marginRight: 16 } },
        React.createElement("div", { style: { fontSize: 14, fontWeight: 600, color: THEME.text, marginBottom: 2 } }, label),
        description && React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, description)
      ),
      control
    );
  }

  function optionButtons(options, current, onChange) {
    return React.createElement("div", { style: { display: "flex", gap: 6 } },
      options.map(function(opt) {
        var active = current === opt.value;
        return React.createElement("button", {
          key: opt.value,
          onClick: function() { SoundManager.play("click"); onChange(opt.value); },
          style: {
            padding: "6px 14px", borderRadius: 16,
            border: "1px solid " + (active ? THEME.accent : THEME.border),
            background: active ? THEME.accent + "22" : "transparent",
            color: active ? THEME.accent : THEME.textDim,
            fontSize: 12, fontWeight: 600, cursor: "pointer", fontFamily: "inherit"
          }
        }, opt.label);
      })
    );
  }

  var sections = [
    {
      title: "Sound & Haptics",
      items: [
        { label: "Sound Effects", desc: "Card sounds, notifications, UI feedback", control: React.createElement(ToggleSwitch, { value: soundOn, onChange: setSoundOn }) },
        { label: "Background Music", desc: "Ambient music during gameplay", control: React.createElement(ToggleSwitch, { value: musicOn, onChange: setMusicOn }) },
        { label: "Vibration", desc: "Haptic feedback on mobile", control: React.createElement(ToggleSwitch, { value: vibrationOn, onChange: setVibrationOn }) }
      ]
    },
    {
      title: "Notifications",
      items: [
        { label: "Push Notifications", desc: "Receive alerts when app is in background", control: React.createElement(ToggleSwitch, { value: notifOn, onChange: setNotifOn }) },
        { label: "Friend Activity", desc: "When friends come online or send requests", control: React.createElement(ToggleSwitch, { value: friendNotifOn, onChange: setFriendNotifOn }) },
        { label: "Game Invites", desc: "When someone invites you to a game", control: React.createElement(ToggleSwitch, { value: gameNotifOn, onChange: setGameNotifOn }) }
      ]
    },
    {
      title: "Gameplay",
      items: [
        { label: "Auto-Play Last Card", desc: "Automatically play when only one valid card remains", control: React.createElement(ToggleSwitch, { value: autoPlayOn, onChange: setAutoPlayOn }) },
        { label: "Show Rating", desc: "Display your rating to other players", control: React.createElement(ToggleSwitch, { value: showRatingOn, onChange: setShowRatingOn }) },
        {
          label: "Card Style", desc: "Visual style of playing cards",
          control: optionButtons(
            [{ value: "classic", label: "Classic" }, { value: "modern", label: "Modern" }, { value: "arabic", label: "Arabic" }],
            cardStyleVal, setCardStyle
          )
        },
        {
          label: "Table Theme", desc: "Color of the game table felt",
          control: optionButtons(
            [{ value: "green", label: "Green" }, { value: "blue", label: "Blue" }, { value: "red", label: "Red" }, { value: "dark", label: "Dark" }],
            tableThemeVal, setTableTheme
          )
        }
      ]
    }
  ];

  return React.createElement("div", null,
    React.createElement(SectionHeader, { title: "Settings" }),

    resp.isDesktop ? React.createElement("div", {
      style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }
    },
      sections.map(function(section, si) {
        return React.createElement(Card, {
          key: si,
          style: si === 2 ? { gridColumn: "1 / -1" } : undefined
        },
          React.createElement("h3", {
            style: { margin: "0 0 4px", fontSize: 16, fontWeight: 700, color: THEME.text }
          }, section.title),
          section.items.map(function(item, ii) {
            return React.createElement("div", { key: ii }, settingRow(item.label, item.desc, item.control));
          })
        );
      })
    ) : React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
      sections.map(function(section, si) {
        return React.createElement(Card, { key: si },
          React.createElement("h3", {
            style: { margin: "0 0 4px", fontSize: 16, fontWeight: 700, color: THEME.text }
          }, section.title),
          section.items.map(function(item, ii) {
            return React.createElement("div", { key: ii }, settingRow(item.label, item.desc, item.control));
          })
        );
      })
    ),

    /* Privacy & Safety */
    React.createElement(Card, { style: { marginTop: 20 } },
      React.createElement("h3", { style: { margin: "0 0 12px", fontSize: 16, fontWeight: 700, color: THEME.text } }, "Privacy & Safety"),
      React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 8 } },
        React.createElement("button", {
          onClick: function() { if (props.onNavigate) props.onNavigate("blocked"); },
          style: {
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "12px 16px", background: THEME.bgSurface,
            borderRadius: THEME.radiusSm, border: "none",
            color: THEME.text, fontSize: 14, cursor: "pointer",
            fontFamily: "inherit", textAlign: "left"
          }
        },
          React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
            React.createElement(IconSlash, { size: 16, color: THEME.red }),
            "Blocked Users"
          ),
          React.createElement(IconChevron, { direction: "right" })
        ),
        React.createElement("button", {
          style: {
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "12px 16px", background: THEME.bgSurface,
            borderRadius: THEME.radiusSm, border: "none",
            color: THEME.text, fontSize: 14, cursor: "pointer",
            fontFamily: "inherit", textAlign: "left"
          }
        },
          React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
            React.createElement(IconFlag, { size: 16, color: THEME.accent }),
            "Report History"
          ),
          React.createElement(IconChevron, { direction: "right" })
        ),
        React.createElement("button", {
          style: {
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "12px 16px", background: THEME.bgSurface,
            borderRadius: THEME.radiusSm, border: "none",
            color: THEME.text, fontSize: 14, cursor: "pointer",
            fontFamily: "inherit", textAlign: "left"
          }
        },
          React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
            React.createElement(IconShield, { size: 16, color: THEME.green }),
            "Safety Center"
          ),
          React.createElement(IconChevron, { direction: "right" })
        )
      )
    ),

    /* Danger zone */
    React.createElement(Card, {
      style: { marginTop: 20, border: "1px solid " + THEME.red + "33" }
    },
      React.createElement("h3", { style: { margin: "0 0 12px", fontSize: 16, fontWeight: 700, color: THEME.red } }, "Account"),
      React.createElement("div", { style: { display: "flex", gap: 12, flexWrap: "wrap" } },
        React.createElement(Button, { variant: "secondary", onClick: props.onLogout }, "Sign Out"),
        React.createElement(Button, { variant: "danger" }, "Delete Account")
      )
    )
  );
}

/* ============================================ */
/*  SOCIAL FEATURES                             */
/* ============================================ */

/* Social Icons */
function IconChat(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })
  );
}

function IconUserPlus(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("path", { d: "M16 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" }),
    React.createElement("circle", { cx: 8.5, cy: 7, r: 4 }),
    React.createElement("line", { x1: 20, y1: 8, x2: 20, y2: 14 }),
    React.createElement("line", { x1: 23, y1: 11, x2: 17, y2: 11 })
  );
}

function IconBell(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("path", { d: "M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9" }),
    React.createElement("path", { d: "M13.73 21a2 2 0 01-3.46 0" })
  );
}

function IconBlock(props) {
  return React.createElement("svg", { width: props.size || 16, height: props.size || 16, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.red, strokeWidth: 2 },
    React.createElement("circle", { cx: 12, cy: 12, r: 10 }),
    React.createElement("line", { x1: 4.93, y1: 4.93, x2: 19.07, y2: 19.07 })
  );
}

function IconSend(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.accent, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("line", { x1: 22, y1: 2, x2: 11, y2: 13 }),
    React.createElement("polygon", { points: "22 2 15 22 11 13 2 9 22 2" })
  );
}

/* Sample friends data */
var SAMPLE_FRIENDS = [
  { id: 1, name: "KingOfTarneeb", status: "online", rating: 2450, inGame: true, gameName: "Tarneeb" },
  { id: 2, name: "CardMaster99", status: "online", rating: 2380, inGame: false },
  { id: 3, name: "TarneebPro", status: "online", rating: 2340, inGame: false },
  { id: 4, name: "AhwaChamp", status: "away", rating: 2290, inGame: false },
  { id: 5, name: "BluffWizard", status: "offline", rating: 2120, lastSeen: "2h ago" },
  { id: 6, name: "CardShark2024", status: "offline", rating: 2090, lastSeen: "1d ago" },
  { id: 7, name: "SpadeQueen", status: "offline", rating: 1980, lastSeen: "3d ago" }
];

var SAMPLE_REQUESTS = [
  { id: 101, name: "LuckyAce", rating: 1850, mutual: 2 },
  { id: 102, name: "DoubleDown", rating: 2010, mutual: 0 }
];

/* Taunts data */
var TAUNTS = [
  { id: "laugh", emoji: "\uD83D\uDE02", label: "Haha" },
  { id: "think", emoji: "\uD83E\uDD14", label: "Hmm" },
  { id: "clap", emoji: "\uD83D\uDC4F", label: "GG" },
  { id: "fire", emoji: "\uD83D\uDD25", label: "Fire" },
  { id: "cry", emoji: "\uD83D\uDE2D", label: "No!" },
  { id: "flex", emoji: "\uD83D\uDCAA", label: "Easy" },
  { id: "wave", emoji: "\uD83D\uDC4B", label: "Hi" },
  { id: "sleep", emoji: "\uD83D\uDE34", label: "Zzz" },
  { id: "eyes", emoji: "\uD83D\uDC40", label: "Ooh" },
  { id: "skull", emoji: "\uD83D\uDC80", label: "Dead" },
  { id: "crown", emoji: "\uD83D\uDC51", label: "King" },
  { id: "pray", emoji: "\uD83D\uDE4F", label: "Pls" }
];

/* Chat messages sample */
var SAMPLE_MESSAGES = [
  { id: 1, sender: "KingOfTarneeb", text: "Who wants to play?", time: "2m ago", isYou: false },
  { id: 2, sender: "CardMaster99", text: "I'm in! Create a room", time: "1m ago", isYou: false },
  { id: 3, sender: "You", text: "Let's go, creating now", time: "30s ago", isYou: true }
];

/* ---- FRIENDS LIST SCREEN ---- */
function FriendsScreen(props) {
  var resp = useResponsive();
  var tab = useState("all"); var activeTab = tab[0]; var setTab = tab[1];
  var searchVal = useState(""); var search = searchVal[0]; var setSearch = searchVal[1];
  var showAddModal = useState(false); var addModal = showAddModal[0]; var setAddModal = showAddModal[1];
  var addInput = useState(""); var addVal = addInput[0]; var setAddVal = addInput[1];
  var addSent = useState(false); var sent = addSent[0]; var setSent = addSent[1];

  var statusColors = { online: THEME.green, away: THEME.accent, offline: THEME.textMuted };
  var tabs = ["all", "online", "requests"];

  var filtered = SAMPLE_FRIENDS;
  if (activeTab === "online") {
    filtered = SAMPLE_FRIENDS.filter(function(f) { return f.status === "online"; });
  }
  if (search) {
    filtered = filtered.filter(function(f) {
      return f.name.toLowerCase().indexOf(search.toLowerCase()) >= 0;
    });
  }

  var onlineCount = 0;
  var fi = 0;
  while (fi < SAMPLE_FRIENDS.length) {
    if (SAMPLE_FRIENDS[fi].status === "online") onlineCount++;
    fi++;
  }

  return React.createElement("div", null,
    /* Header */
    React.createElement("div", {
      style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }
    },
      React.createElement("div", null,
        React.createElement("h2", { style: { margin: 0, fontSize: 22, fontWeight: 700, color: THEME.text } }, "Friends"),
        React.createElement("p", { style: { margin: 0, color: THEME.textDim, fontSize: 13 } }, onlineCount + " online")
      ),
      React.createElement("div", { style: { display: "flex", gap: 8 } },
        React.createElement(Button, {
          variant: "primary", size: "sm",
          onClick: function() { setAddModal(true); setSent(false); setAddVal(""); }
        },
          React.createElement(IconUserPlus, { size: 16, color: THEME.bg }),
          "Add Friend"
        )
      )
    ),

    /* Search */
    React.createElement("div", { style: { marginBottom: 16 } },
      React.createElement("input", {
        type: "text",
        value: search,
        onChange: function(e) { setSearch(e.target.value); },
        placeholder: "Search friends...",
        style: {
          width: "100%", padding: "10px 16px",
          background: THEME.bgSurface, border: "1px solid " + THEME.border,
          borderRadius: THEME.radiusSm, color: THEME.text,
          fontSize: 14, outline: "none", fontFamily: "inherit",
          boxSizing: "border-box"
        }
      })
    ),

    /* Tabs */
    React.createElement("div", { style: { display: "flex", gap: 8, marginBottom: 20 } },
      tabs.map(function(t) {
        var label = t === "all" ? "All (" + SAMPLE_FRIENDS.length + ")" : t === "online" ? "Online (" + onlineCount + ")" : "Requests (" + SAMPLE_REQUESTS.length + ")";
        return React.createElement("button", {
          key: t,
          onClick: function() { setTab(t); },
          style: {
            padding: "7px 18px", borderRadius: 20,
            border: "1px solid " + (activeTab === t ? THEME.accent : THEME.border),
            background: activeTab === t ? THEME.accent + "22" : "transparent",
            color: activeTab === t ? THEME.accent : THEME.textDim,
            fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit"
          }
        }, label);
      })
    ),

    /* Content */
    resp.isDesktop ? React.createElement("div", {
      style: { display: "grid", gridTemplateColumns: "1fr 360px", gap: 20 }
    },
      /* Friends list */
      React.createElement("div", null,
        activeTab === "requests" ? React.createElement(Card, { padding: 0, style: { overflow: "hidden" } },
          SAMPLE_REQUESTS.length === 0
            ? React.createElement("div", { style: { padding: 32, textAlign: "center", color: THEME.textDim } }, "No pending requests")
            : SAMPLE_REQUESTS.map(function(req, idx) {
                return React.createElement("div", {
                  key: req.id,
                  style: {
                    display: "flex", alignItems: "center", gap: 12,
                    padding: "14px 16px",
                    borderBottom: idx < SAMPLE_REQUESTS.length - 1 ? "1px solid " + THEME.border : "none"
                  }
                },
                  React.createElement(Avatar, { name: req.name, size: 40 }),
                  React.createElement("div", { style: { flex: 1, minWidth: 0 } },
                    React.createElement("div", { style: { fontWeight: 600, fontSize: 14, color: THEME.text } }, req.name),
                    React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } },
                      "Rating: " + req.rating + (req.mutual > 0 ? " \u2022 " + req.mutual + " mutual friends" : "")
                    )
                  ),
                  React.createElement("div", { style: { display: "flex", gap: 8 } },
                    React.createElement(Button, { variant: "primary", size: "sm" }, "Accept"),
                    React.createElement(Button, { variant: "secondary", size: "sm" }, "Decline")
                  )
                );
              })
        ) : React.createElement(Card, { padding: 0, style: { overflow: "hidden" } },
          filtered.length === 0
            ? React.createElement("div", { style: { padding: 32, textAlign: "center", color: THEME.textDim } }, "No friends found")
            : filtered.map(function(friend, idx) {
                return React.createElement("div", {
                  key: friend.id,
                  style: {
                    display: "flex", alignItems: "center", gap: 12,
                    padding: "12px 16px",
                    borderBottom: idx < filtered.length - 1 ? "1px solid " + THEME.border : "none"
                  }
                },
                  React.createElement("div", { style: { position: "relative" } },
                    React.createElement(Avatar, { name: friend.name, size: 40 }),
                    React.createElement("div", {
                      style: {
                        position: "absolute", bottom: 0, right: 0,
                        width: 12, height: 12, borderRadius: "50%",
                        background: statusColors[friend.status] || THEME.textMuted,
                        border: "2px solid " + THEME.bgCard
                      }
                    })
                  ),
                  React.createElement("div", { style: { flex: 1, minWidth: 0 } },
                    React.createElement("div", { style: { fontWeight: 600, fontSize: 14, color: THEME.text, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, friend.name),
                    React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } },
                      friend.inGame ? "Playing " + friend.gameName : friend.status === "offline" ? "Last seen " + friend.lastSeen : friend.status === "away" ? "Away" : "Online"
                    )
                  ),
                  React.createElement("div", { style: { fontSize: 13, color: THEME.accent, fontWeight: 600, marginRight: 8 } }, friend.rating),
                  friend.status === "online" && !friend.inGame && React.createElement(Button, {
                    variant: "primary", size: "sm",
                    onClick: function() { if (props.onInvite) props.onInvite(friend); }
                  }, "Invite"),
                  friend.inGame && React.createElement(Badge, { color: "blue" }, "In Game"),
                  React.createElement(PlayerContextMenu, {
                    playerName: friend.name,
                    playerRating: friend.rating,
                    alignRight: true
                  },
                    React.createElement("button", {
                      style: {
                        background: "none", border: "none", color: THEME.textMuted,
                        fontSize: 18, cursor: "pointer", padding: "4px 8px",
                        fontFamily: "inherit", lineHeight: 1
                      }
                    }, "\u22EF")
                  )
                );
              })
        )
      ),

      /* Chat sidebar */
      React.createElement(ChatPanel, { username: props.username })
    ) : React.createElement("div", null,
      /* Mobile: just friends list */
      activeTab === "requests" ? React.createElement(Card, { padding: 0, style: { overflow: "hidden" } },
        SAMPLE_REQUESTS.map(function(req, idx) {
          return React.createElement("div", {
            key: req.id,
            style: { display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", borderBottom: idx < SAMPLE_REQUESTS.length - 1 ? "1px solid " + THEME.border : "none" }
          },
            React.createElement(Avatar, { name: req.name, size: 36 }),
            React.createElement("div", { style: { flex: 1, minWidth: 0 } },
              React.createElement("div", { style: { fontWeight: 600, fontSize: 14, color: THEME.text } }, req.name),
              React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, "Rating: " + req.rating)
            ),
            React.createElement(Button, { variant: "primary", size: "sm" }, "Accept")
          );
        })
      ) : React.createElement(Card, { padding: 0, style: { overflow: "hidden" } },
        filtered.map(function(friend, idx) {
          return React.createElement("div", {
            key: friend.id,
            style: { display: "flex", alignItems: "center", gap: 10, padding: "12px 16px", borderBottom: idx < filtered.length - 1 ? "1px solid " + THEME.border : "none" }
          },
            React.createElement("div", { style: { position: "relative" } },
              React.createElement(Avatar, { name: friend.name, size: 36 }),
              React.createElement("div", { style: { position: "absolute", bottom: 0, right: 0, width: 10, height: 10, borderRadius: "50%", background: statusColors[friend.status], border: "2px solid " + THEME.bgCard } })
            ),
            React.createElement("div", { style: { flex: 1, minWidth: 0 } },
              React.createElement("div", { style: { fontWeight: 600, fontSize: 13, color: THEME.text } }, friend.name),
              React.createElement("div", { style: { fontSize: 11, color: THEME.textDim } }, friend.status === "online" ? (friend.inGame ? "In Game" : "Online") : friend.lastSeen || "Away")
            ),
            React.createElement("span", { style: { fontSize: 12, color: THEME.accent, fontWeight: 600 } }, friend.rating)
          );
        })
      )
    ),

    /* Add Friend Modal */
    addModal && React.createElement("div", {
      style: {
        position: "fixed", top: 0, left: 0, right: 0, bottom: 0,
        background: "rgba(0,0,0,0.6)", display: "flex",
        alignItems: "center", justifyContent: "center", zIndex: 200
      },
      onClick: function() { setAddModal(false); }
    },
      React.createElement("div", {
        style: {
          width: "100%", maxWidth: 400, padding: 28,
          background: THEME.bgCard, borderRadius: THEME.radiusLg,
          border: "1px solid " + THEME.border, boxShadow: THEME.shadow
        },
        onClick: function(e) { e.stopPropagation(); }
      },
        React.createElement("h3", { style: { margin: "0 0 8px", color: THEME.text, fontSize: 18 } }, "Add Friend"),
        React.createElement("p", { style: { margin: "0 0 20px", color: THEME.textDim, fontSize: 13 } }, "Enter their username to send a friend request"),
        !sent ? React.createElement("div", null,
          React.createElement("input", {
            type: "text",
            value: addVal,
            onChange: function(e) { setAddVal(e.target.value); },
            placeholder: "Username",
            style: {
              width: "100%", padding: "12px 16px",
              background: THEME.bgSurface, border: "1px solid " + THEME.border,
              borderRadius: THEME.radiusSm, color: THEME.text,
              fontSize: 15, outline: "none", fontFamily: "inherit",
              boxSizing: "border-box", marginBottom: 16
            }
          }),
          React.createElement("div", { style: { display: "flex", gap: 12 } },
            React.createElement(Button, {
              variant: "secondary", onClick: function() { setAddModal(false); },
              style: { flex: 1 }
            }, "Cancel"),
            React.createElement(Button, {
              variant: "primary", disabled: !addVal,
              onClick: function() { setSent(true); },
              style: { flex: 2 }
            }, "Send Request")
          )
        ) : React.createElement("div", { style: { textAlign: "center", padding: "16px 0" } },
          React.createElement("div", { style: { fontSize: 40, marginBottom: 12 } }, "\u2705"),
          React.createElement("div", { style: { color: THEME.text, fontWeight: 600, marginBottom: 4 } }, "Request Sent!"),
          React.createElement("div", { style: { color: THEME.textDim, fontSize: 13, marginBottom: 16 } }, "Sent to " + addVal),
          React.createElement(Button, { variant: "secondary", onClick: function() { setAddModal(false); } }, "Done")
        )
      )
    )
  );
}

/* ---- CHAT PANEL ---- */
function ChatPanel(props) {
  var messages = useState(SAMPLE_MESSAGES); var msgs = messages[0]; var setMsgs = messages[1];
  var input = useState(""); var inputVal = input[0]; var setInput = input[1];
  var channel = useState("general"); var ch = channel[0]; var setCh = channel[1];

  var channels = [
    { id: "general", name: "General", unread: 3 },
    { id: "lfg", name: "Looking for Game", unread: 1 },
    { id: "strategy", name: "Strategy Talk", unread: 0 }
  ];

  var handleSend = function() {
    if (!inputVal.trim()) return;
    var newMsg = {
      id: msgs.length + 1,
      sender: "You",
      text: inputVal,
      time: "now",
      isYou: true
    };
    setMsgs(msgs.concat([newMsg]));
    setInput("");
  };

  return React.createElement(Card, {
    style: { display: "flex", flexDirection: "column", height: 460, padding: 0, overflow: "hidden" }
  },
    /* Channel tabs */
    React.createElement("div", {
      style: {
        display: "flex", gap: 0, borderBottom: "1px solid " + THEME.border,
        overflowX: "auto"
      }
    },
      channels.map(function(c) {
        return React.createElement("button", {
          key: c.id,
          onClick: function() { setCh(c.id); },
          style: {
            padding: "10px 16px", background: "transparent",
            border: "none", borderBottom: ch === c.id ? "2px solid " + THEME.accent : "2px solid transparent",
            color: ch === c.id ? THEME.accent : THEME.textDim,
            fontSize: 12, fontWeight: 600, cursor: "pointer",
            fontFamily: "inherit", whiteSpace: "nowrap",
            display: "flex", alignItems: "center", gap: 6
          }
        },
          c.name,
          c.unread > 0 && React.createElement("span", {
            style: {
              background: THEME.red, color: "#fff",
              fontSize: 10, fontWeight: 700,
              padding: "1px 6px", borderRadius: 10, minWidth: 16, textAlign: "center"
            }
          }, c.unread)
        );
      })
    ),

    /* Messages area */
    React.createElement("div", {
      style: {
        flex: 1, overflowY: "auto", padding: 12,
        display: "flex", flexDirection: "column", gap: 8
      }
    },
      msgs.map(function(msg) {
        return React.createElement("div", {
          key: msg.id,
          style: {
            display: "flex",
            flexDirection: msg.isYou ? "row-reverse" : "row",
            gap: 8, alignItems: "flex-end"
          }
        },
          !msg.isYou && React.createElement(Avatar, { name: msg.sender, size: 24 }),
          React.createElement("div", {
            style: {
              maxWidth: "75%", padding: "8px 12px",
              background: msg.isYou ? THEME.accent + "22" : THEME.bgSurface,
              borderRadius: 12,
              borderBottomRightRadius: msg.isYou ? 4 : 12,
              borderBottomLeftRadius: msg.isYou ? 12 : 4
            }
          },
            !msg.isYou && React.createElement("div", {
              style: { fontSize: 11, fontWeight: 600, color: THEME.accent, marginBottom: 2 }
            }, msg.sender),
            React.createElement("div", { style: { fontSize: 13, color: THEME.text, lineHeight: 1.4 } }, msg.text),
            React.createElement("div", { style: { fontSize: 10, color: THEME.textMuted, marginTop: 2, textAlign: msg.isYou ? "right" : "left" } }, msg.time)
          )
        );
      })
    ),

    /* Input */
    React.createElement("div", {
      style: {
        display: "flex", gap: 8, padding: 12,
        borderTop: "1px solid " + THEME.border
      }
    },
      React.createElement("input", {
        type: "text",
        value: inputVal,
        onChange: function(e) { setInput(e.target.value); },
        onKeyDown: function(e) { if (e.key === "Enter") handleSend(); },
        placeholder: "Type a message...",
        style: {
          flex: 1, padding: "8px 14px",
          background: THEME.bgSurface, border: "1px solid " + THEME.border,
          borderRadius: 20, color: THEME.text, fontSize: 13,
          outline: "none", fontFamily: "inherit"
        }
      }),
      React.createElement("button", {
        onClick: handleSend,
        style: {
          width: 36, height: 36, borderRadius: "50%",
          background: THEME.accent, border: "none",
          display: "flex", alignItems: "center", justifyContent: "center",
          cursor: "pointer", flexShrink: 0
        }
      },
        React.createElement(IconSend, { size: 16, color: THEME.bg })
      )
    )
  );
}

/* ---- IN-GAME TAUNTS PANEL ---- */
function TauntsPanel(props) {
  var isOpen = useState(false); var open = isOpen[0]; var setOpen = isOpen[1];
  var lastTaunt = useState(null); var taunt = lastTaunt[0]; var setTaunt = lastTaunt[1];
  var showBubble = useState(false); var bubble = showBubble[0]; var setBubble = showBubble[1];

  var handleTaunt = function(t) {
    SoundManager.play("taunt");
    setTaunt(t);
    setBubble(true);
    setOpen(false);
    setTimeout(function() { setBubble(false); }, 2500);
  };

  return React.createElement("div", { style: { position: "relative" } },
    /* Taunt bubble floating above */
    bubble && taunt && React.createElement("div", {
      style: {
        position: "absolute", bottom: "100%", left: "50%",
        transform: "translateX(-50%)",
        background: THEME.bgCard, border: "1px solid " + THEME.border,
        borderRadius: 16, padding: "8px 16px",
        boxShadow: THEME.shadow, marginBottom: 8,
        whiteSpace: "nowrap", zIndex: 50,
        animation: "la3ib-fadeup 0.3s ease"
      }
    },
      React.createElement("span", { style: { fontSize: 24 } }, taunt.emoji),
      React.createElement("span", { style: { fontSize: 13, color: THEME.text, marginLeft: 8, fontWeight: 600 } }, taunt.label)
    ),

    /* Toggle button */
    React.createElement("button", {
      onClick: function() { setOpen(!open); },
      style: {
        display: "flex", alignItems: "center", gap: 6,
        padding: "8px 14px", background: THEME.bgCard,
        border: "1px solid " + THEME.border, borderRadius: 20,
        color: THEME.textDim, fontSize: 13, cursor: "pointer",
        fontFamily: "inherit"
      }
    },
      React.createElement(IconChat, { size: 16, color: THEME.textDim }),
      "Taunt"
    ),

    /* Taunts grid popup */
    open && React.createElement("div", {
      style: {
        position: "absolute", bottom: "100%", left: 0,
        background: THEME.bgCard, border: "1px solid " + THEME.border,
        borderRadius: THEME.radius, padding: 12,
        boxShadow: THEME.shadow, marginBottom: 8,
        display: "grid", gridTemplateColumns: "repeat(4, 1fr)",
        gap: 6, width: 220, zIndex: 50
      }
    },
      TAUNTS.map(function(t) {
        return React.createElement("button", {
          key: t.id,
          onClick: function() { handleTaunt(t); },
          style: {
            display: "flex", flexDirection: "column", alignItems: "center",
            gap: 2, padding: "8px 4px",
            background: THEME.bgSurface, border: "1px solid " + THEME.border,
            borderRadius: THEME.radiusSm, cursor: "pointer",
            fontFamily: "inherit"
          }
        },
          React.createElement("span", { style: { fontSize: 20 } }, t.emoji),
          React.createElement("span", { style: { fontSize: 9, color: THEME.textDim } }, t.label)
        );
      })
    ),

    /* Fadeup animation */
    React.createElement("style", null,
      "@keyframes la3ib-fadeup { from { opacity: 0; transform: translateX(-50%) translateY(8px); } to { opacity: 1; transform: translateX(-50%) translateY(0); } }"
    )
  );
}

/* ---- OPPONENT TAUNT BUBBLE (shown on felt table) ---- */
function OpponentTauntBubble(props) {
  var taunt = props.taunt;
  if (!taunt) return null;
  return React.createElement("div", {
    style: {
      position: "absolute",
      background: THEME.bgCard + "ee",
      border: "1px solid " + THEME.border,
      borderRadius: 12, padding: "4px 10px",
      boxShadow: THEME.shadowSm,
      zIndex: 20, whiteSpace: "nowrap",
      animation: "la3ib-fadeup 0.3s ease"
    }
  },
    React.createElement("span", { style: { fontSize: 18 } }, taunt.emoji)
  );
}

/* ============================================ */
/*  REPORT / BLOCK / MODERATION SYSTEM          */
/* ============================================ */

function IconFlag(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.red, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("path", { d: "M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" }),
    React.createElement("line", { x1: 4, y1: 22, x2: 4, y2: 15 })
  );
}

function IconShield(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.accent, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("path", { d: "M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" })
  );
}

function IconEye(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2 },
    React.createElement("path", { d: "M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" }),
    React.createElement("circle", { cx: 12, cy: 12, r: 3 })
  );
}

function IconSlash(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.red, strokeWidth: 2 },
    React.createElement("circle", { cx: 12, cy: 12, r: 10 }),
    React.createElement("line", { x1: 4.93, y1: 4.93, x2: 19.07, y2: 19.07 })
  );
}

function IconMute(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2 },
    React.createElement("polygon", { points: "11 5 6 9 2 9 2 15 6 15 11 19 11 5" }),
    React.createElement("line", { x1: 23, y1: 9, x2: 17, y2: 15 }),
    React.createElement("line", { x1: 17, y1: 9, x2: 23, y2: 15 })
  );
}

/* Report reasons */
var REPORT_REASONS = [
  { id: "cheating", label: "Cheating / Exploiting", desc: "Using bugs or external tools to gain unfair advantage" },
  { id: "abuse", label: "Abusive Chat / Taunts", desc: "Offensive, hateful, or harassing messages" },
  { id: "harassment", label: "Targeted Harassment", desc: "Repeatedly targeting or bullying a specific player" },
  { id: "collusion", label: "Collusion", desc: "Secretly cooperating with opponents" },
  { id: "stalling", label: "Intentional Stalling", desc: "Deliberately wasting time to frustrate others" },
  { id: "inappropriate", label: "Inappropriate Username/Avatar", desc: "Offensive or inappropriate profile content" },
  { id: "other", label: "Other", desc: "Something else not listed above" }
];

/* ---- REPORT MODAL ---- */
function ReportModal(props) {
  var selectedReason = useState(null); var reason = selectedReason[0]; var setReason = selectedReason[1];
  var details = useState(""); var detailsVal = details[0]; var setDetails = details[1];
  var submitted = useState(false); var isSub = submitted[0]; var setSub = submitted[1];
  var submitting = useState(false); var isLoading = submitting[0]; var setLoading = submitting[1];

  if (!props.show) return null;

  var handleSubmit = function() {
    if (!reason) return;
    setLoading(true);
    /* Simulate API call */
    setTimeout(function() {
      setLoading(false);
      setSub(true);
    }, 1200);
  };

  return React.createElement("div", {
    style: {
      position: "fixed", top: 0, left: 0, right: 0, bottom: 0,
      background: "rgba(0,0,0,0.7)", display: "flex",
      alignItems: "center", justifyContent: "center", zIndex: 300,
      animation: "la3ib-fadeIn 0.2s ease"
    },
    onClick: function() { if (!isLoading) props.onClose(); }
  },
    React.createElement("div", {
      style: {
        width: "100%", maxWidth: 480, maxHeight: "85vh",
        background: THEME.bgCard, borderRadius: THEME.radiusLg,
        border: "1px solid " + THEME.border, boxShadow: THEME.shadow,
        overflow: "hidden", display: "flex", flexDirection: "column"
      },
      onClick: function(e) { e.stopPropagation(); }
    },
      /* Header */
      React.createElement("div", {
        style: {
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "16px 20px", borderBottom: "1px solid " + THEME.border
        }
      },
        React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
          React.createElement(IconFlag, { size: 20, color: THEME.red }),
          React.createElement("h3", { style: { margin: 0, fontSize: 17, fontWeight: 700, color: THEME.text } },
            "Report " + (props.playerName || "Player")
          )
        ),
        React.createElement("button", {
          onClick: props.onClose,
          style: { background: "none", border: "none", cursor: "pointer", padding: 4 }
        }, React.createElement(IconX, { size: 18, color: THEME.textDim }))
      ),

      /* Body */
      isSub ? React.createElement("div", {
        style: { padding: 40, textAlign: "center" }
      },
        React.createElement("div", {
          style: {
            width: 64, height: 64, borderRadius: "50%",
            background: THEME.green + "18", display: "flex",
            alignItems: "center", justifyContent: "center",
            margin: "0 auto 16px"
          }
        }, React.createElement(IconShield, { size: 32, color: THEME.green })),
        React.createElement("h3", { style: { margin: "0 0 8px", color: THEME.text, fontSize: 18 } }, "Report Submitted"),
        React.createElement("p", { style: { margin: "0 0 8px", color: THEME.textDim, fontSize: 14, lineHeight: 1.5 } },
          "Thank you for helping keep La3ib safe. Our moderation team will review this report within 24 hours."
        ),
        React.createElement("p", { style: { margin: "0 0 24px", color: THEME.textMuted, fontSize: 12 } },
          "Report ID: #RPT-" + Math.floor(Math.random() * 90000 + 10000)
        ),
        React.createElement(Button, { variant: "primary", onClick: props.onClose }, "Done")
      ) : React.createElement("div", {
        style: { flex: 1, overflowY: "auto", padding: 20 }
      },
        /* Player info */
        React.createElement("div", {
          style: {
            display: "flex", alignItems: "center", gap: 12,
            padding: "12px 14px", background: THEME.bgSurface,
            borderRadius: THEME.radiusSm, marginBottom: 20
          }
        },
          React.createElement(Avatar, { name: props.playerName || "Player", size: 36 }),
          React.createElement("div", null,
            React.createElement("div", { style: { fontWeight: 600, fontSize: 14, color: THEME.text } }, props.playerName || "Player"),
            React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, "Rating: " + (props.playerRating || "---"))
          )
        ),

        /* Reason selection */
        React.createElement("div", { style: { marginBottom: 20 } },
          React.createElement("div", {
            style: { fontSize: 13, fontWeight: 600, color: THEME.textDim, marginBottom: 10, textTransform: "uppercase", letterSpacing: "0.5px" }
          }, "Select a reason"),
          REPORT_REASONS.map(function(r) {
            var selected = reason === r.id;
            return React.createElement("button", {
              key: r.id,
              onClick: function() { SoundManager.play("click"); setReason(r.id); },
              style: {
                display: "flex", alignItems: "flex-start", gap: 12,
                width: "100%", padding: "12px 14px",
                background: selected ? THEME.accent + "12" : "transparent",
                border: "1px solid " + (selected ? THEME.accent + "44" : THEME.border),
                borderRadius: THEME.radiusSm,
                cursor: "pointer", textAlign: "left",
                fontFamily: "inherit", marginBottom: 8,
                transition: "all 0.15s ease"
              }
            },
              React.createElement("div", {
                style: {
                  width: 20, height: 20, borderRadius: "50%",
                  border: "2px solid " + (selected ? THEME.accent : THEME.border),
                  display: "flex", alignItems: "center", justifyContent: "center",
                  flexShrink: 0, marginTop: 1
                }
              },
                selected && React.createElement("div", {
                  style: { width: 10, height: 10, borderRadius: "50%", background: THEME.accent }
                })
              ),
              React.createElement("div", null,
                React.createElement("div", { style: { fontSize: 14, fontWeight: 600, color: selected ? THEME.accent : THEME.text, marginBottom: 2 } }, r.label),
                React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, r.desc)
              )
            );
          })
        ),

        /* Additional details */
        React.createElement("div", { style: { marginBottom: 20 } },
          React.createElement("div", {
            style: { fontSize: 13, fontWeight: 600, color: THEME.textDim, marginBottom: 8 }
          }, "Additional details (optional)"),
          React.createElement("textarea", {
            value: detailsVal,
            onChange: function(e) { setDetails(e.target.value); },
            placeholder: "Describe what happened...",
            rows: 3,
            style: {
              width: "100%", padding: "10px 14px",
              background: THEME.bgSurface, border: "1px solid " + THEME.border,
              borderRadius: THEME.radiusSm, color: THEME.text,
              fontSize: 13, outline: "none", fontFamily: "inherit",
              resize: "vertical", boxSizing: "border-box"
            }
          })
        ),

        /* Actions */
        React.createElement("div", { style: { display: "flex", gap: 12 } },
          React.createElement(Button, {
            variant: "secondary",
            onClick: props.onClose,
            style: { flex: 1 }
          }, "Cancel"),
          React.createElement(Button, {
            variant: "danger",
            disabled: !reason || isLoading,
            onClick: handleSubmit,
            style: { flex: 2 }
          }, isLoading ? "Submitting..." : "Submit Report")
        )
      )
    )
  );
}

/* ---- BLOCK CONFIRM MODAL ---- */
function BlockConfirmModal(props) {
  if (!props.show) return null;
  var blocked = useState(false); var isBlocked = blocked[0]; var setBlocked = blocked[1];

  return React.createElement("div", {
    style: {
      position: "fixed", top: 0, left: 0, right: 0, bottom: 0,
      background: "rgba(0,0,0,0.7)", display: "flex",
      alignItems: "center", justifyContent: "center", zIndex: 300,
      animation: "la3ib-fadeIn 0.2s ease"
    },
    onClick: props.onClose
  },
    React.createElement("div", {
      style: {
        width: "100%", maxWidth: 400, padding: 28,
        background: THEME.bgCard, borderRadius: THEME.radiusLg,
        border: "1px solid " + THEME.border, boxShadow: THEME.shadow
      },
      onClick: function(e) { e.stopPropagation(); }
    },
      isBlocked ? React.createElement("div", { style: { textAlign: "center" } },
        React.createElement("div", { style: { fontSize: 40, marginBottom: 12 } }, "\uD83D\uDEAB"),
        React.createElement("h3", { style: { margin: "0 0 8px", color: THEME.text } }, (props.playerName || "Player") + " Blocked"),
        React.createElement("p", { style: { margin: "0 0 20px", color: THEME.textDim, fontSize: 13, lineHeight: 1.5 } },
          "They can no longer send you messages, game invites, or friend requests. You won't be matched with them."
        ),
        React.createElement(Button, { variant: "secondary", onClick: props.onClose }, "Done")
      ) : React.createElement("div", null,
        React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 10, marginBottom: 16 } },
          React.createElement(IconSlash, { size: 24, color: THEME.red }),
          React.createElement("h3", { style: { margin: 0, color: THEME.text, fontSize: 18 } }, "Block " + (props.playerName || "Player") + "?")
        ),
        React.createElement("p", { style: { margin: "0 0 20px", color: THEME.textDim, fontSize: 14, lineHeight: 1.5 } },
          "Blocking this player will prevent them from contacting you, inviting you to games, or being matched with you. You can unblock them later from your blocked list."
        ),
        React.createElement("div", { style: { display: "flex", gap: 12 } },
          React.createElement(Button, { variant: "secondary", onClick: props.onClose, style: { flex: 1 } }, "Cancel"),
          React.createElement(Button, {
            variant: "danger", style: { flex: 2 },
            onClick: function() { SoundManager.play("click"); setBlocked(true); if (props.onBlock) props.onBlock(props.playerName); }
          }, "Block Player")
        )
      )
    )
  );
}

/* ---- PLAYER CONTEXT MENU (right-click / long-press on player) ---- */
function PlayerContextMenu(props) {
  var isOpen = useState(false); var open = isOpen[0]; var setOpen = isOpen[1];
  var showReport = useState(false); var report = showReport[0]; var setReport = showReport[1];
  var showBlock = useState(false); var block = showBlock[0]; var setBlock = showBlock[1];

  if (!props.playerName) return props.children || null;

  var menuItems = [
    { label: "View Profile", icon: IconEye, color: THEME.textDim, action: function() { setOpen(false); } },
    { label: "Send Message", icon: IconChat, color: THEME.blue, action: function() { setOpen(false); } },
    { label: "Invite to Game", icon: IconCards, color: THEME.green, action: function() { setOpen(false); } },
    { label: "Mute Player", icon: IconMute, color: THEME.accent, action: function() { SoundManager.play("click"); setOpen(false); } },
    { label: "Report", icon: IconFlag, color: THEME.red, action: function() { setOpen(false); setReport(true); } },
    { label: "Block", icon: IconSlash, color: THEME.red, action: function() { setOpen(false); setBlock(true); } }
  ];

  return React.createElement("div", { style: { position: "relative", display: "inline-block" } },
    /* Trigger */
    React.createElement("div", {
      onClick: function(e) { e.stopPropagation(); SoundManager.play("click"); setOpen(!open); },
      style: { cursor: "pointer" }
    }, props.children),

    /* Menu dropdown */
    open && React.createElement("div", {
      style: {
        position: "absolute", top: "100%",
        left: props.alignRight ? undefined : 0,
        right: props.alignRight ? 0 : undefined,
        width: 200, background: THEME.bgCard,
        border: "1px solid " + THEME.border,
        borderRadius: THEME.radius, boxShadow: THEME.shadow,
        marginTop: 4, zIndex: 250, overflow: "hidden",
        animation: "la3ib-fadeIn 0.15s ease"
      }
    },
      /* Player header */
      React.createElement("div", {
        style: {
          display: "flex", alignItems: "center", gap: 8,
          padding: "10px 14px", borderBottom: "1px solid " + THEME.border,
          background: THEME.bgSurface
        }
      },
        React.createElement(Avatar, { name: props.playerName, size: 24 }),
        React.createElement("span", { style: { fontSize: 13, fontWeight: 600, color: THEME.text } }, props.playerName)
      ),
      /* Menu items */
      menuItems.map(function(item, idx) {
        var isSep = idx === 3;
        return React.createElement("div", { key: idx },
          isSep && React.createElement("div", { style: { height: 1, background: THEME.border, margin: "4px 0" } }),
          React.createElement("button", {
            onClick: item.action,
            style: {
              display: "flex", alignItems: "center", gap: 10,
              width: "100%", padding: "9px 14px",
              background: "transparent", border: "none",
              color: item.color, fontSize: 13, fontWeight: 500,
              cursor: "pointer", fontFamily: "inherit",
              textAlign: "left", transition: "background 0.1s"
            }
          },
            React.createElement(item.icon, { size: 15, color: item.color }),
            item.label
          )
        );
      })
    ),

    /* Click outside to close */
    open && React.createElement("div", {
      style: { position: "fixed", top: 0, left: 0, right: 0, bottom: 0, zIndex: 249 },
      onClick: function() { setOpen(false); }
    }),

    /* Report Modal */
    React.createElement(ReportModal, {
      show: report,
      playerName: props.playerName,
      playerRating: props.playerRating,
      onClose: function() { setReport(false); }
    }),

    /* Block Confirm Modal */
    React.createElement(BlockConfirmModal, {
      show: block,
      playerName: props.playerName,
      onBlock: props.onBlock,
      onClose: function() { setBlock(false); }
    })
  );
}

/* ---- BLOCKED USERS MANAGER ---- */
function BlockedUsersScreen(props) {
  var resp = useResponsive();
  var blockedList = usePersist("blocked_users", [
    { name: "ToxicPlayer99", blockedDate: "2 days ago" },
    { name: "SpamBot3000", blockedDate: "1 week ago" }
  ]);
  var blocked = blockedList[0]; var setBlocked = blockedList[1];

  var handleUnblock = function(name) {
    setBlocked(blocked.filter(function(b) { return b.name !== name; }));
  };

  return React.createElement("div", null,
    React.createElement(SectionHeader, { title: "Blocked Users" }),
    React.createElement("p", { style: { color: THEME.textDim, fontSize: 13, marginBottom: 20 } },
      "Blocked players cannot send you messages, friend requests, game invites, or be matched with you."
    ),
    blocked.length === 0
      ? React.createElement(Card, { style: { textAlign: "center", padding: 40 } },
          React.createElement(IconShield, { size: 40, color: THEME.green }),
          React.createElement("h3", { style: { margin: "12px 0 4px", color: THEME.text } }, "No Blocked Users"),
          React.createElement("p", { style: { margin: 0, color: THEME.textDim, fontSize: 13 } }, "Your block list is empty")
        )
      : React.createElement(Card, { padding: 0, style: { overflow: "hidden" } },
          blocked.map(function(user, idx) {
            return React.createElement("div", {
              key: idx,
              style: {
                display: "flex", alignItems: "center", gap: 12,
                padding: "14px 16px",
                borderBottom: idx < blocked.length - 1 ? "1px solid " + THEME.border : "none"
              }
            },
              React.createElement(Avatar, { name: user.name, size: 36 }),
              React.createElement("div", { style: { flex: 1, minWidth: 0 } },
                React.createElement("div", { style: { fontWeight: 600, fontSize: 14, color: THEME.text } }, user.name),
                React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, "Blocked " + user.blockedDate)
              ),
              React.createElement(Button, {
                variant: "secondary", size: "sm",
                onClick: function() { SoundManager.play("click"); handleUnblock(user.name); }
              }, "Unblock")
            );
          })
        ),

    React.createElement("div", { style: { marginTop: 20 } },
      React.createElement(Button, { variant: "secondary", onClick: props.onBack }, "Back to Settings")
    )
  );
}

/* ============================================ */
/*  LOBBY & MATCHMAKING SYSTEM                  */
/* ============================================ */

/* Generate a random room code */
function generateRoomCode() {
  var chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  var code = "";
  var i = 0;
  while (i < 6) {
    code = code + chars.charAt(Math.floor(Math.random() * chars.length));
    i++;
  }
  return code;
}

/* Simulated player names for matchmaking demo */
var BOT_NAMES = [
  "KingOfTarneeb", "CardMaster99", "TarneebPro", "AhwaChamp",
  "DakkakElKart", "ShadyCards", "TrumpKing", "KabootMaster",
  "BluffWizard", "CardShark2024", "LuckyAce", "SpadeQueen",
  "DoubleDown", "TrickHunter", "BidBoss", "TableKing"
];

function getRandomBotName() {
  return BOT_NAMES[Math.floor(Math.random() * BOT_NAMES.length)];
}

/* Icon components for lobby */
function IconSearch(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("circle", { cx: 11, cy: 11, r: 8 }),
    React.createElement("line", { x1: 21, y1: 21, x2: 16.65, y2: 16.65 })
  );
}

function IconUsers(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("path", { d: "M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" }),
    React.createElement("circle", { cx: 9, cy: 7, r: 4 }),
    React.createElement("path", { d: "M23 21v-2a4 4 0 00-3-3.87" }),
    React.createElement("path", { d: "M16 3.13a4 4 0 010 7.75" })
  );
}

function IconCopy(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("rect", { x: 9, y: 9, width: 13, height: 13, rx: 2 }),
    React.createElement("path", { d: "M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" })
  );
}

function IconClock(props) {
  return React.createElement("svg", { width: props.size || 18, height: props.size || 18, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("circle", { cx: 12, cy: 12, r: 10 }),
    React.createElement("polyline", { points: "12 6 12 12 16 14" })
  );
}

function IconBot(props) {
  return React.createElement("svg", { width: props.size || 20, height: props.size || 20, viewBox: "0 0 24 24", fill: "none", stroke: props.color || THEME.textDim, strokeWidth: 2, strokeLinecap: "round" },
    React.createElement("rect", { x: 3, y: 8, width: 18, height: 12, rx: 2 }),
    React.createElement("circle", { cx: 9, cy: 14, r: 2 }),
    React.createElement("circle", { cx: 15, cy: 14, r: 2 }),
    React.createElement("line", { x1: 12, y1: 4, x2: 12, y2: 8 }),
    React.createElement("circle", { cx: 12, cy: 3, r: 1 })
  );
}

/* ---- GAME MODE SELECTION SCREEN ---- */
function GameModeScreen(props) {
  var resp = useResponsive();
  var gameId = props.gameId || "tarneeb";
  var gameName = gameId === "tarneeb" ? "Tarneeb" : gameId === "estimation" ? "Estimation" : "Game";

  var modes = [
    {
      id: "quickmatch",
      title: "Quick Match",
      desc: "Find opponents automatically. Get matched with players of similar skill level.",
      icon: IconSearch,
      color: THEME.accent,
      players: "4 Players",
      time: "~30 sec wait"
    },
    {
      id: "create",
      title: "Create Private Room",
      desc: "Create a room and share the code with friends to join.",
      icon: IconUsers,
      color: THEME.green,
      players: "Invite Friends",
      time: "You host"
    },
    {
      id: "join",
      title: "Join Room",
      desc: "Enter a room code from a friend to join their game.",
      icon: IconCards,
      color: THEME.blue,
      players: "Enter Code",
      time: "Join friend"
    },
    {
      id: "ai",
      title: "Play vs AI",
      desc: "Practice against computer opponents. Choose your difficulty level.",
      icon: IconBot,
      color: "#9050d0",
      players: "You + 3 AI",
      time: "Instant start"
    }
  ];

  return React.createElement("div", null,
    /* Back + Header */
    React.createElement("div", {
      style: { display: "flex", alignItems: "center", gap: 12, marginBottom: 24 }
    },
      React.createElement("button", {
        onClick: props.onBack,
        style: {
          display: "flex", alignItems: "center", gap: 6,
          background: THEME.bgCard, border: "1px solid " + THEME.border,
          borderRadius: THEME.radiusSm, padding: "8px 16px",
          color: THEME.accent, fontSize: 14, fontWeight: 600,
          cursor: "pointer", fontFamily: "inherit"
        }
      },
        React.createElement(IconChevron, { direction: "left", color: THEME.accent }),
        "Back"
      ),
      React.createElement("div", null,
        React.createElement("h2", { style: { margin: 0, fontSize: 22, fontWeight: 700, color: THEME.text } }, gameName),
        React.createElement("p", { style: { margin: 0, color: THEME.textDim, fontSize: 13 } }, "Choose how you want to play")
      )
    ),

    /* Mode Cards */
    React.createElement(ResponsiveGrid, {
      cols: { mobile: 1, tablet: 2, desktop: 2, desktopLg: 4 },
      gap: 16
    },
      modes.map(function(mode) {
        return React.createElement(Card, {
          key: mode.id,
          style: {
            cursor: "pointer",
            position: "relative",
            overflow: "hidden",
            padding: 24
          },
          onClick: function() { props.onSelectMode(mode.id); }
        },
          React.createElement("div", {
            style: {
              position: "absolute", top: 0, left: 0, right: 0, height: 4,
              background: mode.color
            }
          }),
          React.createElement("div", {
            style: {
              width: 52, height: 52, borderRadius: 12,
              background: mode.color + "18",
              display: "flex", alignItems: "center", justifyContent: "center",
              marginBottom: 16
            }
          },
            React.createElement(mode.icon, { size: 24, color: mode.color })
          ),
          React.createElement("h3", {
            style: { margin: "0 0 8px", fontSize: 17, fontWeight: 700, color: THEME.text }
          }, mode.title),
          React.createElement("p", {
            style: { margin: "0 0 16px", fontSize: 13, color: THEME.textDim, lineHeight: 1.5 }
          }, mode.desc),
          React.createElement("div", {
            style: { display: "flex", justifyContent: "space-between", alignItems: "center" }
          },
            React.createElement(Badge, { color: "dim" }, mode.players),
            React.createElement("span", { style: { fontSize: 12, color: THEME.textMuted } }, mode.time)
          )
        );
      })
    ),

    /* Recent rooms */
    React.createElement("div", { style: { marginTop: 32 } },
      React.createElement(SectionHeader, { title: "Online Now" }),
      React.createElement(Card, { padding: 16 },
        React.createElement("div", {
          style: { display: "flex", justifyContent: "space-around", textAlign: "center" }
        },
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 28, fontWeight: 800, color: THEME.accent } }, "847"),
            React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, "Players Online")
          ),
          React.createElement("div", { style: { width: 1, background: THEME.border } }),
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 28, fontWeight: 800, color: THEME.green } }, "214"),
            React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, "Active Games")
          ),
          React.createElement("div", { style: { width: 1, background: THEME.border } }),
          React.createElement("div", null,
            React.createElement("div", { style: { fontSize: 28, fontWeight: 800, color: THEME.blue } }, "~25s"),
            React.createElement("div", { style: { fontSize: 12, color: THEME.textDim } }, "Avg. Wait Time")
          )
        )
      )
    )
  );
}

/* ---- MATCHMAKING QUEUE SCREEN ---- */
function MatchmakingScreen(props) {
  var resp = useResponsive();
  var elapsed = useState(0); var time = elapsed[0]; var setTime = elapsed[1];
  var dots = useState(0); var dotCount = dots[0]; var setDots = dots[1];
  var found = useState(false); var matchFound = found[0]; var setFound = found[1];

  useEffect(function() {
    var timer = setInterval(function() {
      setTime(function(t) { return t + 1; });
      setDots(function(d) { return (d + 1) % 4; });
    }, 1000);
    return function() { clearInterval(timer); };
  }, []);

  /* Simulate finding a match after 3-6 seconds */
  useEffect(function() {
    var delay = 3000 + Math.floor(Math.random() * 3000);
    var matchTimer = setTimeout(function() {
      setFound(true);
      setTimeout(function() {
        props.onMatchFound({
          roomCode: generateRoomCode(),
          players: [
            { name: props.username || "You", slot: "south", isYou: true },
            { name: getRandomBotName(), slot: "west", isYou: false },
            { name: getRandomBotName(), slot: "north", isYou: false },
            { name: getRandomBotName(), slot: "east", isYou: false }
          ]
        });
      }, 1500);
    }, delay);
    return function() { clearTimeout(matchTimer); };
  }, []);

  var dotStr = "";
  var d = 0;
  while (d < dotCount) { dotStr = dotStr + "."; d++; }

  var minutes = Math.floor(time / 60);
  var seconds = time % 60;
  var timeStr = (minutes > 0 ? minutes + ":" : "") + (seconds < 10 && minutes > 0 ? "0" : "") + seconds + "s";

  return React.createElement("div", {
    style: { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: resp.isDesktop ? 500 : 400, textAlign: "center" }
  },
    /* Animated searching indicator */
    React.createElement("div", {
      style: {
        width: 100, height: 100, borderRadius: "50%",
        border: matchFound ? "4px solid " + THEME.green : "4px solid " + THEME.border,
        borderTopColor: matchFound ? THEME.green : THEME.accent,
        animation: matchFound ? "none" : "la3ib-spin 1s linear infinite",
        display: "flex", alignItems: "center", justifyContent: "center",
        marginBottom: 24,
        background: matchFound ? THEME.green + "15" : "transparent",
        transition: "all 0.3s ease"
      }
    },
      matchFound
        ? React.createElement("span", { style: { fontSize: 36, color: THEME.green } }, "\u2713")
        : React.createElement(IconSearch, { size: 36, color: THEME.accent })
    ),

    React.createElement("h2", {
      style: { margin: "0 0 8px", fontSize: 24, fontWeight: 700, color: THEME.text }
    }, matchFound ? "Match Found!" : "Finding Opponents" + dotStr),

    React.createElement("p", {
      style: { margin: "0 0 24px", color: THEME.textDim, fontSize: 14 }
    }, matchFound ? "Preparing your game..." : "Looking for players near your skill level"),

    !matchFound && React.createElement("div", {
      style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 32 }
    },
      React.createElement(IconClock, { size: 16, color: THEME.textMuted }),
      React.createElement("span", { style: { color: THEME.textMuted, fontSize: 14 } }, "Searching for " + timeStr)
    ),

    /* Player slots filling in */
    React.createElement(Card, {
      style: { width: "100%", maxWidth: 400, padding: 20 }
    },
      React.createElement("div", {
        style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }
      },
        ["South (You)", "West", "North", "East"].map(function(pos, idx) {
          var isFilled = idx === 0 || (matchFound && idx <= 3) || (!matchFound && time > idx * 1.5 && idx <= Math.min(time, 3));
          var playerName = idx === 0 ? (props.username || "You") : (isFilled ? getRandomBotName() : "Searching...");
          return React.createElement("div", {
            key: pos,
            style: {
              display: "flex", alignItems: "center", gap: 10,
              padding: "10px 12px",
              background: isFilled ? THEME.bgSurface : "transparent",
              borderRadius: THEME.radiusSm,
              border: "1px solid " + (isFilled ? THEME.border : THEME.border + "66"),
              opacity: isFilled ? 1 : 0.5
            }
          },
            isFilled
              ? React.createElement(Avatar, { name: playerName, size: 28 })
              : React.createElement("div", {
                  style: {
                    width: 28, height: 28, borderRadius: "50%",
                    border: "2px dashed " + THEME.textMuted, flexShrink: 0
                  }
                }),
            React.createElement("div", { style: { minWidth: 0 } },
              React.createElement("div", {
                style: {
                  fontSize: 13, fontWeight: 600,
                  color: isFilled ? THEME.text : THEME.textMuted,
                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
                }
              }, playerName),
              React.createElement("div", { style: { fontSize: 11, color: THEME.textMuted } }, pos)
            )
          );
        })
      )
    ),

    !matchFound && React.createElement(Button, {
      variant: "secondary",
      onClick: props.onCancel,
      style: { marginTop: 24 }
    }, "Cancel"),

    /* CSS animation for spinner - inject via style tag */
    React.createElement("style", null,
      "@keyframes la3ib-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }"
    )
  );
}

/* ---- JOIN ROOM SCREEN ---- */
function JoinRoomScreen(props) {
  var resp = useResponsive();
  var codeState = useState(""); var code = codeState[0]; var setCode = codeState[1];
  var errorState = useState(""); var error = errorState[0]; var setError = errorState[1];
  var loading = useState(false); var isLoading = loading[0]; var setLoading = loading[1];

  var handleJoin = function() {
    if (code.length < 4) {
      setError("Please enter a valid room code");
      return;
    }
    setLoading(true);
    setError("");
    /* Simulate room lookup */
    setTimeout(function() {
      setLoading(false);
      /* For demo, always succeed */
      props.onJoinRoom({
        roomCode: code.toUpperCase(),
        players: [
          { name: "RoomHost", slot: "south", isYou: false },
          { name: props.username || "You", slot: "west", isYou: true },
          { name: null, slot: "north", isYou: false },
          { name: null, slot: "east", isYou: false }
        ]
      });
    }, 1500);
  };

  return React.createElement("div", {
    style: {
      display: "flex", flexDirection: "column", alignItems: "center",
      justifyContent: "center", minHeight: resp.isDesktop ? 400 : 300
    }
  },
    React.createElement("div", {
      style: {
        width: 64, height: 64, borderRadius: 16,
        background: THEME.blue + "18",
        display: "flex", alignItems: "center", justifyContent: "center",
        marginBottom: 24
      }
    },
      React.createElement(IconCards, { size: 32, color: THEME.blue })
    ),
    React.createElement("h2", {
      style: { margin: "0 0 8px", fontSize: 22, fontWeight: 700, color: THEME.text }
    }, "Join Room"),
    React.createElement("p", {
      style: { margin: "0 0 24px", color: THEME.textDim, fontSize: 14 }
    }, "Enter the room code shared by your friend"),

    React.createElement("div", { style: { width: "100%", maxWidth: 340 } },
      React.createElement("input", {
        type: "text",
        value: code,
        onChange: function(e) { setCode(e.target.value.toUpperCase()); setError(""); },
        placeholder: "Enter room code",
        maxLength: 8,
        style: {
          width: "100%", padding: "16px 20px",
          background: THEME.bgSurface, border: "2px solid " + (error ? THEME.red : THEME.border),
          borderRadius: THEME.radius, color: THEME.text,
          fontSize: 24, fontWeight: 700, textAlign: "center",
          letterSpacing: "6px", outline: "none",
          fontFamily: "inherit", boxSizing: "border-box",
          textTransform: "uppercase"
        }
      }),
      error && React.createElement("div", {
        style: { color: THEME.red, fontSize: 13, marginTop: 8, textAlign: "center" }
      }, error),
      React.createElement("div", { style: { display: "flex", gap: 12, marginTop: 20 } },
        React.createElement(Button, {
          variant: "secondary",
          onClick: props.onBack,
          style: { flex: 1 }
        }, "Back"),
        React.createElement(Button, {
          variant: "primary",
          onClick: handleJoin,
          disabled: isLoading || code.length < 4,
          style: { flex: 2 }
        }, isLoading ? "Joining..." : "Join Game")
      )
    )
  );
}

/* ---- AI DIFFICULTY SELECTION ---- */
function AIDifficultyScreen(props) {
  var resp = useResponsive();

  var difficulties = [
    { id: "easy", label: "Easy", desc: "Relaxed play. Great for learning.", color: THEME.green, stars: 1 },
    { id: "medium", label: "Medium", desc: "Balanced challenge.", color: THEME.accent, stars: 2 },
    { id: "hard", label: "Hard", desc: "Competitive AI.", color: THEME.red, stars: 3 }
  ];

  return React.createElement("div", {
    style: { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: resp.isDesktop ? 400 : 300 }
  },
    React.createElement("div", {
      style: { width: 56, height: 56, borderRadius: 14, background: "#9050d0" + "18", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }
    },
      React.createElement(IconBot, { size: 28, color: "#9050d0" })
    ),
    React.createElement("h2", { style: { margin: "0 0 4px", fontSize: 22, fontWeight: 700, color: THEME.text } }, "Choose Difficulty"),
    React.createElement("p", { style: { margin: "0 0 24px", color: THEME.textDim, fontSize: 13 } }, "Select AI opponent difficulty"),

    React.createElement(ResponsiveGrid, {
      cols: { mobile: 1, tablet: 3, desktop: 3 },
      gap: 12,
      style: { width: "100%", maxWidth: 640 }
    },
      difficulties.map(function(diff) {
        var starElements = [];
        var si = 0;
        while (si < 3) {
          starElements.push(React.createElement(IconStar, { key: si, filled: si < diff.stars, size: 16 }));
          si++;
        }
        return React.createElement(Card, {
          key: diff.id,
          style: { cursor: "pointer", textAlign: "center", padding: 20, position: "relative", overflow: "hidden" },
          onClick: function() { props.onSelectDifficulty(diff.id); }
        },
          React.createElement("div", { style: { position: "absolute", top: 0, left: 0, right: 0, height: 4, background: diff.color } }),
          React.createElement("div", { style: { display: "flex", justifyContent: "center", gap: 4, marginBottom: 8 } }, starElements),
          React.createElement("h3", { style: { margin: "0 0 6px", fontSize: 16, fontWeight: 700, color: diff.color } }, diff.label),
          React.createElement("p", { style: { margin: 0, fontSize: 12, color: THEME.textDim, lineHeight: 1.4 } }, diff.desc)
        );
      })
    ),

    React.createElement(Button, { variant: "secondary", onClick: props.onBack, style: { marginTop: 20 } }, "Back")
  );
}

/* ---- WAITING ROOM (for private rooms) ---- */
function WaitingRoom(props) {
  var resp = useResponsive();
  var room = props.room || {};
  var players = room.players || [];
  var roomCode = room.roomCode || "------";
  var copied = useState(false); var isCopied = copied[0]; var setCopied = copied[1];
  var countdown = useState(null); var cdVal = countdown[0]; var setCdVal = countdown[1];

  /* Check if room is full (4 players) */
  var filledCount = 0;
  var pi = 0;
  while (pi < players.length) {
    if (players[pi] && players[pi].name) filledCount++;
    pi++;
  }

  /* Simulate players joining for private rooms */
  var simPlayers = useState(players);
  var currentPlayers = simPlayers[0]; var setCurrentPlayers = simPlayers[1];

  useEffect(function() {
    /* Gradually fill empty slots */
    var fillTimer = setInterval(function() {
      setCurrentPlayers(function(prev) {
        var hasEmpty = false;
        var next = prev.map(function(p) {
          if (!hasEmpty && p && !p.name && !p.isYou) {
            hasEmpty = true;
            return Object.assign({}, p, { name: getRandomBotName() });
          }
          return p;
        });
        /* Check if all slots filled */
        var allFilled = true;
        var ci = 0;
        while (ci < next.length) {
          if (!next[ci] || !next[ci].name) allFilled = false;
          ci++;
        }
        if (allFilled) {
          clearInterval(fillTimer);
          setCdVal(5);
        }
        return next;
      });
    }, 2000 + Math.floor(Math.random() * 3000));
    return function() { clearInterval(fillTimer); };
  }, []);

  /* Countdown when room is full */
  useEffect(function() {
    if (cdVal === null) return;
    if (cdVal <= 0) {
      props.onStartGame(currentPlayers);
      return;
    }
    var cdTimer = setTimeout(function() { setCdVal(cdVal - 1); }, 1000);
    return function() { clearTimeout(cdTimer); };
  }, [cdVal]);

  var handleCopy = function() {
    if (navigator.clipboard) {
      navigator.clipboard.writeText(roomCode);
    }
    setCopied(true);
    setTimeout(function() { setCopied(false); }, 2000);
  };

  var slotLabels = ["South", "West", "North", "East"];

  return React.createElement("div", {
    style: {
      display: "flex", flexDirection: "column", alignItems: "center",
      justifyContent: "center", minHeight: resp.isDesktop ? 500 : 400
    }
  },
    React.createElement("h2", {
      style: { margin: "0 0 8px", fontSize: 22, fontWeight: 700, color: THEME.text }
    }, cdVal !== null ? "Game Starting in " + cdVal + "..." : "Waiting for Players"),
    React.createElement("p", {
      style: { margin: "0 0 24px", color: THEME.textDim, fontSize: 14 }
    }, "Share the room code with your friends"),

    /* Room Code Display */
    React.createElement(Card, {
      style: {
        textAlign: "center", padding: 24, marginBottom: 24,
        border: "2px solid " + THEME.accent + "44"
      }
    },
      React.createElement("div", { style: { color: THEME.textDim, fontSize: 12, marginBottom: 8, textTransform: "uppercase", fontWeight: 600 } }, "Room Code"),
      React.createElement("div", {
        style: {
          fontSize: 36, fontWeight: 800, color: THEME.accent,
          letterSpacing: "8px", marginBottom: 12, fontFamily: "monospace"
        }
      }, roomCode),
      React.createElement(Button, {
        variant: "secondary",
        size: "sm",
        onClick: handleCopy
      },
        React.createElement(IconCopy, { size: 14, color: isCopied ? THEME.green : THEME.textDim }),
        isCopied ? "Copied!" : "Copy Code"
      )
    ),

    /* Player Slots */
    React.createElement(Card, {
      style: { width: "100%", maxWidth: 480, padding: 20 }
    },
      React.createElement("div", {
        style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }
      },
        currentPlayers.map(function(player, idx) {
          var isFilled = player && player.name;
          var isYou = player && player.isYou;
          return React.createElement("div", {
            key: idx,
            style: {
              display: "flex", alignItems: "center", gap: 10,
              padding: "12px 14px",
              background: isFilled ? THEME.bgSurface : "transparent",
              borderRadius: THEME.radiusSm,
              border: isYou ? "2px solid " + THEME.accent + "44" : "1px solid " + (isFilled ? THEME.border : THEME.border + "44"),
              opacity: isFilled ? 1 : 0.5
            }
          },
            isFilled
              ? React.createElement(Avatar, { name: player.name, size: 32 })
              : React.createElement("div", {
                  style: {
                    width: 32, height: 32, borderRadius: "50%",
                    border: "2px dashed " + THEME.textMuted,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    flexShrink: 0
                  }
                },
                  React.createElement("span", { style: { color: THEME.textMuted, fontSize: 16 } }, "?")
                ),
            React.createElement("div", { style: { minWidth: 0, flex: 1 } },
              React.createElement("div", {
                style: {
                  fontSize: 14, fontWeight: 600,
                  color: isFilled ? THEME.text : THEME.textMuted,
                  overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
                }
              }, isFilled ? player.name + (isYou ? " (You)" : "") : "Waiting..."),
              React.createElement("div", { style: { fontSize: 11, color: THEME.textMuted } }, slotLabels[idx])
            ),
            isFilled && React.createElement("div", {
              style: {
                width: 8, height: 8, borderRadius: "50%",
                background: THEME.green, flexShrink: 0
              }
            })
          );
        })
      )
    ),

    React.createElement("div", { style: { display: "flex", gap: 12, marginTop: 24 } },
      React.createElement(Button, {
        variant: "secondary",
        onClick: props.onLeave
      }, "Leave Room"),
      cdVal === null && filledCount >= 2 && React.createElement(Button, {
        variant: "primary",
        onClick: function() { props.onStartGame(currentPlayers); }
      }, "Start with AI Fill")
    )
  );
}

/* ---- GAME SETTINGS SCREEN (shared for all modes) ---- */
function GameSettingsScreen(props) {
  var resp = useResponsive();
  var gameStyle = useState("egyptian"); var style = gameStyle[0]; var setStyle = gameStyle[1];
  var targetScore = useState(41); var target = targetScore[0]; var setTarget = targetScore[1];

  var modeLabels = { quickmatch: "Quick Match", create: "Create Room", join: "Join Room", ai: "Play vs AI" };

  var gameModes = [
    { id: "egyptian", label: "Egyptian", desc: "Bid tricks + suit. Kabbout, Sans, Dakak rules.", color: THEME.accent },
    { id: "syrian", label: "Syrian", desc: "Trump decided by last dealt card. Classic bidding.", color: "#4a90d9" },
    { id: "classic", label: "Classic", desc: "Bid tricks only. Winner picks trump after.", color: THEME.green }
  ];

  var targets = [
    { val: 31, label: "31" },
    { val: 41, label: "41" },
    { val: 61, label: "61" }
  ];

  return React.createElement("div", {
    style: { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", minHeight: resp.isDesktop ? 400 : 300 }
  },
    React.createElement("div", {
      style: { width: 56, height: 56, borderRadius: 14, background: THEME.accent + "18", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 16 }
    },
      React.createElement(IconCards, { size: 28, color: THEME.accent })
    ),
    React.createElement("h2", { style: { margin: "0 0 4px", fontSize: 22, fontWeight: 700, color: THEME.text } }, "Game Settings"),
    React.createElement("p", { style: { margin: "0 0 24px", color: THEME.textDim, fontSize: 13 } },
      (modeLabels[props.mode] || "Tarneeb") + " - Choose your game style"
    ),

    /* Game Style */
    React.createElement("div", { style: { width: "100%", maxWidth: 640, marginBottom: 20 } },
      React.createElement("div", { style: { fontSize: 11, color: THEME.textMuted, marginBottom: 8, textTransform: "uppercase", letterSpacing: 1, fontWeight: 600 } }, "Game Style"),
      React.createElement("div", { style: { display: "flex", gap: 8 } },
        gameModes.map(function(gm) {
          var isActive = style === gm.id;
          return React.createElement("button", {
            key: gm.id,
            onClick: function() { setStyle(gm.id); },
            style: {
              flex: 1, padding: "14px 8px", borderRadius: THEME.radius,
              background: isActive ? gm.color + "22" : THEME.bgCard,
              border: isActive ? "2px solid " + gm.color : "1px solid " + THEME.border,
              cursor: "pointer", fontFamily: "inherit", textAlign: "center"
            }
          },
            React.createElement("div", { style: { fontSize: 15, fontWeight: 700, color: isActive ? gm.color : THEME.text, marginBottom: 4 } }, gm.label),
            React.createElement("div", { style: { fontSize: 10, color: THEME.textDim, lineHeight: 1.4 } }, gm.desc)
          );
        })
      )
    ),

    /* Target Score */
    React.createElement("div", { style: { width: "100%", maxWidth: 640, marginBottom: 24 } },
      React.createElement("div", { style: { fontSize: 11, color: THEME.textMuted, marginBottom: 8, textTransform: "uppercase", letterSpacing: 1, fontWeight: 600 } }, "Target Score"),
      React.createElement("div", { style: { display: "flex", gap: 8 } },
        targets.map(function(t) {
          var isActive = target === t.val;
          return React.createElement("button", {
            key: t.val,
            onClick: function() { setTarget(t.val); },
            style: {
              flex: 1, padding: "12px", borderRadius: THEME.radius,
              background: isActive ? THEME.accent + "22" : THEME.bgCard,
              border: isActive ? "2px solid " + THEME.accent : "1px solid " + THEME.border,
              cursor: "pointer", fontFamily: "inherit",
              fontSize: 20, fontWeight: 800, color: isActive ? THEME.accent : THEME.textDim
            }
          }, t.label);
        })
      )
    ),

    /* Continue + Back */
    React.createElement("div", { style: { display: "flex", gap: 12 } },
      React.createElement(Button, { variant: "secondary", onClick: props.onBack }, "Back"),
      React.createElement(Button, {
        variant: "primary",
        onClick: function() { props.onContinue(style, target); }
      }, "Continue")
    )
  );
}

/* ---- LOBBY CONTROLLER (manages sub-screens) ---- */
function LobbyScreen(props) {
  var resp = useResponsive();
  var phase = useState("modes");
  var lobbyPhase = phase[0]; var setLobbyPhase = phase[1];
  var roomData = useState(null); var room = roomData[0]; var setRoom = roomData[1];
  /* Game settings shared across all modes */
  var pendingMode = useState(null); var pMode = pendingMode[0]; var setPMode = pendingMode[1];
  var gameSettings = useState({ style: "egyptian", target: 41 });
  var settings = gameSettings[0]; var setSettings = gameSettings[1];

  var handleSelectMode = function(mode) {
    /* Store the selected mode and show settings first */
    setPMode(mode);
    setLobbyPhase("settings");
  };

  var handleSettingsContinue = function(style, target) {
    setSettings({ style: style, target: target });
    /* Now proceed to the actual mode */
    if (pMode === "quickmatch") {
      setLobbyPhase("matchmaking");
    } else if (pMode === "create") {
      setRoom({
        roomCode: generateRoomCode(),
        players: [
          { name: props.username || "You", slot: "south", isYou: true },
          { name: null, slot: "west", isYou: false },
          { name: null, slot: "north", isYou: false },
          { name: null, slot: "east", isYou: false }
        ]
      });
      setLobbyPhase("waiting");
    } else if (pMode === "join") {
      setLobbyPhase("join");
    } else if (pMode === "ai") {
      setLobbyPhase("ai");
    }
  };

  var handleMatchFound = function(matchData) {
    setRoom(matchData);
    setLobbyPhase("waiting");
  };

  var handleJoinRoom = function(joinData) {
    setRoom(joinData);
    setLobbyPhase("waiting");
  };

  var handleStartGame = function(finalPlayers) {
    props.onStartGame(finalPlayers);
  };

  var handleSelectDifficulty = function(difficulty, gameMode, targetScore) {
    var mode = gameMode || settings.style || "egyptian";
    var target = targetScore || settings.target || 41;
    /* Connect to backend: join queue then fill with AI */
    if (window.La3ibSocket && window.La3ibSocket.isConnected()) {
      window.La3ibSocket.joinQueue(mode, target, function(resp) {
        if (resp && resp.error) {
          console.error("Join queue error:", resp.error);
          return;
        }
        /* Fill remaining seats with AI */
        setTimeout(function() {
          window.La3ibSocket.fillAI(difficulty, function(aiResp) {
            if (aiResp && aiResp.error) {
              console.error("Fill AI error:", aiResp.error);
            }
          });
        }, 200);
      });
    }
    /* Start game UI immediately */
    props.onStartGame([
      { name: props.username || "You", slot: "south", isYou: true },
      { name: "AI (" + difficulty + ")", slot: "west", isYou: false, isAI: true, difficulty: difficulty },
      { name: "AI (" + difficulty + ")", slot: "north", isYou: false, isAI: true, difficulty: difficulty },
      { name: "AI (" + difficulty + ")", slot: "east", isYou: false, isAI: true, difficulty: difficulty }
    ]);
  };

  var content = null;

  if (lobbyPhase === "modes") {
    content = React.createElement(GameModeScreen, {
      gameId: props.gameId,
      onSelectMode: handleSelectMode,
      onBack: props.onBack
    });
  } else if (lobbyPhase === "settings") {
    /* Game Settings Screen (shared for all modes) */
    content = React.createElement(GameSettingsScreen, {
      mode: pMode,
      onContinue: handleSettingsContinue,
      onBack: function() { setLobbyPhase("modes"); }
    });
  } else if (lobbyPhase === "matchmaking") {
    content = React.createElement(MatchmakingScreen, {
      username: props.username,
      onMatchFound: handleMatchFound,
      onCancel: function() { setLobbyPhase("modes"); }
    });
  } else if (lobbyPhase === "join") {
    content = React.createElement(JoinRoomScreen, {
      username: props.username,
      onJoinRoom: handleJoinRoom,
      onBack: function() { setLobbyPhase("modes"); }
    });
  } else if (lobbyPhase === "ai") {
    content = React.createElement(AIDifficultyScreen, {
      onSelectDifficulty: handleSelectDifficulty,
      onBack: function() { setLobbyPhase("settings"); }
    });
  } else if (lobbyPhase === "waiting") {
    content = React.createElement(WaitingRoom, {
      room: room,
      onStartGame: handleStartGame,
      onLeave: function() { setLobbyPhase("modes"); setRoom(null); }
    });
  }

  return content;
}

/* ============================================ */
/*  TARNEEB GAME SCREEN                         */
/* ============================================ */

function PlayingCard(props) {
  var card = props.card || {};
  var suitColors = { hearts: THEME.red, diamonds: THEME.red, clubs: "#1a1a2e", spades: "#1a1a2e" };
  var suitSymbols = { hearts: "\u2665", diamonds: "\u2666", clubs: "\u2663", spades: "\u2660" };
  var color = suitColors[card.suit] || THEME.text;
  var symbol = suitSymbols[card.suit] || "";
  var w = props.width || 60;
  var h = w * 1.45;

  if (props.faceDown) {
    /* Scale the brand mark based on card width */
    var brandW = Math.max(w * 0.75, 20);
    var brandH = Math.max(w * 0.5, 14);
    return React.createElement("div", {
      style: {
        width: w, height: h, borderRadius: 6,
        background: "linear-gradient(145deg, #142850, #0d1a35)",
        border: "2px solid " + THEME.accent,
        display: "flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0,
        position: "relative",
        overflow: "hidden"
      }
    },
      /* Inner border with diagonal pattern */
      React.createElement("div", {
        style: {
          width: w - 8, height: h - 8, borderRadius: 3,
          border: "1px solid rgba(200,160,68,0.3)",
          display: "flex", flexDirection: "column",
          alignItems: "center", justifyContent: "center",
          background: "repeating-linear-gradient(45deg, transparent, transparent 3px, rgba(200,160,68,0.05) 3px, rgba(200,160,68,0.05) 6px)"
        }
      },
        /* La3ib brand: 3 suit symbols using basic SVG shapes */
        React.createElement("svg", {
          width: brandW, height: brandH,
          viewBox: "0 0 42 20",
          overflow: "visible"
        },
          /* Spade (blue) - left: triangle up + two circle lobes + stem */
          React.createElement("g", { transform: "translate(9, 10)" },
            React.createElement("polygon", { points: "0,-6 4,1 -4,1", fill: THEME.blue, opacity: 0.85 }),
            React.createElement("circle", { cx: -2, cy: 1, r: 2.2, fill: THEME.blue, opacity: 0.85 }),
            React.createElement("circle", { cx: 2, cy: 1, r: 2.2, fill: THEME.blue, opacity: 0.85 }),
            React.createElement("rect", { x: -0.7, y: 1, width: 1.4, height: 3.5, fill: THEME.blue, opacity: 0.85 })
          ),
          /* Heart (red) - center: two circles + triangle down */
          React.createElement("g", { transform: "translate(21, 10)" },
            React.createElement("circle", { cx: -2.5, cy: -2, r: 3, fill: THEME.red, opacity: 0.9 }),
            React.createElement("circle", { cx: 2.5, cy: -2, r: 3, fill: THEME.red, opacity: 0.9 }),
            React.createElement("polygon", { points: "-5.2,0 5.2,0 0,6", fill: THEME.red, opacity: 0.9 })
          ),
          /* Diamond (gold) - right: rotated square */
          React.createElement("g", { transform: "translate(33, 10)" },
            React.createElement("rect", { x: -4, y: -4, width: 8, height: 8, fill: THEME.accent, opacity: 0.85, transform: "rotate(45)" })
          )
        )
      )
    );
  }

  var cardHover = useState(false);
  var isCardHovered = cardHover[0]; var setCardHover = cardHover[1];

  return React.createElement("div", {
    style: Object.assign({
      width: w, height: h, borderRadius: 6,
      background: "#fff",
      border: props.selected ? "2px solid " + THEME.accent : isCardHovered && props.onClick ? "2px solid " + THEME.accentDim : "1px solid #ddd",
      padding: 4,
      cursor: props.onClick ? "pointer" : "default",
      transition: "all 0.2s cubic-bezier(0.23, 1, 0.32, 1)",
      transform: props.selected ? "translateY(-12px) scale(1.05)" : isCardHovered && props.onClick ? "translateY(-6px)" : "none",
      boxShadow: props.selected ? "0 8px 20px rgba(200,160,68,0.5)" : isCardHovered && props.onClick ? "0 4px 12px rgba(200,160,68,0.2)" : "0 1px 4px rgba(0,0,0,0.2)",
      flexShrink: 0,
      position: "relative"
    }, props.style || {}),
    onClick: props.onClick,
    onMouseEnter: props.onClick ? function() { setCardHover(true); } : undefined,
    onMouseLeave: props.onClick ? function() { setCardHover(false); } : undefined
  },
    React.createElement("div", { style: { fontSize: w * 0.22, fontWeight: 700, color: color, lineHeight: 1 } },
      card.rank || ""
    ),
    React.createElement("div", { style: { fontSize: w * 0.18, color: color } }, symbol),
    React.createElement("div", {
      style: {
        position: "absolute",
        top: "50%", left: "50%",
        transform: "translate(-50%,-50%)",
        fontSize: w * 0.4, color: color
      }
    }, symbol)
  );
}

function TarneebGame(props) {
  var resp = useResponsive();
  var selCard = useState(null); var sc = selCard[0]; var setSc = selCard[1];
  var bidAmount = useState(1); var bidVal = bidAmount[0]; var setBidVal = bidAmount[1];
  var bidSuit = useState("S"); var bidS = bidSuit[0]; var setBidS = bidSuit[1];

  /* Try to use live game state from socket, fall back to demo */
  var hasSocket = typeof window !== "undefined" && window.useGameState;
  var game = hasSocket ? window.useGameState() : null;
  var gs = game ? game.state : null;

  /* Card format converter: backend {s:'H',r:'A'} -> frontend {suit:'hearts',rank:'A'} */
  var suitNames = { S: "spades", H: "hearts", D: "diamonds", C: "clubs" };
  var suitShort = { spades: "S", hearts: "H", diamonds: "D", clubs: "C" };
  var suitSymbols = { S: "\u2660", H: "\u2665", D: "\u2666", C: "\u2663" };

  function toFrontCard(c) {
    if (!c) return null;
    if (c.suit) return c; /* already frontend format */
    return { rank: c.r, suit: suitNames[c.s] || c.s };
  }
  function toBackCard(c) {
    if (!c) return null;
    if (c.s) return c; /* already backend format */
    return { r: c.rank, s: suitShort[c.suit] || c.suit };
  }

  /* Determine game data - live or demo */
  var isLive = gs && gs.phase !== "idle" && gs.phase !== "waiting" && gs.myHand && gs.myHand.length > 0;
  var phase = gs ? gs.phase : "bid";
  if (phase === "idle" || phase === "waiting") phase = "bid";
  /* mySeat: try hook first, then global fallback, then default 0 */
  var mySeat = isLive ? gs.mySeat : 0;
  if (mySeat < 0 && window.la3ib_mySeat !== undefined) mySeat = window.la3ib_mySeat;
  if (mySeat < 0 && window.La3ibSocket) mySeat = window.La3ibSocket.getMySeat();
  if (mySeat < 0) mySeat = 0;
  var turn = isLive ? gs.turn : 0;
  var isMyTurn = isLive ? (turn === mySeat) : true;

  /* 10-second turn timer */
  var timerState = useState(10);
  var timer = timerState[0]; var setTimer = timerState[1];
  var timerKey = useState(0); var tKey = timerKey[0]; var setTKey = timerKey[1];

  useEffect(function() {
    /* Reset timer when turn changes */
    setTimer(10);
    setTKey(function(k) { return k + 1; });
  }, [turn, phase]);

  useEffect(function() {
    if (phase !== "bid" && phase !== "play") return;
    if (!isMyTurn) return;
    if (timer <= 0) {
      /* Auto-action when timer expires */
      if (phase === "bid" && game) {
        game.pass();
      } else if (phase === "play" && window.La3ibSocket && hand.length > 0) {
        var validCard = findValidCard();
        if (validCard) {
          window.La3ibSocket.playCard(toBackCard(validCard));
        }
      }
      return;
    }
    var interval = setTimeout(function() {
      setTimer(function(t) { return t - 1; });
    }, 1000);
    return function() { clearTimeout(interval); };
  }, [timer, isMyTurn, phase]);

  /* Hand counts per seat */
  var handCounts = isLive && gs.handCounts ? gs.handCounts : [13, 13, 13, 13];

  var posNames = ["South", "East", "North", "West"];

  /* Hand */
  var hand = [];
  if (isLive && gs.myHand && gs.myHand.length > 0) {
    var hi = 0;
    while (hi < gs.myHand.length) {
      hand.push(toFrontCard(gs.myHand[hi]));
      hi++;
    }
  }
  if (hand.length === 0) {
    hand = [
      { rank: "A", suit: "spades" }, { rank: "K", suit: "spades" },
      { rank: "J", suit: "hearts" }, { rank: "9", suit: "hearts" },
      { rank: "Q", suit: "diamonds" }, { rank: "7", suit: "diamonds" },
      { rank: "10", suit: "clubs" }, { rank: "8", suit: "clubs" },
      { rank: "5", suit: "clubs" }, { rank: "3", suit: "spades" },
      { rank: "6", suit: "diamonds" }, { rank: "4", suit: "hearts" },
      { rank: "2", suit: "clubs" }
    ];
  }

  /* Sort hand: alternate black-red suit groups, each sorted high to low */
  var rankOrder = { A: 14, K: 13, Q: 12, J: 11, "10": 10, "9": 9, "8": 8, "7": 7, "6": 6, "5": 5, "4": 4, "3": 3, "2": 2 };

  /* Build dynamic suit order to alternate colors */
  var hasS = hand.some(function(c) { return c.suit === "spades"; });
  var hasH = hand.some(function(c) { return c.suit === "hearts"; });
  var hasC = hand.some(function(c) { return c.suit === "clubs"; });
  var hasD = hand.some(function(c) { return c.suit === "diamonds"; });
  var blacks = [];
  var reds = [];
  if (hasS) blacks.push("spades");
  if (hasC) blacks.push("clubs");
  if (hasH) reds.push("hearts");
  if (hasD) reds.push("diamonds");
  /* Interleave: start with whichever color has more suits */
  var suitDisplayOrder = [];
  var bIdx = 0; var rIdx = 0;
  var startBlack = blacks.length >= reds.length;
  while (bIdx < blacks.length || rIdx < reds.length) {
    if (startBlack) {
      if (bIdx < blacks.length) suitDisplayOrder.push(blacks[bIdx++]);
      if (rIdx < reds.length) suitDisplayOrder.push(reds[rIdx++]);
    } else {
      if (rIdx < reds.length) suitDisplayOrder.push(reds[rIdx++]);
      if (bIdx < blacks.length) suitDisplayOrder.push(blacks[bIdx++]);
    }
  }
  var suitOrder = {};
  var si = 0;
  while (si < suitDisplayOrder.length) { suitOrder[suitDisplayOrder[si]] = si; si++; }

  hand = hand.slice().sort(function(a, b) {
    var suitDiff = (suitOrder[a.suit] !== undefined ? suitOrder[a.suit] : 9) - (suitOrder[b.suit] !== undefined ? suitOrder[b.suit] : 9);
    if (suitDiff !== 0) return suitDiff;
    return (rankOrder[b.rank] || 0) - (rankOrder[a.rank] || 0);
  });

  /* Trick cards: convert from backend format, position relative to mySeat */
  var trick = [null, null, null, null]; /* indexed by visual position: 0=bottom, 1=right, 2=top, 3=left */
  if (isLive && gs.trickCards) {
    var ti = 0;
    while (ti < gs.trickCards.length) {
      var tc = gs.trickCards[ti];
      if (tc && tc.card) {
        /* Map seat to visual position relative to mySeat */
        var visualPos = (tc.seat - mySeat + 4) % 4;
        trick[visualPos] = toFrontCard(tc.card);
      }
      ti++;
    }
  }

  /* Last completed trick */
  var lastTrick = useState(null); var lastTr = lastTrick[0]; var setLastTr = lastTrick[1];
  useEffect(function() {
    if (!window.La3ibSocket) return;
    var unsub = window.La3ibSocket.on("game:trick_complete", function(data) {
      /* data: { winner, cards, tricks } */
      if (data.cards) {
        var lt = [];
        var lti = 0;
        while (lti < data.cards.length) {
          var c = data.cards[lti];
          if (c && c.card) {
            lt.push({ seat: c.seat, card: toFrontCard(c.card), seatName: posNames[c.seat] || "?" });
          }
          lti++;
        }
        var winnerName = data.winner === mySeat ? "You" : posNames[data.winner] || "?";
        setLastTr({ cards: lt, winner: winnerName, winnerSeat: data.winner });
      }
    });
    return unsub;
  }, []);

  /* Bid history */
  var bidHist = [];
  if (isLive && gs.bidSeq) {
    var bi = 0;
    while (bi < gs.bidSeq.length) {
      var entry = gs.bidSeq[bi];
      var playerName = posNames[entry.seat] || "Player " + entry.seat;
      if (entry.seat === mySeat) playerName = "You";
      if (entry.action === "bid") {
        var displayBid = entry.tricks - 6; /* Convert 7-13 to 1-7 */
        var bidLabel = "";
        if (entry.tricks >= 13 && entry.suit === "N") {
          bidLabel = "KS (Kabbout Sans)";
        } else if (entry.tricks >= 13) {
          bidLabel = "Kabbout " + (suitSymbols[entry.suit] || entry.suit);
        } else if (entry.suit === "N") {
          bidLabel = displayBid + " Sans";
        } else {
          bidLabel = displayBid + " " + (suitSymbols[entry.suit] || entry.suit);
        }
        bidHist.push({ player: playerName, bid: bidLabel });
      } else if (entry.action === "double") {
        bidHist.push({ player: playerName, bid: "Double" });
      } else {
        bidHist.push({ player: playerName, bid: "Pass" });
      }
      bi++;
    }
  }

  /* Scores */
  var nsScore = isLive ? (gs.scores ? gs.scores[0] : 0) : 0;
  var ewScore = isLive ? (gs.scores ? gs.scores[1] : 0) : 0;
  var nsBid = isLive && gs.contract ? gs.contract.tricks : 0;
  var targetScore = isLive ? (gs.target || 41) : 41;

  /* Trump */
  var trumpSuit = null;
  var trumpDisplay = null;
  if (isLive && gs.trump) {
    trumpSuit = suitNames[gs.trump] || gs.trump;
    trumpDisplay = trumpSuit;
  } else if (isLive && gs.contract && gs.contract.suit) {
    if (gs.contract.suit === "N") {
      trumpSuit = "sans";
      trumpDisplay = "Sans (No Trump)";
    } else {
      trumpSuit = suitNames[gs.contract.suit] || gs.contract.suit;
      trumpDisplay = trumpSuit;
    }
  }

  /* Tricks won */
  var nsTricks = isLive ? (gs.tricks ? gs.tricks[0] : 0) : 0;
  var ewTricks = isLive ? (gs.tricks ? gs.tricks[1] : 0) : 0;

  /* Actions */
  var handleBid = function() {
    SoundManager.play("bid");
    if (game) {
      /* Convert display bid (1-7) to backend bid (7-13) */
      game.bid(bidVal + 6, bidS);
    }
  };
  var handlePass = function() {
    SoundManager.play("click");
    if (game) {
      game.pass();
    }
  };
  var handleKabbout = function(suit) {
    SoundManager.play("bid");
    if (game) {
      game.bid(13, suit);
    }
  };
  var playError = useState(null); var playErr = playError[0]; var setPlayErr = playError[1];

  var handlePlayCard = function() {
    if (sc === null || sc >= hand.length) return;
    var card = hand[sc];
    SoundManager.play("cardPlay");
    if (game) {
      var backCard = toBackCard(card);
      window.La3ibSocket.playCard(backCard, function(resp) {
        if (resp && resp.error) {
          setPlayErr(resp.error);
          setTimeout(function() { setPlayErr(null); }, 3000);
        }
      });
    }
    setSc(null);
  };
  var handleNextDeal = function() {
    if (game) game.nextDeal();
  };

  /* Find a valid card to auto-play (must follow led suit) */
  var findValidCard = function() {
    if (!hand || hand.length === 0) return null;
    /* Check if there's a led suit from trick cards */
    var ledSuit = null;
    if (isLive && gs.trickCards && gs.trickCards.length > 0) {
      var firstTrick = gs.trickCards[0];
      if (firstTrick && firstTrick.card) ledSuit = firstTrick.card.s;
      else if (firstTrick && firstTrick.s) ledSuit = firstTrick.s;
    }
    if (ledSuit) {
      var ledSuitFront = suitNames[ledSuit] || ledSuit;
      /* Find cards that follow suit */
      var following = [];
      var fi = 0;
      while (fi < hand.length) {
        if (hand[fi].suit === ledSuitFront) following.push(hand[fi]);
        fi++;
      }
      if (following.length > 0) return following[0];
    }
    return hand[0];
  };

  var cardW = resp.isMobile ? 46 : resp.isTablet ? 52 : 58;
  var tableH = resp.isMobile ? 250 : resp.isTablet ? 290 : 330;

  /* ── Bid Panel ── */
  var bidPanel = React.createElement(Card, {
    style: { padding: 16, marginBottom: resp.isDesktop ? 0 : 12, minWidth: resp.isDesktop ? 200 : undefined }
  },
    React.createElement("h4", { style: { margin: "0 0 12px", color: THEME.accent, fontSize: 14, fontWeight: 700 } }, "Bid History"),
    bidHist.length === 0 && React.createElement("div", { style: { color: THEME.textMuted, fontSize: 12, padding: "8px 0" } },
      isLive ? "Waiting for bids..." : "Demo mode"
    ),
    bidHist.map(function(b, i) {
      return React.createElement("div", {
        key: i,
        style: { display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px solid " + THEME.border, fontSize: 13 }
      },
        React.createElement("span", { style: { color: THEME.textDim } }, b.player),
        React.createElement("span", { style: { color: b.bid === "Pass" ? THEME.textMuted : THEME.accent, fontWeight: 600 } }, b.bid)
      );
    }),
    /* Bid controls - show during bid phase when it's my turn */
    (phase === "bid" && isMyTurn) && React.createElement("div", { style: { marginTop: 12 } },
      /* Bid number (1-7 Egyptian scale: 1=7tricks, 7=13tricks) */
      React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 8 } },
        React.createElement("button", {
          onClick: function() { if (bidVal > 1) setBidVal(bidVal - 1); },
          style: { width: 32, height: 32, borderRadius: "50%", background: THEME.bgSurface, border: "1px solid " + THEME.border, color: THEME.text, fontSize: 18, cursor: "pointer", fontFamily: "inherit" }
        }, "-"),
        React.createElement("div", { style: { textAlign: "center", minWidth: 44 } },
          React.createElement("div", { style: { fontSize: 22, fontWeight: 800, color: THEME.accent } }, bidVal),
          React.createElement("div", { style: { fontSize: 9, color: THEME.textMuted } }, (bidVal + 6) + " tricks")
        ),
        React.createElement("button", {
          onClick: function() { if (bidVal < 6) setBidVal(bidVal + 1); },
          style: { width: 32, height: 32, borderRadius: "50%", background: THEME.bgSurface, border: "1px solid " + THEME.border, color: THEME.text, fontSize: 18, cursor: "pointer", fontFamily: "inherit" }
        }, "+")
      ),
      /* Suit selector (4 suits only, no Sans here) */
      React.createElement("div", { style: { display: "flex", gap: 4, marginBottom: 10 } },
        [
          { id: "C", label: "\u2663", color: "#1a1a2e" },
          { id: "S", label: "\u2660", color: "#1a1a2e" },
          { id: "H", label: "\u2665", color: THEME.red },
          { id: "D", label: "\u2666", color: THEME.red }
        ].map(function(s) {
          return React.createElement("button", {
            key: s.id,
            onClick: function() { setBidS(s.id); },
            style: {
              flex: 1, padding: "6px 0", borderRadius: THEME.radiusSm,
              border: bidS === s.id ? "2px solid " + THEME.accent : "1px solid " + THEME.border,
              background: bidS === s.id ? THEME.accent + "22" : THEME.bgSurface,
              color: s.color, fontSize: 18, cursor: "pointer", fontFamily: "inherit", fontWeight: 700
            }
          }, s.label);
        })
      ),
      /* Bid + Pass row */
      React.createElement("div", { style: { display: "flex", gap: 6, marginBottom: 8 } },
        React.createElement(Button, { variant: "primary", size: "sm", onClick: handleBid, style: { flex: 1 } },
          "Bid " + bidVal + " " + (bidS === "C" ? "\u2663" : bidS === "S" ? "\u2660" : bidS === "H" ? "\u2665" : "\u2666")
        ),
        React.createElement(Button, { variant: "secondary", size: "sm", onClick: handlePass, style: { flex: 1 } }, "Pass")
      ),
      /* Special bids: Sans, Kabbout, KS */
      React.createElement("div", { style: { display: "flex", gap: 4 } },
        /* Sans: current bid number but No Trump */
        React.createElement("button", {
          onClick: function() { SoundManager.play("bid"); if (game) game.bid(bidVal + 6, "N"); },
          style: {
            flex: 1, padding: "8px 4px", borderRadius: THEME.radiusSm,
            background: "rgba(100,180,255,0.12)", border: "1px solid rgba(100,180,255,0.3)",
            color: "#64b4ff", fontSize: 11, fontWeight: 700, cursor: "pointer", fontFamily: "inherit",
            textAlign: "center"
          }
        },
          React.createElement("div", { style: { fontSize: 13 } }, bidVal + " Sans"),
          React.createElement("div", { style: { fontSize: 9, opacity: 0.7 } }, "No Trump")
        ),
        /* Kabbout: 13 tricks with selected suit */
        React.createElement("button", {
          onClick: function() { handleKabbout(bidS); },
          style: {
            flex: 1, padding: "8px 4px", borderRadius: THEME.radiusSm,
            background: "rgba(200,160,68,0.15)", border: "1px solid " + THEME.accent + "44",
            color: THEME.accent, fontSize: 11, fontWeight: 700, cursor: "pointer", fontFamily: "inherit",
            textAlign: "center"
          }
        },
          React.createElement("div", { style: { fontSize: 13 } }, "Kabbout"),
          React.createElement("div", { style: { fontSize: 9, opacity: 0.7 } }, "13 tricks")
        ),
        /* KS: Kabbout Sans (13 tricks, No Trump) */
        React.createElement("button", {
          onClick: function() { handleKabbout("N"); },
          style: {
            flex: 1, padding: "8px 4px", borderRadius: THEME.radiusSm,
            background: "rgba(160,80,208,0.12)", border: "1px solid rgba(160,80,208,0.3)",
            color: "#a050d0", fontSize: 11, fontWeight: 700, cursor: "pointer", fontFamily: "inherit",
            textAlign: "center"
          }
        },
          React.createElement("div", { style: { fontSize: 13 } }, "KS"),
          React.createElement("div", { style: { fontSize: 9, opacity: 0.7 } }, "Kabbout Sans")
        )
      )
    ),
    /* Waiting for others to bid */
    (phase === "bid" && !isMyTurn) && React.createElement("div", {
      style: { marginTop: 12, padding: "10px", background: THEME.bgSurface, borderRadius: THEME.radiusSm, textAlign: "center" }
    },
      React.createElement("div", { style: { color: THEME.textDim, fontSize: 13 } }, "Waiting for " + posNames[turn] + " to bid...")
    ),
    /* Trump display */
    trumpSuit && React.createElement("div", {
      style: { marginTop: 12, padding: "10px 14px", background: THEME.bgSurface, borderRadius: THEME.radiusSm, border: "1px solid " + THEME.accent + "33", animation: "la3ib-trump-reveal 0.6s ease both" }
    },
      React.createElement("span", { style: { color: THEME.textDim, fontSize: 12 } }, "Trump: "),
      React.createElement("span", { style: { color: THEME.accent, fontWeight: 700, fontSize: 16, textTransform: "capitalize" } }, trumpDisplay || trumpSuit)
    ),
    /* Caller/Declarer display */
    isLive && gs.contract && React.createElement("div", {
      style: { marginTop: 8, padding: "8px 14px", background: THEME.bgSurface, borderRadius: THEME.radiusSm, fontSize: 12, color: THEME.textDim }
    },
      React.createElement("span", null, "Caller: "),
      React.createElement("span", { style: { color: THEME.accent, fontWeight: 700 } },
        gs.contract.seat === mySeat ? "You" : posNames[gs.contract.seat] || "Seat " + gs.contract.seat
      ),
      React.createElement("span", null, " (" + (gs.contract.tricks >= 13 && gs.contract.suit === "N" ? "KS" : gs.contract.tricks >= 13 ? "Kabbout" : (gs.contract.tricks - 6)) + " " + (gs.contract.suit === "N" ? "Sans" : (suitSymbols[gs.contract.suit] || gs.contract.suit)) + ")")
    ),
    /* Play error feedback */
    playErr && React.createElement("div", {
      style: { marginTop: 8, padding: "8px 12px", background: "rgba(216,64,64,0.15)", border: "1px solid rgba(216,64,64,0.3)", borderRadius: THEME.radiusSm, color: THEME.redLight, fontSize: 12 }
    }, playErr),
    /* Tricks won display */
    phase === "play" && React.createElement("div", {
      style: { marginTop: 8, display: "flex", justifyContent: "space-between", fontSize: 12, color: THEME.textDim }
    },
      React.createElement("span", null, "N/S: " + nsTricks + " tricks"),
      React.createElement("span", null, "E/W: " + ewTricks + " tricks")
    )
  );

  /* ── Score Panel ── */
  var scorePanel = React.createElement(Card, {
    style: { padding: 16, minWidth: resp.isDesktop ? 200 : undefined }
  },
    React.createElement("h4", { style: { margin: "0 0 12px", color: THEME.accent, fontSize: 14, fontWeight: 700 } }, "Score"),
    React.createElement("div", {
      style: { display: "grid", gridTemplateColumns: "1fr auto 1fr", gap: 8, textAlign: "center", alignItems: "center" }
    },
      React.createElement("div", null,
        React.createElement("div", { style: { fontSize: 11, color: THEME.textDim, marginBottom: 4 } }, "N/S (You)"),
        React.createElement(AnimatedScore, { value: nsScore, style: { fontSize: 28, fontWeight: 800, color: THEME.blue } }),
        nsBid > 0 && React.createElement("div", { style: { fontSize: 11, color: THEME.textMuted } }, "Bid: " + (nsBid >= 13 ? "Kabbout" : (nsBid - 6)))
      ),
      React.createElement("div", { style: { width: 1, height: 48, background: THEME.border } }),
      React.createElement("div", null,
        React.createElement("div", { style: { fontSize: 11, color: THEME.textDim, marginBottom: 4 } }, "E/W"),
        React.createElement(AnimatedScore, { value: ewScore, style: { fontSize: 28, fontWeight: 800, color: THEME.red } })
      )
    ),
    React.createElement("div", {
      style: { marginTop: 12, padding: "8px 0", borderTop: "1px solid " + THEME.border, textAlign: "center" }
    },
      React.createElement("span", { style: { fontSize: 11, color: THEME.textMuted } }, "Target: " + targetScore)
    ),
    /* Between rounds - Next Deal button */
    phase === "between" && React.createElement("div", { style: { marginTop: 12 } },
      React.createElement(Button, { variant: "primary", size: "sm", onClick: handleNextDeal, style: { width: "100%" } }, "Next Deal")
    ),
    /* Game over */
    phase === "done" && React.createElement("div", { style: { marginTop: 12, textAlign: "center" } },
      React.createElement("div", { style: { fontSize: 18, fontWeight: 800, color: THEME.accent, marginBottom: 8 } },
        isLive && gs.winner ? gs.winner + " Wins!" : "Game Over"
      ),
      React.createElement(Button, { variant: "primary", size: "sm", onClick: props.onBack, style: { width: "100%" } }, "Back to Lobby")
    )
  );

  /* ── Felt Table ── */
  var feltTable = React.createElement("div", {
    style: {
      position: "relative", height: tableH,
      background: "radial-gradient(ellipse at center, " + THEME.feltLight + " 0%, " + THEME.felt + " 50%, " + THEME.feltDark + " 100%)",
      borderRadius: resp.isDesktop ? THEME.radiusLg : THEME.radius,
      border: "3px solid #0e3d1e", overflow: "hidden", flex: 1
    }
  },
    /* Position labels relative to mySeat */
    /* Visual: 0=bottom(you), 1=right, 2=top(partner), 3=left */
    [0, 1, 2, 3].map(function(vPos) {
      var actualSeat = (mySeat + vPos) % 4;
      var posStyles = [
        { bottom: 8, left: "50%", transform: "translateX(-50%)" },
        { right: 12, top: "50%", transform: "translateY(-50%)" },
        { top: 8, left: "50%", transform: "translateX(-50%)" },
        { left: 12, top: "50%", transform: "translateY(-50%)" }
      ];
      var isMe = vPos === 0;
      var isTurn = actualSeat === turn;
      var cardCount = handCounts[actualSeat] || 0;
      var isCaller = isLive && gs.contract && gs.contract.seat === actualSeat;
      var label = isMe ? "You" : posNames[actualSeat] || "P" + actualSeat;
      if (vPos === 2) label = (isMe ? "You" : label) + " (Partner)";
      return React.createElement("div", {
        key: vPos,
        style: Object.assign({
          position: "absolute", padding: "4px 10px",
          background: isTurn ? "rgba(200,160,68,0.3)" : isMe ? "rgba(200,160,68,0.15)" : "rgba(0,0,0,0.35)",
          borderRadius: 12, fontSize: 11, fontWeight: 600,
          color: isTurn ? THEME.accent : isMe ? THEME.accentLight : "#b0c0a0",
          zIndex: 10, border: isTurn ? "1px solid " + THEME.accent + "44" : "none",
          display: "flex", alignItems: "center", gap: 6
        }, posStyles[vPos])
      },
        label,
        isCaller && React.createElement("span", {
          style: { background: THEME.accent, color: "#000", borderRadius: 6, padding: "1px 4px", fontSize: 9, fontWeight: 800 }
        }, "CALLER"),
        phase === "play" && React.createElement("span", {
          style: { background: "rgba(0,0,0,0.4)", borderRadius: 8, padding: "1px 5px", fontSize: 10, color: "#ccc" }
        }, cardCount),
        isTurn && React.createElement("span", null, " \u25C0")
      );
    }),
    /* Tricks won display */
    phase === "play" && React.createElement("div", {
      style: {
        position: "absolute", bottom: 40, left: "50%", transform: "translateX(-50%)",
        display: "flex", gap: 16, background: "rgba(0,0,0,0.5)",
        borderRadius: 12, padding: "4px 14px", zIndex: 10, fontSize: 11, fontWeight: 600
      }
    },
      React.createElement("span", { style: { color: THEME.blue } }, "N/S: " + nsTricks),
      React.createElement("span", { style: { color: THEME.textMuted } }, "|"),
      React.createElement("span", { style: { color: THEME.red } }, "E/W: " + ewTricks)
    ),
    /* Turn timer */
    (phase === "play" || phase === "bid") && React.createElement("div", {
      style: {
        position: "absolute", top: resp.isMobile ? 40 : 50, right: resp.isMobile ? 8 : 16,
        zIndex: 15
      }
    },
      React.createElement("div", {
        style: {
          width: 40, height: 40, borderRadius: "50%",
          background: timer <= 3 ? "rgba(216,64,64,0.3)" : "rgba(0,0,0,0.4)",
          border: "2px solid " + (timer <= 3 ? THEME.red : timer <= 5 ? THEME.accent : "#5a6a5a"),
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 16, fontWeight: 800,
          color: timer <= 3 ? THEME.red : timer <= 5 ? THEME.accent : "#b0c0a0",
          transition: "all 0.3s ease"
        }
      }, timer)
    ),
    /* La3ib logo watermark in center */
    React.createElement("div", {
      style: {
        position: "absolute", top: "50%", left: "50%", transform: "translate(-50%,-50%)",
        opacity: 0.08, zIndex: 1, pointerEvents: "none"
      }
    },
      React.createElement(La3ibLogo, { size: resp.isMobile ? 60 : 80 })
    ),
    /* Center trick area */
    React.createElement("div", {
      style: { position: "absolute", top: "50%", left: "50%", transform: "translate(-50%,-50%)", width: resp.isMobile ? 180 : 220, height: resp.isMobile ? 150 : 180, display: "flex", alignItems: "center", justifyContent: "center" }
    },
      trick.map(function(c, idx) {
        if (!c) return null;
        var trickPos = [
          { bottom: -10, left: "50%", transform: "translateX(-50%)" },
          { right: -10, top: "50%", transform: "translateY(-50%)" },
          { top: -10, left: "50%", transform: "translateX(-50%)" },
          { left: -10, top: "50%", transform: "translateY(-50%)" }
        ];
        return React.createElement("div", {
          key: idx, style: Object.assign({ position: "absolute", zIndex: 5 }, trickPos[idx])
        },
          React.createElement(PlayingCard, { card: c, width: resp.isMobile ? 42 : 52 })
        );
      }),
      !trick.some(function(c) { return c !== null; }) && React.createElement("div", {
        style: {
          padding: "12px 24px",
          background: phase === "play" && isMyTurn ? "rgba(200,160,68,0.15)" : "rgba(0,0,0,0.3)",
          borderRadius: 20,
          border: phase === "play" && isMyTurn ? "1px solid rgba(200,160,68,0.3)" : "none",
          color: phase === "play" && isMyTurn ? THEME.accent : "#90a880",
          fontSize: 14, fontWeight: 600, textAlign: "center",
          animation: phase === "play" && isMyTurn ? "la3ib-glow 2s ease-in-out infinite" : "none"
        }
      }, phase === "bid" ? "Bidding" : phase === "play" && isMyTurn ? "Your Turn" : phase === "play" ? "Playing..." : phase === "between" ? "Round Over" : phase === "done" ? "Game Over" : phase === "waiting" ? "Starting..." : "Waiting...")
    ),
    /* Opponent face-down cards - Right player */
    React.createElement("div", { style: { position: "absolute", right: -4, top: "50%", transform: "translateY(-50%)", display: "flex", flexDirection: "column" } },
      Array.apply(null, Array(Math.min(handCounts[(mySeat + 1) % 4] || 3, 5))).map(function(_, i) { return React.createElement(PlayingCard, { key: i, faceDown: true, width: resp.isMobile ? 26 : 32, style: { marginBottom: -16 } }); })
    ),
    /* Top player (partner) */
    React.createElement("div", { style: { position: "absolute", top: -2, left: "50%", transform: "translateX(-50%)", display: "flex", gap: resp.isMobile ? -14 : -10 } },
      Array.apply(null, Array(Math.min(handCounts[(mySeat + 2) % 4] || 5, 7))).map(function(_, i) { return React.createElement(PlayingCard, { key: i, faceDown: true, width: resp.isMobile ? 26 : 32 }); })
    ),
    /* Left player */
    React.createElement("div", { style: { position: "absolute", left: -4, top: "50%", transform: "translateY(-50%)", display: "flex", flexDirection: "column" } },
      Array.apply(null, Array(Math.min(handCounts[(mySeat + 3) % 4] || 3, 5))).map(function(_, i) { return React.createElement(PlayingCard, { key: i, faceDown: true, width: resp.isMobile ? 26 : 32, style: { marginBottom: -16 } }); })
    )
  );

  /* ── Player Hand ── */
  var dealAnim = useDealAnimation(hand.length);
  var playerHand = React.createElement("div", {
    style: { display: "flex", justifyContent: "center", gap: resp.isMobile ? -6 : resp.isTablet ? -2 : 2, padding: "12px 8px", flexWrap: resp.isMobile ? "wrap" : "nowrap", overflowX: resp.isMobile ? "visible" : "auto" }
  },
    hand.map(function(card, idx) {
      var canPlay = phase === "play" && isMyTurn;
      return React.createElement("div", { key: idx, className: dealAnim.getCardClass(idx) },
        React.createElement(PlayingCard, {
          card: card, width: cardW,
          selected: sc === idx,
          onClick: canPlay || phase === "bid" ? function() { SoundManager.play("click"); setSc(sc === idx ? null : idx); } : undefined
        })
      );
    })
  );

  /* ── Back Button ── */
  var backBtn = React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 12 } },
    React.createElement("button", {
      onClick: props.onBack,
      style: { display: "flex", alignItems: "center", gap: 6, background: THEME.bgCard, border: "1px solid " + THEME.border, borderRadius: THEME.radiusSm, padding: "8px 16px", color: THEME.accent, fontSize: 14, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }
    },
      React.createElement(IconChevron, { direction: "left", color: THEME.accent }),
      "Back to Lobby"
    ),
    /* Connection status */
    isLive && React.createElement(Badge, { color: "green" }, "Live"),
    !isLive && React.createElement(Badge, { color: "dim" }, "Demo")
  );

  /* ── Game Info Panel (last trick + caller + tricks) ── */
  var gameInfoPanel = React.createElement(Card, {
    style: { padding: 12, marginTop: 8 }
  },
    /* Caller info */
    isLive && gs.contract && React.createElement("div", {
      style: { marginBottom: 10, padding: "8px 10px", background: THEME.bgSurface, borderRadius: THEME.radiusSm, border: "1px solid " + THEME.accent + "22" }
    },
      React.createElement("div", { style: { fontSize: 10, color: THEME.textMuted, marginBottom: 4, textTransform: "uppercase", letterSpacing: 1 } }, "Caller"),
      React.createElement("div", { style: { fontSize: 14, fontWeight: 700, color: THEME.accent } },
        (gs.contract.seat === mySeat ? "You" : posNames[gs.contract.seat] || "?") +
        " - " + (gs.contract.tricks >= 13 && gs.contract.suit === "N" ? "KS" : gs.contract.tricks >= 13 ? "Kabbout" : (gs.contract.tricks - 6)) + " " + (gs.contract.suit === "N" ? "Sans" : (suitSymbols[gs.contract.suit] || gs.contract.suit))
      )
    ),
    /* Tricks collected */
    phase === "play" && React.createElement("div", {
      style: { marginBottom: 10 }
    },
      React.createElement("div", { style: { fontSize: 10, color: THEME.textMuted, marginBottom: 6, textTransform: "uppercase", letterSpacing: 1 } }, "Tricks Won"),
      React.createElement("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center" } },
        React.createElement("div", { style: { textAlign: "center" } },
          React.createElement("div", { style: { fontSize: 22, fontWeight: 800, color: THEME.blue } }, nsTricks),
          React.createElement("div", { style: { fontSize: 10, color: THEME.textDim } }, "N/S")
        ),
        React.createElement("div", { style: { fontSize: 12, color: THEME.textMuted } }, "of " + (isLive && gs.contract ? gs.contract.tricks : "7")),
        React.createElement("div", { style: { textAlign: "center" } },
          React.createElement("div", { style: { fontSize: 22, fontWeight: 800, color: THEME.red } }, ewTricks),
          React.createElement("div", { style: { fontSize: 10, color: THEME.textDim } }, "E/W")
        )
      )
    ),
    /* Last trick */
    React.createElement("div", { style: { fontSize: 10, color: THEME.textMuted, marginBottom: 6, textTransform: "uppercase", letterSpacing: 1 } }, "Last Trick"),
    lastTr ? React.createElement("div", null,
      React.createElement("div", { style: { display: "flex", gap: 4, justifyContent: "center", marginBottom: 6 } },
        lastTr.cards.map(function(lc, li) {
          return React.createElement("div", { key: li, style: { textAlign: "center" } },
            React.createElement(PlayingCard, { card: lc.card, width: 36 }),
            React.createElement("div", { style: { fontSize: 9, color: lc.seat === lastTr.winnerSeat ? THEME.accent : THEME.textMuted, marginTop: 2, fontWeight: lc.seat === lastTr.winnerSeat ? 700 : 400 } },
              lc.seat === mySeat ? "You" : posNames[lc.seat] || "?"
            )
          );
        })
      ),
      React.createElement("div", { style: { textAlign: "center", fontSize: 11, color: THEME.accent, fontWeight: 600 } },
        "Won by " + lastTr.winner
      )
    ) : React.createElement("div", { style: { textAlign: "center", color: THEME.textMuted, fontSize: 11, padding: "8px 0" } }, "No tricks yet")
  );

  /* ── Desktop Layout ── */
  if (resp.isDesktop) {
    return React.createElement("div", null,
      backBtn,
      React.createElement("div", {
        style: { display: "grid", gridTemplateColumns: "220px 1fr 220px", gap: 16, alignItems: "start" }
      },
        React.createElement("div", null, bidPanel, gameInfoPanel),
        React.createElement("div", null,
          feltTable,
          React.createElement("div", {
            style: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 0" }
          },
            React.createElement(TauntsPanel, null),
            phase === "play" && isMyTurn && sc !== null && React.createElement(Button, {
              variant: "primary", onClick: handlePlayCard
            }, "Play Card")
          ),
          playerHand
        ),
        React.createElement("div", null, scorePanel)
      )
    );
  }

  /* ── Mobile Layout ── */
  return React.createElement("div", null,
    backBtn,
    React.createElement("div", { style: { display: "flex", gap: 8, marginBottom: 12 } },
      React.createElement("div", { style: { flex: 1 } }, bidPanel),
      React.createElement("div", { style: { flex: 1 } }, scorePanel)
    ),
    feltTable,
    React.createElement("div", {
      style: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 0" }
    },
      React.createElement(TauntsPanel, null),
      phase === "play" && isMyTurn && sc !== null && React.createElement(Button, {
        variant: "primary", onClick: handlePlayCard
      }, "Play Card")
    ),
    playerHand,
    gameInfoPanel
  );
}

/* ============================================ */
/*  MAIN PLATFORM APP                           */
/* ============================================ */

function Platform() {
  var resp = useResponsive();
  var authState = usePersist("auth", null);
  var user = authState[0]; var setUser = authState[1];
  var coinState = usePersist("coins", 1000);
  var coins = coinState[0]; var setCoins = coinState[1];
  var tabState = useState("home");
  var activeTab = tabState[0]; var setActiveTab = tabState[1];
  /* Game flow: null -> "lobby:gameId" -> "playing:gameId" */
  var gameState = useState(null);
  var activeGame = gameState[0]; var setActiveGame = gameState[1];
  var gamePlayers = useState(null);
  var players = gamePlayers[0]; var setPlayers = gamePlayers[1];

  var tabs = [
    { id: "home", label: "Home", icon: IconHome },
    { id: "games", label: "Games", icon: IconGames },
    { id: "social", label: "Social", icon: IconChat },
    { id: "store", label: "Store", icon: IconStore },
    { id: "leaderboard", label: "Ranks", icon: IconTrophy },
    { id: "profile", label: "Profile", icon: IconProfile }
  ];

  var handleLogin = function(userData) {
    setUser(userData);
    /* Connect Socket.io with JWT token */
    if (userData.token && window.La3ibSocket) {
      window.La3ibSocket.connect(window.location.origin, userData.token);
    }
  };

  var handleLogout = function() {
    setUser(null);
    setActiveTab("home");
    setActiveGame(null);
    setPlayers(null);
  };

  /* When user clicks Play on a game -> go to lobby */
  var handlePlay = function(gameId) {
    setActiveGame("lobby:" + gameId);
  };

  var handleNavigate = function(tab) {
    setActiveTab(tab);
  };

  /* When lobby starts the actual game */
  var handleStartGame = function(gamePlayers) {
    var gameId = activeGame.replace("lobby:", "");
    setPlayers(gamePlayers);
    setActiveGame("playing:" + gameId);
  };

  /* Back from lobby or game to main screens */
  var handleBackToMain = function() {
    setActiveGame(null);
    setPlayers(null);
  };

  if (!user) {
    return React.createElement(LoginScreen, { onLogin: handleLogin });
  }

  /* Lobby phase */
  if (activeGame && activeGame.indexOf("lobby:") === 0) {
    var lobbyGameId = activeGame.replace("lobby:", "");
    return React.createElement("div", {
      style: {
        minHeight: "100vh",
        background: THEME.bg,
        color: THEME.text,
        fontFamily: "'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif"
      }
    },
      React.createElement("div", { style: resp.containerStyle() },
        React.createElement("div", { style: { padding: resp.isDesktop ? "24px 0" : "16px" } },
          React.createElement(LobbyScreen, {
            gameId: lobbyGameId,
            username: user.username,
            onStartGame: handleStartGame,
            onBack: handleBackToMain
          })
        )
      )
    );
  }

  /* Active game phase */
  if (activeGame && activeGame.indexOf("playing:") === 0) {
    return React.createElement("div", {
      style: {
        minHeight: "100vh",
        background: THEME.bg,
        color: THEME.text,
        fontFamily: "'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif",
        display: "flex",
        justifyContent: "center",
        alignItems: "flex-start",
        padding: resp.isMobile ? "12px 8px" : "20px 24px"
      }
    },
      React.createElement("div", { style: { maxWidth: 1200, width: "100%", margin: "0 auto" } },
        React.createElement(TarneebGame, {
          user: user,
          players: players,
          onBack: handleBackToMain
        })
      )
    );
  }

  var renderScreen = function() {
    if (activeTab === "home") {
      return React.createElement(HomeScreen, {
        user: user, coins: coins,
        onPlay: handlePlay,
        onNavigate: handleNavigate
      });
    }
    if (activeTab === "games") {
      return React.createElement(GamesScreen, { onPlay: handlePlay });
    }
    if (activeTab === "social") {
      return React.createElement(FriendsScreen, {
        username: user.username,
        onInvite: function(friend) { handlePlay("tarneeb"); }
      });
    }
    if (activeTab === "store") {
      return React.createElement(StoreScreen, { coins: coins });
    }
    if (activeTab === "leaderboard") {
      return React.createElement(LeaderboardScreen, null);
    }
    if (activeTab === "profile") {
      return React.createElement(ProfileScreen, {
        user: user, coins: coins,
        onLogout: handleLogout
      });
    }
    if (activeTab === "settings") {
      return React.createElement(SettingsScreen, {
        onLogout: handleLogout,
        onNavigate: handleNavigate
      });
    }
    if (activeTab === "blocked") {
      return React.createElement(BlockedUsersScreen, {
        onBack: function() { handleNavigate("settings"); }
      });
    }
    return null;
  };

  return React.createElement("div", {
    style: {
      minHeight: "100vh",
      background: THEME.bg,
      color: THEME.text,
      fontFamily: "'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif",
      paddingBottom: resp.isDesktop ? 0 : 70
    }
  },
    React.createElement("div", { style: resp.containerStyle() },
      React.createElement(AppHeader, {
        tabs: tabs,
        activeTab: activeTab,
        onTabChange: setActiveTab,
        coins: coins,
        username: user.username,
        onNavigate: handleNavigate
      }),
      React.createElement("div", { style: { padding: resp.isDesktop ? "24px 0" : "16px" } },
        renderScreen()
      )
    ),
    !resp.isDesktop && React.createElement(TabBar, {
      tabs: tabs,
      activeTab: activeTab,
      onTabChange: setActiveTab
    })
  );
}

/* ============================================ */
/*  DEFAULT EXPORT                              */
/* ============================================ */

if (typeof module !== "undefined" && module.exports) {
  module.exports = Platform;
}

/* For direct rendering */
if (typeof window !== "undefined" && window.ReactDOM) {
  var root = document.getElementById("root");
  if (root) {
    if (window.ReactDOM.createRoot) {
      window.ReactDOM.createRoot(root).render(React.createElement(Platform));
    } else {
      window.ReactDOM.render(React.createElement(Platform), root);
    }
  }
}
