@php
    $creativity_levels = [
        '0.25' => 'Economic',
        '0.5' => 'Average',
        '0.75' => 'Good',
        '1' => 'Premium',
    ];

    $voice_tones = ['Professional', 'Funny', 'Casual', 'Excited', 'Witty', 'Sarcastic', 'Feminine', 'Masculine', 'Bold', 'Dramatic', 'Grumpy', 'Secretive', 'other'];

    $card_variant = Theme::getSetting('defaultVariations.card.variant', 'outline') === 'outline' ? 'none' : Theme::getSetting('defaultVariations.card.variant', 'solid');
    $card_size = Theme::getSetting('defaultVariations.card.variant', 'outline') === 'outline' ? 'none' : Theme::getSetting('defaultVariations.card.size', 'md');
    $card_roundness = Theme::getSetting('defaultVariations.card.roundness', 'default') === 'default' ? 'none' : Theme::getSetting('defaultVariations.card.roundness', 'default');

    if ($openai->type == 'audio') {
        if ($card_variant === 'none') {
            $card_variant = 'outline';
        }
        if ($card_size === 'none') {
            $card_size = 'md';
        }
        if ($card_roundness === 'none') {
            $card_roundness = 'lg';
        }
    }
@endphp

@section('titlebar_before')
    <div class="flex w-full grow items-center justify-center">
        <x-credit-list />
    </div>
@endsection

@push('css')
    <style>
        .workbook-form .tox.tox-tinymce,
        .workbook-form .tox .tox-editor-container {
            overflow: visible;
        }

        .workbook-form .tox-editor-header {
            position: sticky;
            top: 0rem;
            padding-left: 4px !important;
            padding-right: 4px !important;
            border-radius: 8px !important;
            backdrop-filter: blur(12px);
            z-index: 10;
            background: hsl(var(--surface-background) / 5%) !important;
        }
    </style>
@endpush

<div
    class="lqd-generator-wrap grid grid-flow-row gap-y-8 lg:grid-flow-col lg:[grid-template-columns:40%_60%] xl:[grid-template-columns:33%_67%]"
    data-generator-type="{{ $openai->type }}"
