/* global React */
// Pixel-art card — canvas background + chamfered SVG panels + bitmap fonts.
// Card is 400×512 final, painted at 100×128 native and upscaled 4× pixelated.

const { useRef, useEffect, useMemo } = React;

// ============ Palettes (limited, per-rarity) ============
const RARITIES = {
  comum: {
    label: "COMUM",
    bgImage: "assets/bg-comum.png",
    frameOuter: "#2e2e34",
    frameGold:  "#c8c8d0",
    frameInner: "#5a5a64",
    namePlateBg:"#f4ecd8",
    namePlateEdge:"#2e2e34",
    nameText:   "#2a2a32",
    statPanelBg:"#22222a",
    statPanelEdge:"#0e0e14",
    panelLine:  "#c8c8d0",
    statLabel:  "#c8c8d0",
    value:      "#f4f4f8",
    icon:       "#f4ecd8",
    divider:    "#0e0e14",
    badgeBg:    "#22222a",
    badgeBorder:"#c8c8d0",
    badgeText:  "#f4ecd8",
    panelBg:    "#22222a",
    panelEdge:  "#0e0e14",
  },
  raro: {
    label: "RARO",
    bgImage: "assets/bg-raro.png",
    frameOuter: "#062448",
    frameGold:  "#f8d860",
    frameInner: "#1a52b8",
    namePlateBg:"#f4ecd8",
    namePlateEdge:"#062448",
    nameText:   "#0a2068",
    statPanelBg:"#0c2a78",
    statPanelEdge:"#04143a",
    panelLine:  "#f8d860",
    statLabel:  "#f8d860",
    value:      "#fff8d0",
    icon:       "#f8d860",
    divider:    "#04143a",
    badgeBg:    "#0c2a78",
    badgeBorder:"#f8d860",
    badgeText:  "#fff8d0",
    panelBg:    "#0c2a78",
    panelEdge:  "#04143a",
  },
  epico: {
    label: "ÉPICO",
    bgImage: "assets/bg-epico.png",
    frameOuter: "#1e0438",
    frameGold:  "#f4d060",
    frameInner: "#5a1c92",
    namePlateBg:"#f4ecd8",
    namePlateEdge:"#1e0438",
    nameText:   "#2a0a55",
    statPanelBg:"#2a0a55",
    statPanelEdge:"#0a0218",
    panelLine:  "#f4d060",
    statLabel:  "#f4d060",
    value:      "#fff8e0",
    icon:       "#f4d060",
    divider:    "#0a0218",
    badgeBg:    "#2a0a55",
    badgeBorder:"#f4d060",
    badgeText:  "#fff8e0",
    panelBg:    "#2a0a55",
    panelEdge:  "#0a0218",
  },
  lendario: {
    label: "LENDÁRIO",
    bgImage: "assets/bg-lendario.png",
    frameOuter: "#2a1404",
    frameGold:  "#f8d860",
    frameInner: "#a06820",
    namePlateBg:"#f4ecd8",
    namePlateEdge:"#2a1404",
    nameText:   "#3a2008",
    statPanelBg:"#3a2008",
    statPanelEdge:"#150804",
    panelLine:  "#f8d860",
    statLabel:  "#f8d860",
    value:      "#fff8d0",
    icon:       "#f8d860",
    divider:    "#150804",
    badgeBg:    "#3a2008",
    badgeBorder:"#f8d860",
    badgeText:  "#fff8d0",
    panelBg:    "#3a2008",
    panelEdge:  "#150804",
  },
};

// ============ Background (uses static images) ============
function PixelBackground({ rarity }) {
  const p = RARITIES[rarity];
  return (
    <img
      src={p.bgImage}
      alt=""
      crossOrigin="anonymous"
      style={{
        position: "absolute",
        inset: 0,
        width: "100%",
        height: "100%",
        zIndex: 0,
        imageRendering: "pixelated",
        objectFit: "cover",
        userSelect: "none",
        pointerEvents: "none",
      }}
      draggable={false}
    />
  );
}

