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

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;

    container.style.cssText = `
      display:flex;gap:2px;padding:10px 6px;overflow-x:auto;
      background:linear-gradient(180deg,#0a2a0e 0%,#0d3311 100%);
      border-top:1px solid rgba(255,255,255,0.08);
      min-height:96px;align-items:center;justify-content:center;
      flex-wrap:wrap;scroll-snap-type:x proximity;
      -webkit-overflow-scrolling:touch;
    `;
  }

  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;
    this.container.innerHTML = hand.map((tile, i) => {
      const playable = this.validTileIds.has(tile.id);
      const selected = this.selectedTileId === tile.id;
      const overlap = i > 0 ? 'margin-left:-6px;' : '';

      return `
      <div class="dh-tile ${playable ? 'dh-playable' : ''} ${selected ? 'dh-selected' : ''}"
           data-id="${tile.id}" data-idx="${i}"
           style="${overlap}scroll-snap-align:center;${this.disabled ? 'pointer-events:none;' : ''}">
        <div class="dh-top">${this._renderPipGrid(tile.left)}</div>
        <div class="dh-divider"></div>
        <div class="dh-bottom">${this._renderPipGrid(tile.right)}</div>
      </div>`;
    }).join('');

    this._bindEvents();
  }

  _renderPipGrid(value) {
    if (value === 0) return '';
    let dots = '';
    for (let i = 0; i < value; i++) {
      dots += '<span class="dh-pip"></span>';
    }
    return dots;
  }

  _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 {
        width:40px;height:70px;
        background:#fffff0;
        border:2px solid #555;
        border-radius:6px;
        display:flex;flex-direction:column;
        align-items:center;justify-content:space-between;
        padding:5px 4px;
        cursor:pointer;
        transition:transform 0.15s cubic-bezier(0.34,1.56,0.64,1),
                   border-color 0.15s,opacity 0.15s,box-shadow 0.15s;
        opacity:0.45;
        user-select:none;
        touch-action:none;
        flex-shrink:0;
      }
      .dh-tile.dh-playable {
        opacity:1;
        border-color:#4ade80;
        box-shadow:0 0 8px rgba(74,222,128,0.25);
      }
      .dh-tile.dh-playable:active { transform:scale(0.94); }
      .dh-tile.dh-selected {
        transform:translateY(-12px) scale(1.05);
        border-color:#10b981;
        box-shadow:0 6px 16px rgba(16,185,129,0.4);
      }
      @keyframes tileGlow {
        0%,100% { box-shadow:0 0 6px rgba(74,222,128,0.2); }
        50% { box-shadow:0 0 14px rgba(74,222,128,0.5); }
      }
      .dh-tile.dh-playable { animation:tileGlow 2s ease-in-out infinite; }
      .dh-tile.dh-selected { animation:none; }
      .dh-divider { width:80%;height:1px;background:#bbb;flex-shrink:0; }
      .dh-top, .dh-bottom {
        display:flex;flex-wrap:wrap;
        width:22px;height:22px;
        align-items:center;justify-content:center;
        gap:1px;
      }
      .dh-pip {
        width:5px;height:5px;
        border-radius:50%;
        background:#1a1a1a;
      }
    `;
  }

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