// Persian Backgammon — design tokens + shared visual primitives
// Exposes: NARD, GirihPattern, GirihTile, Checker, Die, DoublingCube, Icon, Logo

const NARD = {
  // Palette — Persian Heritage moodboard
  c: {
    // Ancient Turquoise (Firuzeh) patina
    turquoise: '#3FB8B0',
    turquoiseDeep: '#2A8A85',
    // Polished Lapis Lazuli
    cobalt: '#1E3A8A',
    cobaltDeep: '#0F2766',
    // Brass / gold accent (kept for inlay)
    gold: '#C9A24C',
    goldDeep: '#8E6D24',
    // Warm Pomegranate Red
    brick: '#B53A2E',
    brickDeep: '#7E251D',
    // Deep Walnut Brown
    walnut: '#3E2A1C',
    walnutMid: '#5C3F28',
    walnutLight: '#8C6240',
    // Charcoal (dark mode)
    charcoal: '#1A130E',
    charcoalDeep: '#100A07',
    // Plaster / stone neutrals
    ivory: '#EFE6D2',
    cream: '#F2EAD7',
    paper: '#F8F2E2',
    line: 'rgba(62,42,28,0.14)',
    lineDk: 'rgba(239,230,210,0.14)',
  },
  // Type scales
  fs: { xs: 11, sm: 13, base: 15, md: 17, lg: 20, xl: 24, xxl: 32, hero: 44 },
  // Spacing
  s: (n) => n * 4,
  // Radius
  r: { sm: 6, md: 10, lg: 14, xl: 22, pill: 9999 },
};

// Theme helpers
const themeFor = (dark) => ({
  bg: dark ? NARD.c.charcoal : NARD.c.cream,
  bg2: dark ? NARD.c.charcoalDeep : NARD.c.paper,
  fg: dark ? NARD.c.ivory : NARD.c.charcoal,
  fgMute: dark ? 'rgba(244,235,217,0.62)' : 'rgba(31,27,22,0.58)',
  fgFaint: dark ? 'rgba(244,235,217,0.38)' : 'rgba(31,27,22,0.34)',
  line: dark ? NARD.c.lineDk : NARD.c.line,
  card: dark ? '#2A2520' : '#FFFFFF',
  cardElev: dark ? '0 2px 10px rgba(0,0,0,0.4)' : '0 2px 10px rgba(31,27,22,0.06), 0 1px 2px rgba(31,27,22,0.04)',
  accent: NARD.c.turquoise,
  accentAlt: NARD.c.gold,
  // Board — Persian Heritage moodboard
  // Light points = polished plaster/lapis ivory, dark points = lapis blue
  // Accent point group = ancient turquoise (firuzeh) patina
  pointA: dark ? '#2A1F14' : NARD.c.ivory,
  pointB: dark ? NARD.c.cobalt : NARD.c.cobalt,
  pointAccent: NARD.c.turquoise,
  boardFrame: dark ? NARD.c.walnut : NARD.c.walnutMid,
  bar: dark ? '#1A0F08' : NARD.c.walnut,
});

