'use client';

/* eslint-disable @typescript-eslint/no-explicit-any */
import { createElement, useEffect, useRef } from 'react';
import type React from 'react';
import { InvalidField } from '@/TailwindPlay/Fields/Invalid.js';
import { TailwindPlayCommonParams } from '@/TailwindPlay/Fields/types.js';
import { extractHusarData } from '@/TailwindPlay/shared/extract.js';
import { isValidHtmlComponent } from '@/TailwindPlay/shared/constants.js';

export const FieldScript: React.FC<TailwindPlayCommonParams> = (props) => {
  const containerRef = useRef<HTMLElement | null>(null);
  const { v, attributes } = extractHusarData<string>(props);

  useEffect(() => {
    const container = containerRef.current;
    if (!container || !v) return;

    const mountedScripts: HTMLScriptElement[] = [];
    const scriptNodes = Array.from(container.querySelectorAll('script'));

    scriptNodes.forEach((scriptNode) => {
      const executableScript = document.createElement('script');
      Array.from(scriptNode.attributes).forEach((attribute) => {
        executableScript.setAttribute(attribute.name, attribute.value);
      });
      executableScript.text = scriptNode.textContent || '';
      scriptNode.replaceWith(executableScript);
      mountedScripts.push(executableScript);
    });

    if (!scriptNodes.length && v.trim() && !v.trim().startsWith('<')) {
      const executableScript = document.createElement('script');
      executableScript.text = v;
      container.appendChild(executableScript);
      mountedScripts.push(executableScript);
    }

    return () => {
      mountedScripts.forEach((scriptNode) => scriptNode.remove());
    };
  }, [v]);

  if (typeof v !== 'string' && v !== null && typeof v !== 'undefined') return <InvalidField />;

  const tag = isValidHtmlComponent(attributes);
  const html = v?.trim().startsWith('<') ? v : '';

  return createElement(tag, {
    ...attributes,
    ref: containerRef,
    dangerouslySetInnerHTML: { __html: html },
  });
};
