<svelte:options customElement={{
  tag: "tinyflow-component",
  shadow: "none",
  props: {
		options: { type: 'Object', attribute: 'options' },
		onInit: { type: 'Object', attribute: 'on-init' }
	},
}} />

<script lang="ts">
  import {SvelteFlowProvider, type useSvelteFlow} from '@xyflow/svelte';
  import TinyflowCore from './TinyflowCore.svelte';
  import {store} from '#store/stores.svelte';
  import type {TinyflowData, TinyflowOptions} from '#types';
  import {setContext} from 'svelte';
  import {createTinyflowNodeNormalizer} from '../utils/nodeInteraction';

  const props = $props<{
        options: TinyflowOptions,
        onInit: (svelteFlow: ReturnType<typeof useSvelteFlow>) => void,
    }>();

    const parseData = (source: TinyflowOptions['data']) => {
        let nextData = source;
        if (typeof nextData === 'string') {
            try {
                nextData = JSON.parse(nextData.trim());
            } catch (error) {
                console.error('Invalid JSON data:', nextData, error);
            }
        }
        return nextData as TinyflowData | null | undefined;
    };

    const getOptions = () => props.options;
    const contextOptions = new Proxy({} as TinyflowOptions, {
        get(_target, property) {
            return (getOptions() as Record<PropertyKey, unknown>)[property];
        },
        has(_target, property) {
            return property in getOptions();
        },
        ownKeys() {
            return Reflect.ownKeys(getOptions());
        },
        getOwnPropertyDescriptor(_target, property) {
            const descriptor = Object.getOwnPropertyDescriptor(getOptions(), property);
            return descriptor ? { ...descriptor, configurable: true } : undefined;
        }
    }) as TinyflowOptions;
    const data = parseData(getOptions().data);
    const initialViewport = data?.viewport || null;
    store.setNodeNormalizer(createTinyflowNodeNormalizer(getOptions()));
    store.init(
        data?.nodes || [],
        data?.edges || [],
        initialViewport,
    );
    setContext('tinyflow_options', contextOptions);
</script>


<SvelteFlowProvider>
    <TinyflowCore onInit={props.onInit} />
</SvelteFlowProvider>
