// tc-ui.jsx — small shared UI atoms used across panels.
const { useState, useRef, useEffect } = React;

// Labeled field wrapper
function Field({ label, hint, children, className = '' }) {
  return (
    <label className={'field ' + className}>
      <span className="field-label">{label}{hint && <em className="field-hint">{hint}</em>}</span>
      {children}
    </label>
  );
}

function TextInput({ value, onChange, placeholder, mono, maxLength, list }) {
  return (
    <input
      type="text"
      className={'tin' + (mono ? ' mono' : '')}
      value={value || ''}
      placeholder={placeholder}
      maxLength={maxLength}
      list={list}
      onChange={(e) => onChange(e.target.value)}
    />
  );
}

function Section({ title, right, children, defaultOpen = true, collapsible = false }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <section className="sect">
      <div className="sect-head" onClick={collapsible ? () => setOpen(o => !o) : undefined}
           style={{ cursor: collapsible ? 'pointer' : 'default' }}>
        <h3 className="sect-title">
          {collapsible && <span className={'caret' + (open ? ' open' : '')}>▸</span>}
          {title}
        </h3>
        {right}
      </div>
      {open && <div className="sect-body">{children}</div>}
    </section>
  );
}

function Button({ children, onClick, variant = 'default', size, disabled, type = 'button', title }) {
  return (
    <button type={type} className={`btn btn-${variant}${size ? ' btn-' + size : ''}`}
            onClick={onClick} disabled={disabled} title={title}>
      {children}
    </button>
  );
}

function Modal({ open, onClose, title, children, footer, width = 560 }) {
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="modal-scrim" onMouseDown={onClose}>
      <div className="modal" style={{ width }} onMouseDown={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h2>{title}</h2>
          <button className="modal-x" onClick={onClose} aria-label="Close">✕</button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

function Toast({ msg }) {
  if (!msg) return null;
  return <div className="toast">{msg}</div>;
}

Object.assign(window, { Field, TextInput, Section, Button, Modal, Toast });
