// Backgammon board — visual + minimal game state for prototype
// Exposes: Board, useGameState, START_POSITION

const START_POSITION = (() => {
  // points[0..23]; positive = gold (player), negative = cobalt (AI)
  // Standard starting position from gold's perspective
  const p = Array(24).fill(0);
  p[0] = 2;   p[11] = 5;   p[16] = 3;   p[18] = 5;
  p[23] = -2; p[12] = -5;  p[7] = -3;   p[5] = -5;
  return { points: p, bar: { gold: 0, cobalt: 0 }, off: { gold: 0, cobalt: 0 } };
})();

function useGameState() {
  const [pos, setPos] = React.useState(START_POSITION);
  const [dice, setDice] = React.useState([5, 3]);
  const [used, setUsed] = React.useState([false, false]);
  const [turn, setTurn] = React.useState('gold');
  const [selected, setSelected] = React.useState(null);
  const [rolling, setRolling] = React.useState(false);
  const [cube, setCube] = React.useState({ value: 1, owner: null });

  const roll = () => {
    setRolling(true);
    setTimeout(() => {
      setDice([1 + Math.floor(Math.random() * 6), 1 + Math.floor(Math.random() * 6)]);
      setUsed([false, false]);
      setRolling(false);
    }, 600);
  };

  return { pos, setPos, dice, setDice, used, setUsed, turn, setTurn, selected, setSelected, rolling, roll, cube, setCube };
}

