'use client';

import { Fragment, type ReactNode } from 'react';
import { cn } from '@djangocfg/ui-core/lib';

import { useTreeContext } from '../context/TreeContext';
import type { FlatRow, TreeRowRenderProps, TreeRowSlot } from '../types';
import { TreeRow } from './TreeRow';
import { TreeEmpty } from './TreeEmpty';

export interface TreeContentProps<T> {
  /** Custom row renderer; falls back to <TreeRow />. */
  children?: TreeRowSlot<T>;
  className?: string;
  /** Override aria-label for the container. */
  ariaLabel?: string;
}

export function TreeContent<T>({ children, className, ariaLabel }: TreeContentProps<T>) {
  const { flatRows, labels, selected, focused, matchingIds } = useTreeContext<T>();

  if (flatRows.length === 0) {
    return <TreeEmpty>{labels.empty}</TreeEmpty>;
  }

  return (
    <div
      role="tree"
      aria-label={ariaLabel ?? labels.ariaLabel}
      className={cn('relative flex flex-col py-1', className)}
    >
      {flatRows.map((row: FlatRow<T>) => {
        const slot: TreeRowRenderProps<T> = {
          node: row.node,
          level: row.level,
          isSelected: selected.has(row.node.id),
          isExpanded: row.isExpanded,
          isFocused: focused === row.node.id,
          isFolder: row.isFolder,
          isLoading: row.isLoading,
          isMatchingSearch: matchingIds.has(row.node.id),
        };
        const node: ReactNode = children ? children(slot) : <TreeRow row={row} />;
        return <Fragment key={row.node.id}>{node}</Fragment>;
      })}
    </div>
  );
}