// ============ Pixel-art icons (12×12 grid) ============
// Each icon is a bitmap as array of strings. '.' = transparent, '#' = filled
const ICON_BITMAPS = {
  trophy: [
    "............",
    "..########..",
    "..#......#..",
    ".##......##.",
    ".#.######.#.",
    ".#.######.#.",
    ".##......##.",
    "..#.####.#..",
    "...#....#...",
    "...######...",
    "..########..",
    "............",
  ],
  star: [
    "............",
    ".....##.....",
    ".....##.....",
    "....####....",
    ".##########.",
    "..########..",
    "...######...",
    "..##....##..",
    ".##......##.",
    "............",
    "............",
    "............",
  ],
  ball: [
    "............",
    "...######...",
    "..#.####.#..",
    ".##.####.##.",
    ".#..####..#.",
    ".########.#.",
    ".#.######.#.",
    ".##.####.##.",
    "..#.####.#..",
    "...######...",
    "............",
    "............",
  ],
  crown: [
    "............",
    ".#..........",
    ".##....##..#",
    ".#.#..#..#.#",
    ".#..##.#..##",
    ".#######..#.",
    ".##########.",
    ".##.####.##.",
    ".##########.",
    "............",
    "............",
    "............",
  ],
  people: [
    "............",
    "...##....##.",
    "..####..####",
    "..####..####",
    "...##....##.",
    "............",
    ".########..#",
    "##......####",
    "##......##.#",
    "##......##.#",
    "############",
    "............",
  ],
  shield: [
    "............",
    "..########..",
    ".##########.",
    ".##########.",
    ".##.....###.",
    ".###...###..",
    ".####.####..",
    "..########..",
    "...######...",
    "....####....",
    ".....##.....",
    "............",
  ],
  calendar: [
    "............",
    "..##....##..",
    "..##....##..",
    "############",
    "#..........#",
    "############",
    "#..#..#..#.#",
    "#..#..#..#.#",
    "#..........#",
    "############",
    "............",
    "............",
  ],
  flag: [
    "............",
    ".#..........",
    ".#######....",
    ".#.....##...",
    ".#......#...",
    ".#.....##...",
    ".#######....",
    ".#..........",
    ".#..........",
    ".#..........",
    "............",
    "............",
  ],
  boot: [
    "............",
    "............",
    "....#####...",
    "...##...##..",
    "..##.....##.",
    "..#.......##",
    "..#.......##",
    "############",
    ".##########.",
    "............",
    "............",
    "............",
  ],
  whistle: [
    "............",
    "............",
    "...####.....",
    "..######.###",
    ".#####.#.###",
    ".#####.#####",
    "..######.###",
    "...####.....",
    "............",
    "............",
    "............",
    "............",
  ],
  position: [
    "............",
    "....####....",
    "..########..",
    ".##......##.",
    ".#...##...#.",
    ".#..####..#.",
    ".#...##...#.",
    ".##......##.",
    "..########..",
    "....####....",
    "............",
    "............",
  ],
  bolt: [
    "............",
    "......###...",
    ".....####...",
    "....####....",
    "...####.....",
    "..########..",
    "...#####....",
    "...####.....",
    "..####......",
    ".####.......",
    "############",
    "............",
  ],
  goal: [
    "............",
    "############",
    "#..#..#..#.#",
    "#..#..#..#.#",
    "############",
    "#..#..#..#.#",
    "#..#..#..#.#",
    "############",
    "#..........#",
    "############",
    "............",
    "............",
  ],
  cards: [
    "............",
    "..######....",
    ".#......#...",
    ".#......#...",
    ".#......#.##",
    ".#......##.#",
    ".#######.#.#",
    "..####...#.#",
    ".......#..##",
    ".......####.",
    "............",
    "............",
  ],
};

const ICON_NAMES = Object.keys(ICON_BITMAPS);