// ─────────────────────────────────────────────────────────────
// Girih — geometric strapwork SVG (10-pointed star tessellation)
// Hand-tuned: a single tile that tessellates seamlessly.
// ─────────────────────────────────────────────────────────────
function GirihTile({ size = 120, stroke = '#2BB7B3', fill = 'none', bg = 'transparent', strokeWidth = 1, opacity = 1 }) {
  // Decagonal star with surrounding strapwork
  const cx = size / 2, cy = size / 2;
  const R = size * 0.42, r = size * 0.18;
  // 10-point star
  const star = [];
  for (let i = 0; i < 20; i++) {
    const a = (i * Math.PI) / 10 - Math.PI / 2;
    const rad = i % 2 === 0 ? R : r;
    star.push(`${cx + rad * Math.cos(a)},${cy + rad * Math.sin(a)}`);
  }
  // Outer ring of small hexagons
  const ringR = size * 0.46;
  const sats = [];
  for (let i = 0; i < 10; i++) {
    const a = (i * Math.PI) / 5 - Math.PI / 2;
    sats.push({ x: cx + ringR * Math.cos(a), y: cy + ringR * Math.sin(a) });
  }
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ opacity }}>
      {bg !== 'transparent' && <rect width={size} height={size} fill={bg}/>}
      {/* outer frame */}
      <rect x={0.5} y={0.5} width={size - 1} height={size - 1} fill="none" stroke={stroke} strokeWidth={strokeWidth} opacity={0.4}/>
      {/* connecting lines from star points to corners (strapwork) */}
      {[0,1,2,3,4,5,6,7,8,9].map(i => {
        const a = (i * Math.PI) / 5 - Math.PI / 2;
        const x1 = cx + R * Math.cos(a), y1 = cy + R * Math.sin(a);
        const x2 = cx + (size * 0.62) * Math.cos(a), y2 = cy + (size * 0.62) * Math.sin(a);
        return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={stroke} strokeWidth={strokeWidth} fill="none"/>;
      })}
      {/* small satellite pentagons */}
      {sats.map((p, i) => {
        const pent = [];
        for (let j = 0; j < 5; j++) {
          const a = (j * 2 * Math.PI) / 5 + (i * Math.PI) / 5;
          pent.push(`${p.x + size * 0.07 * Math.cos(a)},${p.y + size * 0.07 * Math.sin(a)}`);
        }
        return <polygon key={i} points={pent.join(' ')} fill={fill} stroke={stroke} strokeWidth={strokeWidth} strokeLinejoin="round"/>;
      })}
      {/* main 10-point star */}
      <polygon points={star.join(' ')} fill={fill} stroke={stroke} strokeWidth={strokeWidth} strokeLinejoin="round"/>
      {/* inner decagon */}
      <polygon
        points={Array.from({length: 10}, (_, i) => {
          const a = (i * Math.PI) / 5 - Math.PI / 2;
          return `${cx + r * 0.7 * Math.cos(a)},${cy + r * 0.7 * Math.sin(a)}`;
        }).join(' ')}
        fill="none" stroke={stroke} strokeWidth={strokeWidth * 0.7}
      />
    </svg>
  );
}

// Tiled background pattern via repeating SVG dataURL
function GirihPattern({ size = 120, color = '#2BB7B3', opacity = 0.06, style = {} }) {
  const svg = encodeURIComponent(`
<svg xmlns='http://www.w3.org/2000/svg' width='${size}' height='${size}' viewBox='0 0 ${size} ${size}'>
  ${girihPathString(size, color)}
</svg>`);
  return (
    <div style={{
      position: 'absolute', inset: 0,
      backgroundImage: `url("data:image/svg+xml,${svg}")`,
      backgroundSize: `${size}px ${size}px`,
      opacity, pointerEvents: 'none', ...style,
    }} />
  );
}

function girihPathString(size, color) {
  const cx = size / 2, cy = size / 2;
  const R = size * 0.4, r = size * 0.16;
  const star = [];
  for (let i = 0; i < 20; i++) {
    const a = (i * Math.PI) / 10 - Math.PI / 2;
    const rad = i % 2 === 0 ? R : r;
    star.push(`${(cx + rad * Math.cos(a)).toFixed(2)},${(cy + rad * Math.sin(a)).toFixed(2)}`);
  }
  let lines = '';
  for (let i = 0; i < 10; i++) {
    const a = (i * Math.PI) / 5 - Math.PI / 2;
    const x1 = cx + R * Math.cos(a), y1 = cy + R * Math.sin(a);
    const x2 = cx + (size * 0.55) * Math.cos(a), y2 = cy + (size * 0.55) * Math.sin(a);
    lines += `<line x1='${x1.toFixed(2)}' y1='${y1.toFixed(2)}' x2='${x2.toFixed(2)}' y2='${y2.toFixed(2)}' stroke='${color}' stroke-width='1' fill='none'/>`;
  }
  return `
    <polygon points='${star.join(' ')}' fill='none' stroke='${color}' stroke-width='1' stroke-linejoin='round'/>
    ${lines}
    <circle cx='${cx}' cy='${cy}' r='${r * 0.5}' fill='none' stroke='${color}' stroke-width='1'/>
  `;
}