// ─────────────────────────────────────────────────────────────
// Board visual — premium walnut + lapis + turquoise + pomegranate
// ─────────────────────────────────────────────────────────────
function Board({
  pos = START_POSITION, dice = [5,3], used = [false,false],
  selected = null, onPointTap, dark = false,
  checkerStyle = 'khatam', cube = { value: 1, owner: null },
}) {
  const t = themeFor(dark);

  // Designed for 360 wide × 460 tall.
  const W = 360, H = 460;
  const FRAME = 14;
  const TRAY = 26;
  const BAR = 30;
  const innerW = W - FRAME * 2 - TRAY * 2;
  const halfW = (innerW - BAR) / 2;
  const pointW = halfW / 6;
  const pointH = (H - FRAME * 2) * 0.42;
  const innerH = H - FRAME * 2;

  // pointIndex → layout
  const layout = (i) => {
    let col, row, dir;
    if (i >= 12) { row = 'top'; col = i - 12; dir = 'down'; }
    else { row = 'bottom'; col = 11 - i; dir = 'up'; }
    const past = col >= 6 ? BAR : 0;
    const x = col * pointW + past + pointW / 2;
    const y = row === 'top' ? 0 : innerH;
    return { x, y, row, col, dir };
  };

  const stackChecker = (idx, count, side) => {
    const { x, y, dir } = layout(idx);
    const checkers = [];
    const max = Math.min(Math.abs(count), 5);
    const cSize = 28;
    const overflow = Math.abs(count) > 5;
    for (let k = 0; k < max; k++) {
      const offset = k * (cSize - 6);
      const cy = dir === 'down' ? y + 6 + offset : y - 6 - offset - cSize;
      checkers.push({ x: x - cSize / 2, y: cy, k, side, size: cSize, top: k === max - 1 });
    }
    return { checkers, overflow, count: Math.abs(count) };
  };

  // colors
  const surface = dark ? '#1A0F07' : '#E8DCC2';
  const surfaceShade = dark ? '#0F0804' : '#D9CAA8';

  return (
    <div style={{
      width: W, height: H, borderRadius: 16, position: 'relative',
      // Layered walnut: base radial + diagonal grain + edge vignette
      background: dark
        ? 'radial-gradient(120% 140% at 30% 20%, #4A3220 0%, #3E2A1C 38%, #261810 75%, #14090A 100%)'
        : 'radial-gradient(120% 140% at 30% 20%, #6E4A2E 0%, #5C3F28 38%, #3E2A1C 75%, #2A1A10 100%)',
      boxShadow: dark
        ? 'inset 0 0 0 1px rgba(0,0,0,0.55), inset 0 1px 0 rgba(255,210,160,0.08), 0 14px 36px rgba(0,0,0,0.55)'
        : 'inset 0 0 0 1px rgba(0,0,0,0.35), inset 0 1px 0 rgba(255,220,170,0.18), 0 14px 36px rgba(31,17,8,0.32)',
      overflow: 'hidden',
    }}>
      {/* Wood grain — diagonal long fibers */}
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.35, mixBlendMode: 'overlay',
        backgroundImage: `repeating-linear-gradient(92deg,
          transparent 0 2px,
          rgba(0,0,0,0.18) 2px 3px,
          transparent 3px 7px,
          rgba(255,210,160,0.06) 7px 8px)`,
      }}/>
      {/* Cross-grain highlight band */}
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.28, mixBlendMode: 'soft-light',
        backgroundImage: `linear-gradient(178deg,
          rgba(255,220,170,0.5) 0%,
          rgba(255,220,170,0) 18%,
          rgba(0,0,0,0) 70%,
          rgba(0,0,0,0.45) 100%)`,
      }}/>
      {/* corner sheen */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(80% 60% at 18% 8%, rgba(255,236,196,0.22), transparent 55%)',
      }}/>

      {/* Decorative inlay border — brass + pomegranate hairlines */}
      <KhatamBorder W={W} H={H} dark={dark} />

      {/* Inner well — recessed plaster surface */}
      <div style={{
        position: 'absolute',
        left: FRAME + TRAY, top: FRAME,
        width: innerW, height: innerH,
        background: surface,
        boxShadow: dark
          ? 'inset 0 2px 6px rgba(0,0,0,0.7), inset 0 -1px 2px rgba(0,0,0,0.5), 0 0 0 0.5px rgba(0,0,0,0.6)'
          : 'inset 0 2px 6px rgba(60,40,20,0.32), inset 0 -1px 2px rgba(60,40,20,0.18), 0 0 0 0.5px rgba(0,0,0,0.25)',
      }}>
        {/* plaster speckle texture */}
        <div style={{
          position: 'absolute', inset: 0, opacity: dark ? 0.18 : 0.22, mixBlendMode: 'multiply',
          backgroundImage: `radial-gradient(circle at 20% 30%, rgba(0,0,0,0.4) 0.5px, transparent 1px),
                            radial-gradient(circle at 75% 65%, rgba(0,0,0,0.3) 0.5px, transparent 1px),
                            radial-gradient(circle at 40% 80%, rgba(0,0,0,0.3) 0.5px, transparent 1px),
                            radial-gradient(circle at 90% 20%, rgba(0,0,0,0.25) 0.5px, transparent 1px)`,
          backgroundSize: '7px 7px, 9px 9px, 11px 11px, 6px 6px',
        }}/>

        {/* points */}
        <svg width={innerW} height={innerH} style={{ position: 'absolute', inset: 0 }}>
          <defs>
            {/* vertical gradient for triangles for subtle depth */}
            <linearGradient id="pt-light-top" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={dark ? '#D9C8A6' : '#F4ECD7'}/>
              <stop offset="100%" stopColor={dark ? '#A89572' : '#D8C599'}/>
            </linearGradient>
            <linearGradient id="pt-light-bot" x1="0" y1="1" x2="0" y2="0">
              <stop offset="0%" stopColor={dark ? '#D9C8A6' : '#F4ECD7'}/>
              <stop offset="100%" stopColor={dark ? '#A89572' : '#D8C599'}/>
            </linearGradient>
            <linearGradient id="pt-lapis-top" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={dark ? '#3A5BC4' : '#2C4FB0'}/>
              <stop offset="100%" stopColor={dark ? '#15276A' : '#0F2766'}/>
            </linearGradient>
            <linearGradient id="pt-lapis-bot" x1="0" y1="1" x2="0" y2="0">
              <stop offset="0%" stopColor={dark ? '#3A5BC4' : '#2C4FB0'}/>
              <stop offset="100%" stopColor={dark ? '#15276A' : '#0F2766'}/>
            </linearGradient>
            <linearGradient id="pt-firuzeh-top" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={dark ? '#5DD3CB' : '#5DD3CB'}/>
              <stop offset="100%" stopColor={dark ? '#1F7E7A' : '#1F7E7A'}/>
            </linearGradient>
            <linearGradient id="pt-firuzeh-bot" x1="0" y1="1" x2="0" y2="0">
              <stop offset="0%" stopColor={dark ? '#5DD3CB' : '#5DD3CB'}/>
              <stop offset="100%" stopColor={dark ? '#1F7E7A' : '#1F7E7A'}/>
            </linearGradient>
            <radialGradient id="point-glow" cx="50%" cy="50%" r="60%">
              <stop offset="0%" stopColor="rgba(255,236,196,0.25)"/>
              <stop offset="100%" stopColor="rgba(255,236,196,0)"/>
            </radialGradient>
          </defs>

          {/* faint center seam (down the middle of each point) */}
          {Array.from({length: 12}, (_, col) => {
            const past = col >= 6 ? BAR : 0;
            const x = col * pointW + past;
            const isLight = col % 2 === 0;
            const accentKey = col % 4 < 2 ? 'lapis' : 'firuzeh';
            const fillTop = isLight ? `url(#pt-light-top)` : `url(#pt-${accentKey}-top)`;
            const fillBot = isLight ? `url(#pt-light-bot)` : `url(#pt-${accentKey}-bot)`;
            const tipColor = accentKey === 'lapis' ? '#C9A24C' : '#C9A24C';
            return (
              <g key={col}>
                {/* TOP triangle */}
                <polygon
                  points={`${x},0 ${x + pointW},0 ${x + pointW/2},${pointH}`}
                  fill={fillTop}
                  stroke={dark ? 'rgba(0,0,0,0.5)' : 'rgba(31,15,5,0.32)'}
                  strokeWidth="0.5"
                />
                {/* inner shadow at base */}
                <polygon
                  points={`${x},0 ${x + pointW},0 ${x + pointW/2},${pointH * 0.16}`}
                  fill={isLight ? 'rgba(60,40,20,0.18)' : 'rgba(0,0,0,0.28)'}
                />
                {/* tiny brass dot at tip */}
                <circle cx={x + pointW/2} cy={pointH - 2.5} r="1"
                  fill={tipColor} opacity="0.7"/>

                {/* BOTTOM triangle */}
                <polygon
                  points={`${x},${innerH} ${x + pointW},${innerH} ${x + pointW/2},${innerH - pointH}`}
                  fill={fillBot}
                  stroke={dark ? 'rgba(0,0,0,0.5)' : 'rgba(31,15,5,0.32)'}
                  strokeWidth="0.5"
                />
                <polygon
                  points={`${x},${innerH} ${x + pointW},${innerH} ${x + pointW/2},${innerH - pointH * 0.16}`}
                  fill={isLight ? 'rgba(60,40,20,0.18)' : 'rgba(0,0,0,0.28)'}
                />
                <circle cx={x + pointW/2} cy={innerH - pointH + 2.5} r="1"
                  fill={tipColor} opacity="0.7"/>
              </g>
            );
          })}

          {/* center bar — walnut band w/ vertical brass hairlines */}
          <g>
            <rect x={6 * pointW} y={0} width={BAR} height={innerH}
              fill={dark ? '#1A0F07' : '#3E2A1C'}/>
            {/* inset shadow */}
            <rect x={6 * pointW} y={0} width="2" height={innerH}
              fill="rgba(0,0,0,0.5)"/>
            <rect x={6 * pointW + BAR - 2} y={0} width="2" height={innerH}
              fill="rgba(0,0,0,0.5)"/>
            {/* brass hairlines */}
            <line x1={6 * pointW + 4} y1={2} x2={6 * pointW + 4} y2={innerH - 2}
              stroke="#C9A24C" strokeWidth="0.35" opacity="0.5"/>
            <line x1={6 * pointW + BAR - 4} y1={2} x2={6 * pointW + BAR - 4} y2={innerH - 2}
              stroke="#C9A24C" strokeWidth="0.35" opacity="0.5"/>

            {/* khatam stack on bar */}
            <g transform={`translate(${6 * pointW + BAR/2}, ${innerH/2 - 60})`}>
              {[0, 30, 60, 90, 120].map((yOff, idx) => {
                const stars = ['gold','red','turq','red','gold'];
                const tone = stars[idx];
                const fill = tone === 'gold' ? '#D9B25C' : tone === 'red' ? '#B53A2E' : '#3FB8B0';
                const edge = tone === 'gold' ? '#8E6D24' : tone === 'red' ? '#7E251D' : '#2A8A85';
                return (
                  <g key={idx} transform={`translate(0, ${yOff})`}>
                    <polygon
                      points={Array.from({length: 16}, (_, i) => {
                        const a = (i * Math.PI) / 8 - Math.PI / 2;
                        const r = i % 2 === 0 ? 7 : 3;
                        return `${(r * Math.cos(a)).toFixed(1)},${(r * Math.sin(a)).toFixed(1)}`;
                      }).join(' ')}
                      fill={fill} stroke={edge} strokeWidth="0.5" strokeLinejoin="round"
                    />
                    <circle r="1.2" fill={edge}/>
                  </g>
                );
              })}
            </g>
          </g>

          {/* horizontal mid-line score band — subtle */}
          <line x1="0" y1={innerH/2} x2={innerW} y2={innerH/2}
            stroke={dark ? 'rgba(255,255,255,0.04)' : 'rgba(0,0,0,0.06)'}
            strokeWidth="0.5"/>
        </svg>

        {/* checkers */}
        {pos.points.map((count, idx) => {
          if (count === 0) return null;
          const side = count > 0 ? 'gold' : 'cobalt';
          const { checkers, overflow, count: total } = stackChecker(idx, count, side);
          const isSelected = selected === idx;
          return (
            <div key={idx}>
              {checkers.map((c, i) => (
                <div key={i} style={{ position: 'absolute', left: c.x, top: c.y, transition: 'all 200ms' }}>
                  <Checker size={c.size} side={side} style={checkerStyle}
                    selected={isSelected && c.top}
                    dark={dark}
                  />
                  {c.top && overflow && (
                    <div style={{
                      position: 'absolute', inset: 0, display: 'flex',
                      alignItems: 'center', justifyContent: 'center',
                      fontFamily: "'Cormorant Garamond', serif",
                      fontSize: 13, fontWeight: 600,
                      color: side === 'gold' ? '#FFF1E8' : '#1E3A8A',
                      textShadow: side === 'gold' ? '0 1px 0 rgba(0,0,0,0.4)' : '0 1px 0 rgba(255,255,255,0.6)',
                    }}>{total}</div>
                  )}
                </div>
              ))}
              <div
                onClick={() => onPointTap && onPointTap(idx)}
                style={{
                  position: 'absolute',
                  left: layout(idx).x - pointW/2, top: layout(idx).row === 'top' ? 0 : innerH - pointH,
                  width: pointW, height: pointH, cursor: 'pointer',
                }}
              />
            </div>
          );
        })}

        {/* dice */}
        <div style={{
          position: 'absolute', left: 9 * pointW + BAR + 8, top: innerH/2 - 18,
          display: 'flex', gap: 6,
          filter: 'drop-shadow(0 3px 4px rgba(0,0,0,0.35))',
        }}>
          <Die value={dice[0]} size={32} used={used[0]}/>
          <Die value={dice[1]} size={32} used={used[1]}/>
        </div>

        {/* doubling cube on bar */}
        {cube.value > 1 && (
          <div style={{ position: 'absolute', left: 6 * pointW + BAR/2 - 16, top: innerH/2 - 16 }}>
            <DoublingCube value={cube.value} size={32}/>
          </div>
        )}
        {cube.value === 1 && (
          <div style={{ position: 'absolute', left: 6 * pointW + BAR/2 - 14, top: 8, opacity: 0.85 }}>
            <DoublingCube value={64} size={28}/>
          </div>
        )}

        {/* bar checkers */}
        {pos.bar.gold > 0 && Array.from({length: pos.bar.gold}, (_, i) => (
          <div key={`bg${i}`} style={{ position: 'absolute', left: 6 * pointW + BAR/2 - 14, top: innerH/2 + 30 + i * 22 }}>
            <Checker size={28} side="gold" style={checkerStyle} dark={dark}/>
          </div>
        ))}
        {pos.bar.cobalt > 0 && Array.from({length: pos.bar.cobalt}, (_, i) => (
          <div key={`bc${i}`} style={{ position: 'absolute', left: 6 * pointW + BAR/2 - 14, top: innerH/2 - 58 - i * 22 }}>
            <Checker size={28} side="cobalt" style={checkerStyle} dark={dark}/>
          </div>
        ))}
      </div>

      {/* bear-off trays */}
      <BearOffTray side="left" off={pos.off.cobalt} W={W} H={H} FRAME={FRAME} TRAY={TRAY} dark={dark} sideColor="cobalt" checkerStyle={checkerStyle}/>
      <BearOffTray side="right" off={pos.off.gold} W={W} H={H} FRAME={FRAME} TRAY={TRAY} dark={dark} sideColor="gold" checkerStyle={checkerStyle}/>
    </div>
  );
}