// Renders a pixel icon at a given pixel size (each '#' becomes a SIZE×SIZE square)
function PixelIcon({ name, color, pixelSize = 2 }) {
  const map = ICON_BITMAPS[name] || ICON_BITMAPS.star;
  const w = map[0].length * pixelSize;
  const h = map.length * pixelSize;
  return (
    <svg
      width={w}
      height={h}
      viewBox={`0 0 ${map[0].length} ${map.length}`}
      shapeRendering="crispEdges"
      style={{ display: "block", imageRendering: "pixelated" }}
    >
      {map.map((row, y) =>
        row.split("").map((c, x) =>
          c === "#" ? <rect key={`${x},${y}`} x={x} y={y} width="1" height="1" fill={color} /> : null
        )
      )}
    </svg>
  );
}

// ============ Pixel frame (chunky gold, double-line) ============
function PixelFrame({ rarity }) {
  const p = RARITIES[rarity];
  // Native 100×128 viewBox, pixel-perfect rings.
  // Frame layers from outermost to innermost:
  //   0-1: outer dark line (1 native px)
  //   1-5: thick gold band (4 native px)
  //   5-6: inner dark line (1 native px)
  // Total: 6 native px = 24 upscaled px
  const outer = "M0,0 H100 V128 H0 Z";
  const r1 = "M1,1 H99 V127 H1 Z";
  const r5 = "M5,5 H95 V123 H5 Z";
  const r6 = "M6,6 H94 V122 H6 Z";
  return (
    <svg
      width="100%"
      height="100%"
      viewBox="0 0 100 128"
      shapeRendering="crispEdges"
      preserveAspectRatio="none"
      style={{ position: "absolute", inset: 0, zIndex: 4, pointerEvents: "none" }}
    >
      {/* outer dark line */}
      <path d={`${outer} ${r1}`} fillRule="evenodd" fill={p.frameOuter} />
      {/* gold band */}
      <path d={`${r1} ${r5}`} fillRule="evenodd" fill={p.frameGold} />
      {/* gold subtle shading — a darker stripe inside the band gives bevel */}
      <path d="M2,2 H98 V3 H2 Z M2,125 H98 V126 H2 Z M2,3 H3 V125 H2 Z M97,3 H98 V125 H97 Z"
            fill={p.frameOuter} opacity="0.18" />
      {/* inner dark line */}
      <path d={`${r5} ${r6}`} fillRule="evenodd" fill={p.frameOuter} />
    </svg>
  );
}

// ============ Pixel corner brackets (simple L, like reference) ============
function PixelCornerOrnaments({ rarity }) {
  const p = RARITIES[rarity];
  // Simple 4×4 native L-bracket: just a corner accent
  const Bracket = () => (
    <g>
      {/* horizontal bar */}
      <rect x="0" y="0" width="4" height="1" fill={p.frameOuter} />
      {/* vertical bar */}
      <rect x="0" y="0" width="1" height="4" fill={p.frameOuter} />
    </g>
  );
  return (
    <svg
      width="100%"
      height="100%"
      viewBox="0 0 100 128"
      shapeRendering="crispEdges"
      preserveAspectRatio="none"
      style={{ position: "absolute", inset: 0, zIndex: 5, pointerEvents: "none" }}
    >
      <g transform="translate(6,6)"><Bracket /></g>
      <g transform="translate(94,6) scale(-1,1)"><Bracket /></g>
      <g transform="translate(6,122) scale(1,-1)"><Bracket /></g>
      <g transform="translate(94,122) scale(-1,-1)"><Bracket /></g>
    </svg>
  );
}

