class ClaudeKeyboard {
  constructor(onSendText, onSendKey) {
    this.onSendText = onSendText;
    this.onSendKey = onSendKey;
    this._active = false;
    this._actionRow = null;
    this._allKeysRow = null;
    this._lastMode = null;
    this._lastIsThinking = false;
    this._lastSelectionOptions = null;
  }

  activate() {
    if (this._active) return;
    this._active = true;
    this._allKeysRow = document.querySelector('.key-row.all-keys');
    if (this._allKeysRow) this._allKeysRow.hidden = true;
    this._createActionRow();
  }

  deactivate() {
    if (!this._active) return;
    this._active = false;
    if (this._allKeysRow) {
      this._allKeysRow.hidden = false;
      this._allKeysRow = null;
    }
    if (this._actionRow && this._actionRow.parentNode) {
      this._actionRow.parentNode.removeChild(this._actionRow);
    }
    this._actionRow = null;
    this._lastMode = null;
    this._lastIsThinking = false;
    this._lastSelectionOptions = null;
  }

  updateContext(doc) {
    if (!this._active || !this._actionRow) return;

    const mode = doc.statusBar ? doc.statusBar.mode : null;
    const lastBlock = this._getLastMeaningfulBlock(doc.blocks);
    const isThinking = lastBlock && lastBlock.type === 'thinking';
    const selectionBlock = this._getLastSelectionBlock(doc.blocks);
    const selectionOptions = selectionBlock ? selectionBlock.options : null;

    // Check if anything changed
    const selKey = selectionOptions ? selectionOptions.map(o => o.key).join(',') : null;
    const lastSelKey = this._lastSelectionOptions ? this._lastSelectionOptions.map(o => o.key).join(',') : null;
    if (mode === this._lastMode && isThinking === this._lastIsThinking && selKey === lastSelKey) return;

    this._lastMode = mode;
    this._lastIsThinking = isThinking;
    this._lastSelectionOptions = selectionOptions;
    this._buildActionRow(mode, isThinking, selectionOptions);
  }

  _getLastMeaningfulBlock(blocks) {
    for (let i = blocks.length - 1; i >= 0; i--) {
      if (blocks[i].type !== 'empty') return blocks[i];
    }
    return null;
  }

  _getLastSelectionBlock(blocks) {
    // Find the last selection block (only if near the end)
    for (let i = blocks.length - 1; i >= 0; i--) {
      const t = blocks[i].type;
      if (t === 'selection') return blocks[i];
      if (t !== 'empty') return null; // stop at first non-empty non-selection
    }
    return null;
  }

  _createActionRow() {
    const row = document.createElement('div');
    row.className = 'key-row cc-action-row';
    const keyboard = document.getElementById('virtual-keyboard');
    const inputRow = keyboard ? keyboard.querySelector('.key-row.input-row') : null;
    if (inputRow) {
      keyboard.insertBefore(row, inputRow);
    }
    this._actionRow = row;
    this._buildActionRow(null, false, null);
  }

  _buildActionRow(mode, isThinking, selectionOptions) {
    if (!this._actionRow) return;
    this._actionRow.innerHTML = '';

    // Mode pill (always present)
    if (mode) {
      const icons  = { plan: '⏸', code: '●', bypass: '⏵' };
      const labels = { plan: 'Plan', code: 'Code', bypass: 'Bypass' };
      const pill = this._makeBtn(
        `cc-action-mode-pill cc-mode-${mode}`,
        icons[mode] || '●',
        labels[mode] || mode,
        () => this.onSendKey('Shift-Tab')
      );
      this._actionRow.appendChild(pill);
    }

    if (selectionOptions && selectionOptions.length > 0) {
      // Selection mode: show option quick-buttons
      for (const opt of selectionOptions) {
        const label = opt.label.length > 12 ? opt.label.slice(0, 12) + '…' : opt.label;
        const btn = this._makeBtn(
          'cc-action-option' + (opt.focused ? ' cc-action-option-focused' : ''),
          opt.index + '.',
          label,
          () => this.onSendText(opt.key + '\n')
        );
        this._actionRow.appendChild(btn);
      }
    } else {
      // Normal mode: Stop + common keys
      const stopBtn = this._makeBtn(
        'cc-action-stop' + (isThinking ? ' cc-action-thinking' : ''),
        '⏹',
        'Stop',
        () => this.onSendKey('Escape')
      );
      this._actionRow.appendChild(stopBtn);

      const keys = [
        { icon: '⇥', label: 'Tab',  key: 'Tab' },
        { icon: '^C', label: 'Int',  key: 'Ctrl-c' },
        { icon: '/',  label: '/',    key: '/' },
        { icon: '◀', label: '',     key: 'ArrowLeft' },
        { icon: '▼', label: '',     key: 'ArrowDown' },
        { icon: '▲', label: '',     key: 'ArrowUp' },
        { icon: '▶', label: '',     key: 'ArrowRight' },
      ];
      for (const k of keys) {
        const btn = this._makeBtn('', k.icon, k.label, () => this.onSendKey(k.key));
        this._actionRow.appendChild(btn);
      }
    }
  }

  _makeBtn(extraClass, icon, label, onClick) {
    const btn = document.createElement('button');
    btn.className = `cc-action-btn ${extraClass}`;

    const iconEl = document.createElement('span');
    iconEl.className = 'cc-action-icon';
    iconEl.textContent = icon;

    btn.appendChild(iconEl);

    if (label) {
      const labelEl = document.createElement('span');
      labelEl.className = 'cc-action-label';
      labelEl.textContent = label;
      btn.appendChild(labelEl);
    }

    btn.addEventListener('click', () => {
      if (navigator.vibrate) navigator.vibrate(8);
      onClick();
    });

    return btn;
  }
}

window.ClaudeKeyboard = ClaudeKeyboard;
