import * as audio from '../../../core/audio.js';

const PIP_POSITIONS = {
  0: [],
  1: [[0, 0]],
  2: [[-1, -1], [1, 1]],
  3: [[-1, -1], [0, 0], [1, 1]],
  4: [[-1, -1], [1, -1], [-1, 1], [1, 1]],
  5: [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]],
  6: [[-1, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [1, 1]]
};

export class DominoHand {
  constructor(container, options = {}) {
    this.container = container;
    this.onTileSelect = options.onTileSelect || null;
    this.onDragStart = options.onDragStart || null;

    this.tiles = [];
    this.validTileIds = new Set();
    this.selectedTileId = null;
    this.disabled = false;
    this._prevTileIds = [];

    container.style.cssText = `
      display:flex;gap:0;padding:8px 6px;
      background:linear-gradient(180deg, #0c1a2a 0%, #0a1420 100%);
      border-top:1px solid rgba(228,172,56,0.1);
      min-height:100px;align-items:flex-end;justify-content:center;
      overflow:visible;position:relative;
    `;
  }

  setTiles(tiles, validTileIds) {
    this.tiles = tiles;
    this.validTileIds = validTileIds;
    this.render();
  }

  setSelected(tileId) {
    this.selectedTileId = tileId;
    this.render();
  }

  clearSelection() {
    this.selectedTileId = null;
    this.render();
  }

  setDisabled(disabled) {
    this.disabled = disabled;
    this.render();
  }

  render() {
    const hand = this.tiles;
    const count = hand.length;

    // Smart sizing: scale tiles to always fit viewport
    const containerW = this.container.clientWidth || 360;
    const maxTileW = 44;
    const minTileW = 30;
    const idealGap = 6;
    const maxHandW = containerW - 16;

    // Calculate tile width to fit all tiles with gaps
    let tileW = Math.min(maxTileW, (maxHandW - idealGap * (count - 1)) / count);
    tileW = Math.max(minTileW, tileW);
    const tileH = tileW * 1.8;
    const gap = Math.min(idealGap, (maxHandW - tileW * count) / Math.max(count - 1, 1));

    // Fan angle for many tiles (like holding cards)
    const useFan = count > 5;
    const maxFanAngle = 2.5; // degrees per tile from center
    const maxLift = 4; // px arc lift at center

    const newIds = hand.map(t => t.id);
    const addedIds = new Set(newIds.filter(id => !this._prevTileIds.includes(id)));
    this._prevTileIds = newIds;

    this.container.innerHTML = hand.map((tile, i) => {
      const playable = this.validTileIds.has(tile.id);
      const selected = this.selectedTileId === tile.id;
      const isNew = addedIds.has(tile.id);

      // Fan geometry
      let angle = 0, lift = 0;
      if (useFan) {
        const center = (count - 1) / 2;
        const offset = i - center;
        angle = offset * maxFanAngle;
        lift = -Math.abs(offset) * (maxLift / (count / 2));
      }

      const transform = selected
        ? `translateY(-16px) scale(1.12)`
        : `rotate(${angle}deg) translateY(${lift}px)`;

      const animDelay = isNew ? `animation:tileSlideIn 0.3s cubic-bezier(0.34,1.56,0.64,1) both;` : '';

      return `
      <div class="dh-tile ${playable ? 'dh-playable' : ''} ${selected ? 'dh-selected' : ''}"
           data-id="${tile.id}" data-idx="${i}"
           style="width:${tileW}px;height:${tileH}px;transform:${transform};margin:0 ${gap/2}px;${this.disabled ? 'pointer-events:none;' : ''}${animDelay}">
        <div class="dh-half dh-top">
          ${this._renderPips(tile.left, tileW)}
        </div>
        <div class="dh-divider"></div>
        <div class="dh-half dh-bottom">
          ${this._renderPips(tile.right, tileW)}
        </div>
      </div>`;
    }).join('');

    this._bindEvents();
  }

  _renderPips(value, tileW) {
    if (value === 0) return '';
    const positions = PIP_POSITIONS[value] || [];
    const halfW = tileW / 2;
    const spread = halfW * 0.45;
    const pipSize = Math.max(3.5, tileW * 0.1);

    return positions.map(([px, py]) => {
      const cx = halfW + px * spread;
      const cy = halfW * 0.82 + py * spread;
      return `<span class="dh-pip" style="left:${cx - pipSize/2}px;top:${cy - pipSize/2}px;width:${pipSize}px;height:${pipSize}px;"></span>`;
    }).join('');
  }