// ─────────────────────────────────────────────────────────────
// Checker — three styles
//   khatam: radial inlay rings + center rosette
//   minimal: solid disc with thin ring + monogram
//   carved: raised concentric grooves
// ─────────────────────────────────────────────────────────────
function Checker({ size = 38, side = 'gold', style = 'khatam', selected = false, captured = false, dark = false }) {
  const isGold = side === 'gold';
  // "gold" side = warm pomegranate red (moodboard); "cobalt" side = ivory plaster with cobalt monogram
  const mainA = isGold ? '#C84638' : '#F2EAD7';
  const mainB = isGold ? '#7E251D' : '#C7B898';
  const inlay = isGold ? '#F2EAD7' : '#1E3A8A';
  const opacity = captured ? 0.55 : 1;
  const sz = captured ? size * 0.78 : size;

  return (
    <div style={{
      width: sz, height: sz, position: 'relative', opacity,
      filter: selected ? `drop-shadow(0 0 8px ${isGold ? '#E26C5C' : '#7AAEFF'})` : 'none',
      transition: 'filter 160ms',
    }}>
      <svg width={sz} height={sz} viewBox="0 0 100 100" style={{ display: 'block' }}>
        <defs>
          <radialGradient id={`bg-${side}-${style}`} cx="38%" cy="34%" r="70%">
            <stop offset="0%" stopColor={isGold ? '#E26852' : '#FFFAEC'}/>
            <stop offset="55%" stopColor={mainA}/>
            <stop offset="100%" stopColor={mainB}/>
          </radialGradient>
          <radialGradient id={`hl-${side}-${style}`} cx="35%" cy="28%" r="40%">
            <stop offset="0%" stopColor="rgba(255,255,255,0.6)"/>
            <stop offset="100%" stopColor="rgba(255,255,255,0)"/>
          </radialGradient>
        </defs>
        {/* base disc */}
        <circle cx="50" cy="50" r="48" fill={`url(#bg-${side}-${style})`} stroke={mainB} strokeWidth="0.8"/>

        {style === 'khatam' && <>
          {/* outer ring */}
          <circle cx="50" cy="50" r="44" fill="none" stroke={inlay} strokeWidth="0.6" opacity="0.6"/>
          <circle cx="50" cy="50" r="40" fill="none" stroke={mainB} strokeWidth="0.4" opacity="0.7"/>
          {/* 8-point khatam rosette */}
          {Array.from({length: 16}, (_, i) => {
            const a = (i * Math.PI) / 8;
            const rIn = 6, rOut = i % 2 === 0 ? 18 : 11;
            return `${50 + rOut * Math.cos(a)},${50 + rOut * Math.sin(a)}`;
          }) && (
            <polygon
              points={Array.from({length: 16}, (_, i) => {
                const a = (i * Math.PI) / 8 - Math.PI / 2;
                const rOut = i % 2 === 0 ? 18 : 10;
                return `${(50 + rOut * Math.cos(a)).toFixed(1)},${(50 + rOut * Math.sin(a)).toFixed(1)}`;
              }).join(' ')}
              fill={inlay} opacity="0.85"
              stroke={mainB} strokeWidth="0.4"
            />
          )}
          {/* tiny radiating wedges between star points */}
          {Array.from({length: 8}, (_, i) => {
            const a = (i * Math.PI) / 4 - Math.PI / 2;
            const x1 = 50 + 22 * Math.cos(a), y1 = 50 + 22 * Math.sin(a);
            const x2 = 50 + 36 * Math.cos(a), y2 = 50 + 36 * Math.sin(a);
            return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={inlay} strokeWidth="0.7" opacity="0.5"/>;
          })}
          {/* center dot */}
          <circle cx="50" cy="50" r="3" fill={mainB}/>
          <circle cx="50" cy="50" r="1.4" fill={inlay} opacity="0.9"/>
        </>}

        {style === 'minimal' && <>
          <circle cx="50" cy="50" r="40" fill="none" stroke={inlay} strokeWidth="0.8" opacity="0.5"/>
          {/* simple monogram — N (Nard) for gold, persian-ish dot for cobalt */}
          {isGold ? (
            <text x="50" y="62" textAnchor="middle" fontFamily="'Cormorant Garamond', serif" fontSize="36" fontWeight="500" fill={inlay} opacity="0.85">N</text>
          ) : (
            <g opacity="0.85" fill={inlay}>
              <circle cx="50" cy="50" r="5"/>
              <circle cx="50" cy="32" r="2"/>
              <circle cx="50" cy="68" r="2"/>
              <circle cx="32" cy="50" r="2"/>
              <circle cx="68" cy="50" r="2"/>
            </g>
          )}
        </>}

        {style === 'carved' && <>
          {[42, 34, 26, 18].map((r, i) => (
            <circle key={i} cx="50" cy="50" r={r} fill="none"
              stroke={i % 2 === 0 ? mainB : inlay}
              strokeWidth={i % 2 === 0 ? 0.6 : 0.5}
              opacity={0.55} />
          ))}
          {/* center brass nail */}
          <circle cx="50" cy="50" r="6" fill={mainB}/>
          <circle cx="50" cy="50" r="3" fill={inlay}/>
          <circle cx="50" cy="50" r="1" fill={mainB}/>
        </>}

        {/* highlight on top */}
        <ellipse cx="38" cy="32" rx="22" ry="12" fill={`url(#hl-${side}-${style})`} opacity="0.7"/>
      </svg>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Die — ivory with cobalt pips
// ─────────────────────────────────────────────────────────────
const PIPS = {
  1: [[0.5,0.5]],
  2: [[0.28,0.28],[0.72,0.72]],
  3: [[0.28,0.28],[0.5,0.5],[0.72,0.72]],
  4: [[0.28,0.28],[0.72,0.28],[0.28,0.72],[0.72,0.72]],
  5: [[0.28,0.28],[0.72,0.28],[0.5,0.5],[0.28,0.72],[0.72,0.72]],
  6: [[0.28,0.25],[0.72,0.25],[0.28,0.5],[0.72,0.5],[0.28,0.75],[0.72,0.75]],
};
function Die({ value = 1, size = 44, used = false, rolling = false }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: size * 0.18,
      background: 'linear-gradient(155deg, #FFFCF1 0%, #F4EBD9 60%, #E5D6B5 100%)',
      boxShadow: '0 2px 5px rgba(0,0,0,0.18), inset 0 1px 0 rgba(255,255,255,0.6), inset 0 -1px 0 rgba(0,0,0,0.08)',
      position: 'relative', opacity: used ? 0.45 : 1,
      transform: rolling ? 'rotate(-8deg)' : 'none',
      transition: 'transform 200ms, opacity 200ms',
      border: '0.5px solid rgba(0,0,0,0.08)',
    }}>
      {PIPS[value].map(([x, y], i) => (
        <div key={i} style={{
          position: 'absolute',
          left: `${x * 100}%`, top: `${y * 100}%`,
          transform: 'translate(-50%, -50%)',
          width: size * 0.16, height: size * 0.16, borderRadius: '50%',
          background: '#1E3A8A',
          boxShadow: 'inset 0 1px 1px rgba(0,0,0,0.4)',
        }}/>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Doubling cube — brass with engraved numeral
// ─────────────────────────────────────────────────────────────
function DoublingCube({ value = 64, size = 40 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: size * 0.16,
      background: 'linear-gradient(155deg, #E8C679 0%, #C9A04A 50%, #8B6920 100%)',
      boxShadow: '0 2px 4px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.45), inset 0 -1px 0 rgba(0,0,0,0.2)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: "'Cormorant Garamond', serif",
      fontSize: size * 0.5, fontWeight: 600,
      color: '#1F1B16',
      textShadow: '0 1px 0 rgba(255,255,255,0.3)',
      border: '0.5px solid rgba(31,27,22,0.3)',
    }}>{value}</div>
  );
}

// ─────────────────────────────────────────────────────────────
// Icons — line-art, 24x24, single stroke color
// ─────────────────────────────────────────────────────────────
function Icon({ name, size = 22, color = 'currentColor', strokeWidth = 1.6 }) {
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'back': return <svg {...p}><path d="M15 5l-7 7 7 7"/></svg>;
    case 'gear': return <svg {...p}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/></svg>;
    case 'undo': return <svg {...p}><path d="M9 14l-4-4 4-4"/><path d="M5 10h9a5 5 0 010 10h-3"/></svg>;
    case 'sound': return <svg {...p}><path d="M11 5L6 9H3v6h3l5 4V5z"/><path d="M15.5 8.5a5 5 0 010 7"/><path d="M18 6a9 9 0 010 12"/></svg>;
    case 'mute': return <svg {...p}><path d="M11 5L6 9H3v6h3l5 4V5z"/><path d="M22 9l-6 6M16 9l6 6"/></svg>;
    case 'music': return <svg {...p}><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>;
    case 'haptic': return <svg {...p}><path d="M12 4v3"/><path d="M12 17v3"/><path d="M4 12h3"/><path d="M17 12h3"/><path d="M6.3 6.3l2.1 2.1"/><path d="M15.6 15.6l2.1 2.1"/><path d="M6.3 17.7l2.1-2.1"/><path d="M15.6 8.4l2.1-2.1"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'share': return <svg {...p}><path d="M12 3v13"/><path d="M7 8l5-5 5 5"/><path d="M5 21h14"/></svg>;
    case 'info': return <svg {...p}><circle cx="12" cy="12" r="9"/><path d="M12 11v5"/><circle cx="12" cy="8" r="0.6" fill={color}/></svg>;
    case 'lock': return <svg {...p}><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 018 0v4"/></svg>;
    case 'check': return <svg {...p}><path d="M5 12l5 5L20 7"/></svg>;
    case 'chevron': return <svg {...p}><path d="M9 6l6 6-6 6"/></svg>;
    case 'play': return <svg {...p} fill={color}><path d="M7 4l13 8-13 8z"/></svg>;
    case 'home': return <svg {...p}><path d="M4 11l8-7 8 7v9a1 1 0 01-1 1h-4v-7h-6v7H5a1 1 0 01-1-1z"/></svg>;
    case 'stats': return <svg {...p}><path d="M4 20V10"/><path d="M10 20V4"/><path d="M16 20v-8"/><path d="M22 20H2"/></svg>;
    case 'book': return <svg {...p}><path d="M4 5a2 2 0 012-2h13v16H6a2 2 0 00-2 2V5z"/><path d="M4 19a2 2 0 012-2h13"/></svg>;
    case 'trophy': return <svg {...p}><path d="M8 4h8v5a4 4 0 01-8 0V4z"/><path d="M16 6h3v2a3 3 0 01-3 3"/><path d="M8 6H5v2a3 3 0 003 3"/><path d="M9 14h6l-1 5H10z"/><path d="M8 21h8"/></svg>;
    default: return null;
  }
}

// ─────────────────────────────────────────────────────────────
// Logo — Persian geometric monogram (10-pt star + interlace)
// ─────────────────────────────────────────────────────────────
function Logo({ size = 80, color = '#2BB7B3', accent = '#D4A24C' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100">
      <defs>
        <linearGradient id="logo-fill" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor={color}/>
          <stop offset="100%" stopColor={accent}/>
        </linearGradient>
      </defs>
      {/* outer ring */}
      <circle cx="50" cy="50" r="46" fill="none" stroke={color} strokeWidth="1.2" opacity="0.4"/>
      <circle cx="50" cy="50" r="42" fill="none" stroke={color} strokeWidth="1.6"/>
      {/* 10-point star */}
      <polygon
        points={Array.from({length: 20}, (_, i) => {
          const a = (i * Math.PI) / 10 - Math.PI / 2;
          const r = i % 2 === 0 ? 36 : 16;
          return `${(50 + r * Math.cos(a)).toFixed(1)},${(50 + r * Math.sin(a)).toFixed(1)}`;
        }).join(' ')}
        fill="none" stroke="url(#logo-fill)" strokeWidth="1.8" strokeLinejoin="round"
      />
      {/* inner pentagon */}
      <polygon
        points={Array.from({length: 5}, (_, i) => {
          const a = (i * 2 * Math.PI) / 5 - Math.PI / 2;
          return `${(50 + 12 * Math.cos(a)).toFixed(1)},${(50 + 12 * Math.sin(a)).toFixed(1)}`;
        }).join(' ')}
        fill="none" stroke={accent} strokeWidth="1.4"
      />
      {/* center dot */}
      <circle cx="50" cy="50" r="3" fill={accent}/>
    </svg>
  );
}

Object.assign(window, { NARD, themeFor, GirihPattern, GirihTile, Checker, Die, DoublingCube, Icon, Logo });