>
    <div class="flex w-full flex-col gap-6 lg:pe-8">
        @if ($openai->type != 'image')

            <div class="flex flex-col gap-3.5">
                <div class="flex gap-3">
                    <div
                        class="relative inline-grid h-16 w-[78px] shrink-0 place-items-center rounded-t-xl bg-surface-background p-3 after:absolute after:start-0 after:top-full after:h-3.5 after:w-full after:bg-surface-background">
                        <div
                            class="absolute -bottom-3.5 start-full size-3 bg-surface-background after:absolute after:bottom-0 after:start-0 after:size-full after:rounded-es-full after:bg-background">
                        </div>
                        <x-button
                            class="size-11"
                            variant="outline"
                            size="none"
                            href="{{ route('dashboard.user.openai.list') }}"
                        >
                            <x-tabler-grid-dots class="size-5" />
                        </x-button>
                    </div>

                    <div
                        class="group relative z-1 grow"
                        :class="{ 'active': dropdownOpen }"
                        x-data="{
                            dropdownOpen: false,
                        }"
                        @click.outside="dropdownOpen = false"
                        @keydown.escape.window="dropdownOpen = false"
                    >
                        <button
                            class="relative z-20 flex h-16 w-full items-center justify-between rounded-xl bg-heading-foreground/5 px-[22px] py-3 text-sm font-semibold text-heading-foreground backdrop-blur-xl transition-all hover:bg-gradient-to-r hover:from-gradient-from hover:via-gradient-via hover:to-gradient-to hover:text-primary-foreground group-[&.active]:bg-gradient-to-r group-[&.active]:from-gradient-from group-[&.active]:via-gradient-via group-[&.active]:to-gradient-to group-[&.active]:text-primary-foreground"
                            type="button"
                            @click.prevent="dropdownOpen = !dropdownOpen"
                        >
                            <span>
                                {{ __($openai->title) }}
                            </span>

                            <x-tabler-chevron-down class="size-4" />
                        </button>

                        <div
                            class="absolute -end-4 -start-4 -top-4 z-10 h-0 max-h-[70vh] gap-0.5 overflow-hidden rounded-xl bg-surface-background text-xs font-semibold shadow-xl shadow-black/5 transition-all after:absolute after:left-0 after:top-0 after:z-1 after:h-24 after:w-full after:rounded-t-lg after:backdrop-blur-lg after:[mask-image:linear-gradient(to_bottom,black_25%,transparent)] group-[&.active]:h-96">
                            <div class="relative z-1 flex h-full flex-col gap-0.5 overflow-y-auto px-4 pb-2 pt-24">
                                @foreach ($list as $item)
                                    <a
                                        @class([
                                            'group/link flex items-center rounded-lg px-4 py-3 gap-2 text-heading-foreground hover:bg-heading-foreground/5 [&.selected]:bg-primary [&.selected]:text-primary-foreground',
                                            'selected' => $item->slug == $openai->slug,
                                        ])
                                        href="{{ route('dashboard.user.openai.generator', $item->slug) }}"
                                    >
                                        <span
                                            class="inline-grid size-8 place-items-center rounded-full bg-heading-foreground/5 group-[&.selected]/link:bg-primary-foreground/5 [&_svg:not([fill=none])]:fill-current [&_svg]:h-auto [&_svg]:w-5"
                                        >
                                            {!! $item->image !!}
                                        </span>
                                        {{ __($item->title) }}
                                    </a>
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>
                <x-card
                    class="lqd-generator-options-card roudned-e-xl rounded-se-xl rounded-ss-none bg-surface-background"
                    variant="solid"
                    size="lg"
                >
                    <form
                        class="lqd-generator-form flex flex-col gap-5"
                        id="openai_generator_form"
                        onsubmit="return sendOpenaiGeneratorForm();"
                        enctype="multipart/form-data"
                        x-data=""
                    >
                        @if ($openai->type === 'audio')
                            <div class="w-full text-center text-sm">
                                <x-tabler-volume
                                    class="mx-auto mb-2 size-8"
                                    stroke-width="1.5"
                                />
                                <p class="m-0 font-medium">
                                    <span class="opacity-70">
                                        @lang('Drag and drop an audio file')
                                    </span>
                                </p>
                                <p
                                    class="file-name m-0 font-medium [overflow-wrap:anywhere]"
                                    x-ref="fileName"
                                >
                                    @lang('or click here to browse your files.')
                                </p>
                            </div>
                        @endif
                        @foreach (json_decode($openai->questions) ?? [] as $question)
                            @if ($question?->type == 'text')
                                <x-forms.input
                                    id="{{ $question?->name }}"
                                    size="lg"
                                    label="{{ __($question?->question) }}"
                                    type="{{ $question?->type }}"
                                    name="{{ $question?->name }}"
                                    placeholder="{{ __($question?->question) }}"
                                    required
                                />
                            @elseif($question?->type == 'textarea')
                                <x-forms.input
                                    id="{{ $question?->name }}"
                                    size="lg"
                                    label="{{ __($question?->question) }}"
                                    name="{{ $question?->name }}"
                                    type="textarea"
                                    rows="8"
                                    placeholder="{{ __($question?->question) }}"
                                    required
                                />
                            @elseif($question?->type == 'select')
                                <x-forms.input
                                    id="{{ $question?->name }}"
                                    size="lg"
                                    label="{{ __($question?->question) }}"
                                    name="{{ $question?->name }}"
                                    type="select"
                                    required
                                >
                                    @foreach ($question?->selectListValues ?? [] as $input)
                                        <option value="{{ $input }}">
                                            {{ $input }}
                                        </option>
                                    @endforeach
                                </x-forms.input>
                            @elseif($question?->type == 'file')
                                <x-forms.input
                                    class="{{ $openai->type === 'audio' ? 'absolute opacity-0 top-0 start-0 cursor-pointer w-full h-full z-3' : '' }}"
                                    class:label="static text-center text-heading-foreground/40 text-3xs lg:px-10"
                                    id="{{ $question?->name }}"
                                    container-class="static"
                                    size="lg"
                                    label="{{ __($question?->question) }}"
                                    name="{{ $question?->name }}"
                                    type="file"
                                    placeholder="{{ __($question?->question) }}"
                                    required
                                    x-ref="file"
                                    @change="if ( $refs.fileName ) { $refs.fileName.innerText = $refs.file.files[0]?.name ?? '' }"
                                    @drop.prevent="if ( $refs.fileName ) { $refs.fileName.innerText = event.dataTransfer.files[0].name; } $refs.file.files = event.dataTransfer.files"
                                />
                            @endif
                        @endforeach

                        @if ($openai->type == 'text')
                            @if (setting('hide_output_length_option') != 1)
                                <x-forms.input
                                    id="maximum_length"
                                    size="lg"
                                    label="{{ __('Maximum Length') }}"
                                    name="maximum_length"
                                    type="number"
                                    placeholder="{{ __('Maximum character length of text') }}"
                                    required
                                    min="1"
                                    step="1"
                                />
                            @endif

                            @if (setting('hide_creativity_option') != 1)
                                <x-forms.input
                                    id="creativity"
                                    size="lg"
                                    label="{{ __('Creativity') }}"
                                    name="creativity"
                                    type="select"
                                    required
                                >
                                    @foreach ($creativity_levels as $creativity => $label)
                                        <option
                                            value="{{ $creativity }}"
                                            @selected($setting->openai_default_creativity == $creativity)
                                        >
                                            {{ __($label) }}
                                        </option>
                                    @endforeach
                                </x-forms.input>
                            @endif

                            <x-forms.input
                                id="language"
                                size="lg"
                                label="{{ __('Language') }}"
                                name="language"
                                type="select"
                                required
                            >
                                @include('panel.user.openai.components.countries')
                            </x-forms.input>

                            @if (setting('hide_tone_of_voice_option') != 1)
                                <x-forms.input
                                    id="tone_of_voice"
                                    size="lg"
                                    type="select"
                                    label="{{ __('Tone of Voice') }}"
                                    containerClass="w-full"
                                    name="tone_of_voice"
                                    required
                                >
                                    @foreach ($voice_tones as $tone)
                                        <option
                                            value="{{ $tone }}"
                                            @selected($setting->openai_default_tone_of_voice == $tone)
                                        >
                                            {{ __($tone) }}
                                        </option>
                                    @endforeach
                                </x-forms.input>
                                <x-forms.input
                                    class:container="hidden w-full md:w-[48%]"
                                    id="tone_of_voice_custom"
                                    name="tone_of_voice_custom"
                                    type="text"
                                    label="{{ __('Enter custom tone') }}"
                                    switcher
                                />
                            @endif

                            <x-forms.input
                                id="number_of_results"
                                size="lg"
                                type="number"
                                label="{{ __('Number of Results') }}"
                                name="number_of_results"
                                placeholder="{{ __('Maximum character length of text') }}"
                                required
                                min="1"
                                value="1"
                            />
                        @endif

                        <x-button
                            class="relative w-full bg-gradient-to-r from-gradient-from via-gradient-via to-gradient-to"
                            id="openai_generator_button"
                            size="lg"
                            tag="button"
                            type="submit"
                            form="openai_generator_form"
                        >
                            {{ __('Generate') }}
                            <svg
                                class="transition-all group-hover:translate-x-1"
                                width="21"
                                height="15"
                                viewBox="0 0 21 15"
                                fill="currentColor"
                                xmlns="http://www.w3.org/2000/svg"
                            >
                                <path
                                    d="M19.4852 6.37686C16.747 6.37686 14.2514 3.88238 14.2514 1.14308V0.0199585H12.0052V1.14308C12.0052 3.13551 12.879 5.00439 14.2503 6.37686H0.39209V8.62311H14.2503C12.879 9.99556 12.0052 11.8644 12.0052 13.8569V14.98H14.2514V13.8569C14.2514 11.1176 16.747 8.62311 19.4852 8.62311H20.6083V6.37686H19.4852Z"
                                />
                            </svg>
                        </x-button>
                    </form>
                </x-card>
            </div>
        @endif
    </div>

    <x-card
        class="w-full [&_.tox-edit-area__iframe]:!bg-transparent"
        id="generator_sidebar_table"
        variant="{{ Theme::getSetting('defaultVariations.card.variant', 'outline') === 'outline' ? 'none' : Theme::getSetting('defaultVariations.card.variant', 'solid') }}"
        size="{{ Theme::getSetting('defaultVariations.card.variant', 'outline') === 'outline' ? 'none' : Theme::getSetting('defaultVariations.card.size', 'md') }}"
        roundness="{{ Theme::getSetting('defaultVariations.card.roundness', 'default') === 'default' ? 'none' : Theme::getSetting('defaultVariations.card.roundness', 'default') }}"
    >
        @include('panel.user.openai.components.generator_sidebar_table')
    </x-card>