  _bindEvents() {
    const tiles = this.container.querySelectorAll('.dh-tile');
    tiles.forEach(el => {
      let startX = 0, startY = 0, isDrag = false;

      el.addEventListener('pointerdown', (e) => {
        if (this.disabled) return;
        startX = e.clientX;
        startY = e.clientY;
        isDrag = false;
        el.setPointerCapture(e.pointerId);
      });

      el.addEventListener('pointermove', (e) => {
        if (!startX && !startY) return;
        const dx = Math.abs(e.clientX - startX);
        const dy = Math.abs(e.clientY - startY);
        if ((dx > 10 || dy > 10) && !isDrag) {
          isDrag = true;
          const id = el.dataset.id;
          const tile = this.tiles.find(t => t.id === id);
          if (tile && this.validTileIds.has(id)) {
            el.releasePointerCapture(e.pointerId);
            const rect = el.getBoundingClientRect();
            this.onDragStart?.(tile, { x: rect.left + rect.width / 2, y: rect.top, startEvent: e });
          }
        }
      });

      el.addEventListener('pointerup', (e) => {
        if (!isDrag && startX) {
          const id = el.dataset.id;
          const tile = this.tiles.find(t => t.id === id);
          if (tile && this.validTileIds.has(id)) {
            audio.play('click');
            this.onTileSelect?.(tile);
          }
        }
        startX = 0; startY = 0; isDrag = false;
      });

      el.addEventListener('pointercancel', () => { startX = 0; startY = 0; isDrag = false; });
    });
  }

  getStyle() {
    return `
      .dh-tile {
        background: linear-gradient(160deg, #FFFDF5 0%, #F5EFE0 100%);
        border: 1.5px solid #C4AD82;
        border-radius: 6px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;
        padding: 0;
        cursor: pointer;
        transition: transform 0.25s cubic-bezier(0.34,1.56,0.64,1),
                    border-color 0.2s, opacity 0.2s, box-shadow 0.2s,
                    filter 0.2s;
        opacity: 0.55;
        user-select: none;
        touch-action: none;
        flex-shrink: 0;
        box-shadow: 0 3px 8px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.7);
        position: relative;
        transform-origin: center bottom;
        filter: saturate(0.3) brightness(0.85);
      }
      .dh-tile.dh-playable {
        opacity: 1;
        border-color: #E4AC38;
        box-shadow: 0 3px 8px rgba(0,0,0,0.5), 0 0 12px rgba(228,172,56,0.3),
                    inset 0 1px 0 rgba(255,255,255,0.7);
        filter: brightness(1);
      }
      .dh-tile.dh-playable:active {
        transform: translateY(-4px) scale(0.96) !important;
      }
      .dh-tile.dh-selected {
        transform: translateY(-16px) scale(1.12) !important;
        border-color: #E4AC38;
        box-shadow: 0 8px 24px rgba(228,172,56,0.5), 0 0 20px rgba(228,172,56,0.3),
                    inset 0 1px 0 rgba(255,255,255,0.7);
        z-index: 10;
        filter: brightness(1.05);
      }
      @keyframes tileGlow {
        0%, 100% { box-shadow: 0 3px 8px rgba(0,0,0,0.5), 0 0 8px rgba(228,172,56,0.2), inset 0 1px 0 rgba(255,255,255,0.7); }
        50% { box-shadow: 0 3px 8px rgba(0,0,0,0.5), 0 0 16px rgba(228,172,56,0.4), inset 0 1px 0 rgba(255,255,255,0.7); }
      }
      .dh-tile.dh-playable:not(.dh-selected) { animation: tileGlow 2s ease-in-out infinite; }
      .dh-tile.dh-selected { animation: none; }

      @keyframes tileSlideIn {
        from { transform: translateY(40px) scale(0.6); opacity: 0; }
        to { opacity: 1; }
      }

      .dh-half {
        position: relative;
        width: 100%;
        flex: 1;
      }
      .dh-divider {
        width: 78%;
        height: 1.5px;
        background: linear-gradient(90deg, transparent, #B8A080, transparent);
        flex-shrink: 0;
        margin: 0 auto;
      }
      .dh-pip {
        position: absolute;
        border-radius: 50%;
        background: radial-gradient(circle at 35% 35%, #3a3a3a, #0a0a0a);
        box-shadow: inset 0 1px 1px rgba(255,255,255,0.15), 0 0.5px 1px rgba(0,0,0,0.3);
      }
    `;
  }

  destroy() {
    this.container.innerHTML = '';
  }
}