// ============ Chamfered pixel panel ============
function PixelPanel({ x, y, w, h, bg, line, edge, children, style }) {
  // x,y,w,h in upscaled px (400×512 space).
  // Renders an SVG chamfered rect behind the children, then absolute children on top.
  const cx = 6; // chamfer in px (= 1.5 native, but visually 6px reads well)
  return (
    <div style={{ position: "absolute", left: x, top: y, width: w, height: h, ...style }}>
      <svg
        width="100%"
        height="100%"
        viewBox={`0 0 ${w} ${h}`}
        shapeRendering="crispEdges"
        preserveAspectRatio="none"
        style={{ position: "absolute", inset: 0 }}
      >
        {/* dark edge */}
        <path
          d={`M0,${cx} L${cx},0 L${w-cx},0 L${w},${cx} L${w},${h-cx} L${w-cx},${h} L${cx},${h} L0,${h-cx} Z`}
          fill={edge}
        />
        {/* gold line */}
        <path
          d={`M2,${cx} L${cx},2 L${w-cx},2 L${w-2},${cx} L${w-2},${h-cx} L${w-cx},${h-2} L${cx},${h-2} L2,${h-cx} Z`}
          fill={line}
        />
        {/* inner fill */}
        <path
          d={`M4,${cx} L${cx},4 L${w-cx},4 L${w-4},${cx} L${w-4},${h-cx} L${w-cx},${h-4} L${cx},${h-4} L4,${h-cx} Z`}
          fill={bg}
        />
      </svg>
      <div style={{ position: "relative", width: "100%", height: "100%", zIndex: 1 }}>
        {children}
      </div>
    </div>
  );
}

// ============ Rarity badge (small chamfered panel top-left) ============
function RarityBadge({ rarity }) {
  const p = RARITIES[rarity];
  const label = p.label;
  // Approximate badge width based on label length (Press Start 2P ~10px per char at 10px size)
  const w = 24 + label.length * 12;
  return (
    <PixelPanel
      x={20}
      y={20}
      w={w}
      h={32}
      bg={p.badgeBg}
      line={p.frameGold}
      edge={p.frameOuter}
      style={{ zIndex: 6 }}
    >
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          fontFamily: "'Press Start 2P', monospace",
          fontSize: 10,
          color: p.badgeText,
          letterSpacing: "0.04em",
        }}
      >
        {label}
      </div>
    </PixelPanel>
  );
}

// ============ Stat cell ============
function StatCell({ icon, label, value, rarity, isLast }) {
  const p = RARITIES[rarity];
  return (
    <div
      style={{
        flex: 1,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        gap: 6,
        padding: "8px 4px",
        position: "relative",
        height: "100%",
      }}
    >
      <div
        style={{
          fontFamily: "'Press Start 2P', monospace",
          fontSize: 7,
          color: p.statLabel,
          letterSpacing: "0.02em",
          textTransform: "uppercase",
          textAlign: "center",
          lineHeight: 1.4,
        }}
      >
        {label}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
        <PixelIcon name={icon} color={p.icon} pixelSize={2} />
        <div
          style={{
            fontFamily: "'Press Start 2P', monospace",
            fontSize: 12,
            color: p.value,
            letterSpacing: "0.02em",
          }}
        >
          {value}
        </div>
      </div>
      {!isLast && (
        <div
          style={{
            position: "absolute",
            right: 0,
            top: 10,
            bottom: 10,
            width: 4,
            background: p.divider,
          }}
        />
      )}
    </div>
  );
}

// ============ Flag thumbnail (with chamfered border) ============
function FlagThumb({ src, rarity }) {
  const p = RARITIES[rarity];
  return (
    <PixelPanel
      x={0}
      y={0}
      w={80}
      h={56}
      bg={p.panelEdge}
      line={p.frameGold}
      edge={p.frameOuter}
      style={{ position: "relative", flexShrink: 0 }}
    >
      <div style={{
        width: "100%",
        height: "100%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 4,
      }}>
        {src ? (
          <img
            src={src}
            alt="flag"
            style={{
              maxWidth: "100%",
              maxHeight: "100%",
              objectFit: "contain",
              imageRendering: "pixelated",
            }}
            crossOrigin="anonymous"
          />
        ) : (
          <div style={{
            fontFamily: "'Press Start 2P', monospace",
            fontSize: 6,
            color: p.statLabel,
          }}>FLAG</div>
        )}
      </div>
    </PixelPanel>
  );
}

