import { h } from 'preact';
import { wsClient } from '../lib/ws';
import type { Widget } from '../lib/types';

interface Props { widget: Widget; onContextMenu?: (e: MouseEvent) => void; }

export default function Button({ widget, onContextMenu }: Props) {
  const sigRef = widget.signals[0];
  const label = widget.options['label'] ?? 'Button';
  const valueOpt = widget.options['value'] ?? '1';
  const confirm = widget.options['confirm'] === 'true';

  function handleClick() {
    if (!sigRef) return;
    const parsed = parseFloat(valueOpt);
    const val = isNaN(parsed) ? valueOpt : parsed;
    const doWrite = () => wsClient.write(sigRef, val);
    if (confirm) {
      if (window.confirm(`Send ${label}?`)) doWrite();
    } else {
      doWrite();
    }
  }

  return (
    <div
      class="button-widget"
      style={`left:${widget.x}px;top:${widget.y}px;width:${widget.w}px;height:${widget.h}px;`}
      onContextMenu={onContextMenu}
    >
      <button class="btn" onClick={handleClick}>{label}</button>
    </div>
  );
}
