// atoms.jsx — small reusable UI primitives shared across screens

// iOS Safari ignores synchronous select() on number inputs; defer to next tick.
function selectOnFocus(e) {
  const el = e.target;
  setTimeout(() => { try { el.select(); } catch (_) {} }, 0);
}

function Row({ children, onClick, className }) {
  return <div className={"row" + (className ? " " + className : "")} onClick={onClick}>{children}</div>;
}

function Segment({ options, value, onChange }) {
  return (
    <div className="seg">
      {options.map((o) =>
      <button key={o.value} type="button"
      className={"seg-btn" + (value === o.value ? " is-on" : "")}
      onClick={() => onChange(o.value)}>{o.label}</button>
      )}
    </div>);
}

function Sheet({ open, onClose, title, children, footer }) {
  if (!open) return null;
  return (
    <div className="sheet-backdrop" onClick={onClose}>
      <div className="sheet" onClick={(e) => e.stopPropagation()}>
        <div className="sheet-grab"></div>
        {title && <div className="sheet-title">{title}</div>}
        <div className="sheet-body">{children}</div>
        {footer && <div className="sheet-footer">{footer}</div>}
      </div>
    </div>);
}

// Full-screen photo preview overlay. `index === null` (or undefined) closes it.
// onChange is called with the new index when the user navigates.
function PhotoPreview({ photos, index, onClose, onChange }) {
  if (index == null || !photos || photos.length === 0) return null;
  const safe = Math.max(0, Math.min(index, photos.length - 1));
  const prev = () => onChange(safe === 0 ? photos.length - 1 : safe - 1);
  const next = () => onChange((safe + 1) % photos.length);
  return (
    <div className="photo-preview" onClick={onClose}>
      <button className="photo-preview-close" onClick={(e) => { e.stopPropagation(); onClose(); }} aria-label="關閉">×</button>
      <img className="photo-preview-img" src={photos[safe]} onClick={(e) => e.stopPropagation()} alt="" />
      {photos.length > 1 && (
        <>
          <button className="photo-preview-nav left"  onClick={(e) => { e.stopPropagation(); prev(); }} aria-label="上一張">‹</button>
          <button className="photo-preview-nav right" onClick={(e) => { e.stopPropagation(); next(); }} aria-label="下一張">›</button>
          <div className="photo-preview-dots" onClick={(e) => e.stopPropagation()}>
            {photos.map((_, i) => <span key={i} className={i === safe ? "is-on" : ""} />)}
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, { Row, Segment, Sheet, PhotoPreview, selectOnFocus });
