import React, { useMemo, useRef } from 'react';
import type { CellEditWrapperProps } from '../../types';
import { SubCellClickContext, type SubCell } from './subCellContext';

/**
 * Stable owner (mounted by EditableCell around the cell content, kept mounted
 * across the edit↔view swap) for the datetime cell's sub-cell click tracking.
 *
 * The View writes the most-recently-clicked sub-cell to a ref via the
 * context; the Edit consumes it on mount to pick the initial sub-edit. This
 * survives the View→Edit transition without resorting to module-global state
 * or a document-level listener.
 */
export function DateTimeEditWrapper({ children }: CellEditWrapperProps) {
  const lastClickedRef = useRef<SubCell | null>(null);

  const tracker = useMemo(
    () => ({
      consume: () => {
        const value = lastClickedRef.current;
        lastClickedRef.current = null;
        return value;
      },
      record: (sub: SubCell) => {
        lastClickedRef.current = sub;
      },
    }),
    [],
  );

  return (
    <SubCellClickContext.Provider value={tracker}>
      {children}
    </SubCellClickContext.Provider>
  );
}