</div>

@push('script')
    @if ($openai->type == 'code')
        <link
            rel="stylesheet"
            href="{{ custom_theme_url('/assets/libs/prism/prism.css') }}"
        >
        <script src="{{ custom_theme_url('/assets/libs/prism/prism.js') }}"></script>
        <script>
            document.addEventListener('DOMContentLoaded', (event) => {
                "use strict";

                const codeLang = document.querySelector('#code_lang');
                const codePre = document.querySelector('#code-pre');
                const codeOutput = codePre?.querySelector('#code-output');

                if (codeOutput) {
                    let codeOutputText = codeOutput.textContent;
                    const codeBlocks = codeOutputText.match(/```[A-Za-z_]*\n[\s\S]+?```/g);
                    if (codeBlocks) {
                        codeBlocks.forEach((block) => {
                            const language = block.match(/```([A-Za-z_]*)/)[1];
                    const code = block.replace(/```[A-Za-z_]*\n/, '').replace(/```/, '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(
                        /"/g, '&quot;').replace(/'/g, '&#039;');
                    const wrappedCode = `<pre><code class="language-${language}">${code}</code></pre>`;
                    codeOutputText = codeOutputText.replace(block, wrappedCode);
                });
            }

            codePre.innerHTML = codeOutputText;

            codePre.querySelectorAll('pre').forEach(pre => {
                pre.classList.add(`language-${codeLang && codeLang.value !== '' ? codeLang.value : 'javascript'}`);
                    })

                    // saving for copy
                    window.codeRaw = codeOutput.innerText;

                    codePre.querySelectorAll('code').forEach(block => {
                        Prism.highlightElement(block);
                    });
                };
            });
            document.getElementById('tone_of_voice')?.addEventListener('change', function() {
                var customInput = document.getElementById('tone_of_voice_custom');
                if (this.value === 'other') {
                    customInput.parentNode.classList.remove('hidden');
                } else {
                    customInput.parentNode.classList.add('hidden');
                }
            });
        </script>
    @endif
@endpush
