import type { HTMLAttributes, ReactNode, ElementType } from 'react'
import type { SpaceToken } from './tokens.js'

export interface SplitProps extends HTMLAttributes<HTMLElement> {
  /**
   * Fraction of the container the primary pane should take, expressed as
   * a CSS fraction string. Defaults to `'2fr 1fr'` (primary 2x sidebar).
   *
   * @example
   *   <Split fraction="3fr 1fr">         // 75% / 25%
   *   <Split fraction="minmax(0, 1fr) 320px">  // fluid + fixed sidebar
   */
  fraction?: string
  /** Gap between the two panes. */
  space?: SpaceToken
  /**
   * Stack vertically at this breakpoint and below. Pass `false` to never
   * stack. Defaults to `md` (stacks on screens narrower than 768px).
   */
  stackBelow?: 'sm' | 'md' | 'lg' | 'xl' | false
  /** Reverse the order of children (sidebar first instead of second). */
  reverse?: boolean
  /** Render as a different element. */
  as?: ElementType
  children: [ReactNode, ReactNode]
}

const STACK_BELOW_CLASS = {
  sm: 'sm:grid',
  md: 'md:grid',
  lg: 'lg:grid',
  xl: 'xl:grid',
} as const

/**
 * Two-pane split layout (primary + sidebar/aside) that collapses to a
 * stacked layout below a configurable breakpoint. Use this for the
 * document editor (`<Split fraction="minmax(0, 1fr) 320px">`), settings
 * pages with a navigation rail, etc. — anywhere two panes need to live
 * side-by-side at desktop widths and stack on mobile.
 */
export function Split({
  fraction = '2fr 1fr',
  space = '6',
  stackBelow = 'md',
  reverse,
  as: Component = 'div',
  className = '',
  style,
  children,
  ...rest
}: SplitProps) {
  const stackClass =
    stackBelow === false ? 'grid' : `flex flex-col ${STACK_BELOW_CLASS[stackBelow]}`
  const classes = [stackClass, `gap-${space}`, reverse ? 'flex-col-reverse' : '', className]
    .filter(Boolean)
    .join(' ')

  return (
    <Component
      className={classes}
      style={{
        ...(stackBelow === false
          ? { gridTemplateColumns: fraction }
          : { gridTemplateColumns: fraction }),
        ...style,
      }}
      {...rest}
    >
      {children}
    </Component>
  )
}
