import type { FunctionalComponent } from 'preact';
import { useEffect, useState } from 'preact/hooks';
import { registerModule, type AsukaModuleComponent } from '../../core/modules';

const TextFormattingModule: AsukaModuleComponent = (props) => {
  const engineKind = props.context.getEngine?.()?.kind ?? 'fabric';
  const [Component, setComponent] = useState<FunctionalComponent<any> | null>(null);

  useEffect(() => {
    let disposed = false;
    setComponent(null);
    const load = engineKind === '3d'
      ? import('./TextFormatting3DModule')
      : import('./TextFormattingFabricModule');
    void load.then((module) => {
      if (!disposed) setComponent(() => module.default as FunctionalComponent<any>);
    });
    return () => { disposed = true; };
  }, [engineKind]);

  return Component
    ? <Component {...props} />
    : <div class="ask-p-3 ask-text-[12px] ask-text-textMuted">Loading...</div>;
};

registerModule({
  id: 'text-formatting',
  label: 'Text',
  icon: 'formatting',
  displayMode: 'floating',
  supportedEngines: ['fabric', '3d'],
  requiredCapabilities: ['objects'],
  render: TextFormattingModule,
});

export default TextFormattingModule;