function BearOffTray({ side, off = 0, W, H, FRAME, TRAY, dark, sideColor, checkerStyle }) {
  const left = side === 'left' ? FRAME : W - FRAME - TRAY;
  return (
    <div style={{
      position: 'absolute', left, top: FRAME, width: TRAY, height: H - FRAME * 2,
      background: dark
        ? 'linear-gradient(180deg, #14090A 0%, #1F1409 50%, #14090A 100%)'
        : 'linear-gradient(180deg, #2A1A10 0%, #3E2A1C 50%, #2A1A10 100%)',
      borderRadius: 4,
      boxShadow: 'inset 0 1px 4px rgba(0,0,0,0.55), inset 0 -1px 2px rgba(0,0,0,0.35), 0 0 0 0.5px rgba(0,0,0,0.4)',
      display: 'flex', flexDirection: 'column-reverse',
      alignItems: 'center', padding: '6px 0', gap: 2,
      overflow: 'hidden',
    }}>
      {/* brass capline */}
      <div style={{
        position: 'absolute', top: 2, left: 4, right: 4, height: 0.5,
        background: '#C9A24C', opacity: 0.55,
      }}/>
      <div style={{
        position: 'absolute', bottom: 2, left: 4, right: 4, height: 0.5,
        background: '#C9A24C', opacity: 0.55,
      }}/>
      {Array.from({length: Math.min(off, 15)}, (_, i) => (
        <div key={i} style={{ width: TRAY - 8, height: 4, borderRadius: 2,
          background: sideColor === 'gold'
            ? 'linear-gradient(180deg, #E26852 0%, #B53A2E 50%, #7E251D 100%)'
            : 'linear-gradient(180deg, #FFFAEC 0%, #EFE6D2 50%, #C7B898 100%)',
          boxShadow: '0 1px 0 rgba(0,0,0,0.35), inset 0 0.5px 0 rgba(255,255,255,0.4)',
        }}/>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Khatam-style border around board — brass + pomegranate inlay
// Two thin hairlines and small khatam stars at each corner.
// ─────────────────────────────────────────────────────────────
function KhatamBorder({ W, H, dark }) {
  const brass = '#C9A24C';
  const brassDeep = '#8E6D24';
  const red = '#B53A2E';
  const corner = (cx, cy) => (
    <g transform={`translate(${cx}, ${cy})`}>
      <polygon
        points={Array.from({length: 16}, (_, i) => {
          const a = (i * Math.PI) / 8 - Math.PI / 2;
          const r = i % 2 === 0 ? 4.5 : 2;
          return `${(r * Math.cos(a)).toFixed(1)},${(r * Math.sin(a)).toFixed(1)}`;
        }).join(' ')}
        fill={brass} stroke={brassDeep} strokeWidth="0.4" strokeLinejoin="round"
      />
      <circle r="0.8" fill={red}/>
    </g>
  );
  return (
    <svg width={W} height={H} style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {/* outer hairline */}
      <rect x="3.5" y="3.5" width={W - 7} height={H - 7} rx="13" ry="13"
        fill="none" stroke={brassDeep} strokeWidth="0.5" opacity="0.6"/>
      {/* mid hairline */}
      <rect x="6.5" y="6.5" width={W - 13} height={H - 13} rx="11" ry="11"
        fill="none" stroke={brass} strokeWidth="0.6" opacity="0.7"/>
      {/* inner red hairline */}
      <rect x="9.5" y="9.5" width={W - 19} height={H - 19} rx="9" ry="9"
        fill="none" stroke={red} strokeWidth="0.5" opacity="0.55"/>
      {/* corner khatams */}
      {corner(7, 7)}
      {corner(W - 7, 7)}
      {corner(7, H - 7)}
      {corner(W - 7, H - 7)}
    </svg>
  );
}

Object.assign(window, { Board, useGameState, START_POSITION });
