'use client';

import { cloneElement, isValidElement, ReactElement } from 'react';
import { useIsDemoSession } from '@client/hooks/useIsDemoSession';

interface DemoDisabledProps {
  children: ReactElement<{
    disabled?: boolean;
    title?: string;
    'aria-disabled'?: boolean;
    onClick?: (e: React.MouseEvent) => void;
  }>;
  tooltip?: string;
  className?: string;
}

/**
 * Wraps a single button-like child. When the active session is a demo user,
 * sets `disabled` + a tooltip so the action is visibly inert before the user
 * even clicks. Renders children unchanged for real users.
 *
 * If `className` is provided, the child is wrapped in a `<span>` so that
 * layout classes (e.g. `flex-1`) work consistently across demo and real
 * sessions.
 */
export default function DemoDisabled({ children, tooltip = 'Demo mode is read-only', className }: DemoDisabledProps) {
  const isDemo = useIsDemoSession();
  if (!isDemo || !isValidElement(children)) {
    if (className) return <span className={className}>{children}</span>;
    return <>{children}</>;
  }
  const disabledChild = cloneElement(children, {
    disabled: true,
    'aria-disabled': true,
    onClick: (e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();
    },
  });
  // Wrap in a non-disabled span that owns the tooltip — most browsers do not
  // fire `title` tooltips on disabled controls, so the wrapper handles it.
  return (
    <span
      title={tooltip}
      aria-label={tooltip}
      className={className ? `${className} inline-flex` : 'inline-flex'}
      style={{ cursor: 'not-allowed' }}
    >
      {disabledChild}
    </span>
  );
}