// ============ Stat row (vertical list mode — flowing text) ============
function StatRow({ icon, label, value, rarity, isLast, rowHeight }) {
  const p = RARITIES[rarity];
  return (
    <div
      style={{
        height: rowHeight,
        display: "flex",
        alignItems: "center",
        gap: 10,
        padding: "0 14px",
        position: "relative",
        borderBottom: isLast ? "none" : `2px solid ${p.divider}`,
        overflow: "hidden",
      }}
    >
      <div style={{ flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", width: 28 }}>
        <PixelIcon name={icon} color={p.icon} pixelSize={2} />
      </div>
      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", justifyContent: "center", gap: 3 }}>
        <div
          style={{
            fontFamily: "'Press Start 2P', monospace",
            fontSize: 9,
            color: p.statLabel,
            letterSpacing: "0.02em",
            textTransform: "uppercase",
            lineHeight: 1.1,
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
          }}
        >
          {label}
        </div>
        {value && (
          <div
            style={{
              fontFamily: "'Press Start 2P', monospace",
              fontSize: 8,
              color: p.value,
              letterSpacing: "0.02em",
              textTransform: "uppercase",
              lineHeight: 1.1,
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
          >
            {value}
          </div>
        )}
      </div>
    </div>
  );
}

// ============ Main Card ============
function Figurinha({ data, ariaId }) {
  const {
    rarity = "comum",
    name = "BRASIL",
    subtitle = "",
    image = null,
    flag = null,
    stats = [],
    photoLayout = false,
    hideFlag = false,
  } = data || {};

  const p = RARITIES[rarity];

  // Layout dimensions (in 400×512 space)
  // PHOTO MODE: full-bleed image (352×240), bigger name plate with subtitle, vertical-list stats
  // CLASSIC MODE: centered illustration with margins, horizontal stat cells
  const layout = photoLayout
    ? { imgX: 24, imgY: 24, imgW: 352, imgH: 240, nameY: 272, nameH: 64, statsY: 344, statsH: 144, listStats: true }
    : { imgX: 24, imgY: 64, imgW: 352, imgH: 248, nameY: 320, nameH: 56, statsY: 388, statsH: 92,  listStats: false };

  const hasSubtitle = !!(subtitle && subtitle.trim());

  // Name font sizing — accounts for subtitle line + flag overhang
  const reservedRight = hideFlag ? 0 : 60;
  const reservedLeft  = hideFlag ? 0 : 0;
  const usableW = 360 - 24 - reservedRight - reservedLeft;
  const nameFontSize = hasSubtitle
    ? (name.length <= 14 ? 17 : name.length <= 20 ? 14 : name.length <= 26 ? 11 : 9)
    : (name.length <= 6  ? 24 : name.length <= 9  ? 20 : name.length <= 14 ? 16 : 13);

  const rowH = stats.length > 0 ? Math.floor(layout.statsH / stats.length) : layout.statsH;

  return (
    <div
      className="card-frame"
      id={ariaId}
      data-screen-label={`Figurinha ${name} ${p.label}`}
      style={{
        background: p.frameOuter,
        imageRendering: "pixelated",
      }}
    >
      {/* canvas background */}
      <div style={{ position: "absolute", inset: 12, zIndex: 0, overflow: "hidden" }}>
        <PixelBackground rarity={rarity} />
      </div>

      {/* image area (full-bleed in photo mode, contained in classic) */}
      <div
        style={{
          position: "absolute",
          top: layout.imgY,
          left: layout.imgX,
          width: layout.imgW,
          height: layout.imgH,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          overflow: "hidden",
          zIndex: 1,
        }}
      >
        {image ? (
          <img
            src={image}
            alt={name}
            crossOrigin="anonymous"
            style={{
              width: photoLayout ? "100%" : "auto",
              height: photoLayout ? "100%" : "auto",
              maxWidth: "100%",
              maxHeight: "100%",
              objectFit: photoLayout ? "cover" : "contain",
              imageRendering: "pixelated",
              filter: photoLayout ? "none" : "drop-shadow(2px 2px 0 rgba(0,0,0,0.55))",
              display: "block",
            }}
          />
        ) : (
          <div
            style={{
              width: photoLayout ? "100%" : "60%",
              height: photoLayout ? "100%" : "60%",
              border: `4px dashed ${p.frameGold}`,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: p.frameGold,
              fontFamily: "'Press Start 2P', monospace",
              fontSize: photoLayout ? 10 : 9,
              textAlign: "center",
              lineHeight: 1.7,
              opacity: 0.55,
            }}
          >
            {photoLayout ? (
              <span>UPLOAD<br/>352 × 240<br/>(ou 1056 × 720)</span>
            ) : (
              <span>ARTE<br/>CENTRAL</span>
            )}
          </div>
        )}
      </div>

      {/* frame */}
      <PixelFrame rarity={rarity} />
      <PixelCornerOrnaments rarity={rarity} />

      {/* badge */}
      <RarityBadge rarity={rarity} />

      {/* name plate (cream/beige with dark text) */}
      <PixelPanel
        x={20}
        y={layout.nameY}
        w={360}
        h={layout.nameH}
        bg={p.namePlateBg}
        line={p.frameGold}
        edge={p.namePlateEdge}
        style={{ zIndex: 6 }}
      >
        <div style={{
          width: "100%",
          height: "100%",
          display: "flex",
          alignItems: "center",
          padding: "0 12px",
          gap: 12,
        }}>
          {!hideFlag && (
            <div style={{ marginTop: -28, flexShrink: 0 }}>
              <FlagThumb src={flag} rarity={rarity} />
            </div>
          )}
          <div style={{
            flex: 1,
            minWidth: 0,
            textAlign: "center",
            paddingRight: reservedRight,
            display: "flex",
            flexDirection: "column",
            justifyContent: "center",
            gap: hasSubtitle ? 6 : 0,
          }}>
            <div style={{
              fontFamily: "'Press Start 2P', monospace",
              fontSize: nameFontSize,
              color: p.nameText,
              letterSpacing: "0.04em",
              textTransform: "uppercase",
              lineHeight: 1,
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}>
              {name}
            </div>
            {hasSubtitle && (
              <div style={{
                fontFamily: "'Press Start 2P', monospace",
                fontSize: 9,
                color: p.nameText,
                letterSpacing: "0.06em",
                textTransform: "uppercase",
                lineHeight: 1,
                opacity: 0.65,
                whiteSpace: "nowrap",
                overflow: "hidden",
                textOverflow: "ellipsis",
              }}>
                {subtitle}
              </div>
            )}
          </div>
        </div>
      </PixelPanel>

      {/* stats panel */}
      <PixelPanel
        x={20}
        y={layout.statsY}
        w={360}
        h={layout.statsH}
        bg={p.statPanelBg}
        line={p.frameGold}
        edge={p.statPanelEdge}
        style={{ zIndex: 6 }}
      >
        <div style={{
          width: "100%",
          height: "100%",
          display: "flex",
          flexDirection: layout.listStats ? "column" : "row",
          alignItems: "stretch",
        }}>
          {stats.length === 0 ? (
            <div style={{
              flex: 1,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: p.statLabel,
              fontFamily: "'Press Start 2P', monospace",
              fontSize: 8,
              opacity: 0.7,
            }}>SEM ESTATÍSTICAS</div>
          ) : layout.listStats ? (
            stats.map((s, i) => (
              <StatRow
                key={i}
                icon={s.icon}
                label={s.label}
                value={s.value}
                rarity={rarity}
                isLast={i === stats.length - 1}
                rowHeight={rowH}
              />
            ))
          ) : (
            stats.map((s, i) => (
              <StatCell
                key={i}
                icon={s.icon}
                label={s.label}
                value={s.value}
                rarity={rarity}
                isLast={i === stats.length - 1}
              />
            ))
          )}
        </div>
      </PixelPanel>
    </div>
  );
}

// Exports
window.Figurinha = Figurinha;
window.RARITIES = RARITIES;
window.ICON_NAMES = ICON_NAMES;
window.Icons = ICON_BITMAPS; // for the editor preview
window.PixelIcon = PixelIcon;
