import { TouchGuard } from '@sigx/lynx-gestures';
import { component, compound, type Define } from '@sigx/lynx';

export type ModalProps =
  & Define.Prop<'open', boolean, false>
  & Define.Prop<'onClose', () => void, false>
  & Define.Prop<'class', string, false>
  & Define.Slot<'default'>;

const _Modal = component<ModalProps>(({ props, slots }) => {
  return () => {
    // Closed state renders a zero-size, out-of-flow placeholder (not
    // display:none — Lynx can leak unstyled text paint through display:none
    // overlays in some builds; zero-size + absolute is the safer shape, same
    // as StatusBarSync). The modal content itself is fully unmounted.
    if (!props.open) {
      return <view style={{ position: 'absolute', width: '0px', height: '0px', opacity: 0 }} />;
    }
    return (
      <TouchGuard
        class="hero-modal-overlay"
        // Native touch consumption (#787).
        onTap={() => { props.onClose?.(); }}
      >
        <view
          class={`hero-modal-box${props.class ? ' ' + props.class : ''}`}
          // catchtap (Lynx catchEvent) actually stops the bubble — there is
          // no working e.stopPropagation() in this runtime (#260), so the
          // old bindtap guard was a silent no-op and any tap inside the box
          // bubbled to the overlay's close handler.
          catchtap={() => {}}
        >
          {slots.default?.()}
        </view>
      </TouchGuard>
    );
  };
});

type SectionProps = Define.Prop<'class', string, false> & Define.Slot<'default'>;

const ModalHeader = component<SectionProps>(({ props, slots }) => {
  return () => (
    <view class={`hero-modal-header${props.class ? ' ' + props.class : ''}`}>
      {slots.default?.()}
    </view>
  );
});

const ModalBody = component<SectionProps>(({ props, slots }) => {
  return () => (
    <view class={`hero-modal-body${props.class ? ' ' + props.class : ''}`}>
      {slots.default?.()}
    </view>
  );
});

const ModalActions = component<SectionProps>(({ props, slots }) => {
  return () => (
    <view class={`hero-modal-actions${props.class ? ' ' + props.class : ''}`}>
      {slots.default?.()}
    </view>
  );
});

export const Modal = compound(_Modal, {
  Header: ModalHeader,
  Body: ModalBody,
  Actions: ModalActions,
});
