{% extends '_layouts/cp.twig' %}

{% set readOnly = readOnly ?? false %}
{% set fullPageForm = not readOnly %}

{% set crumbs = [
    { label: "Settings"|t('app'), url: url('settings') },
    { label: "Assets"|t('app'), url: url('settings/assets') },
    { label: "Image Transforms"|t('app'), url: url('settings/assets/transforms') }
] %}

{% set formActions = [
  {
    label: 'Save and continue editing'|t('app'),
    redirect: 'settings/assets/transforms/{handle}'|hash,
    shortcut: true,
    retainScroll: true,
  },
] %}

{% set defaultPositionLabel = "Default Focal Point"|t('app') %}
{% set letterboxPositionLabel = "Image Position"|t('app') %}

{% import '_includes/forms.twig' as forms %}

{% if readOnly %}
    {% set contentNotice = readOnlyNotice() %}
{% endif %}

{% block content %}
    {% if not readOnly %}
        {{ actionInput('image-transforms/save') }}
        {{ redirectInput('settings/assets/transforms') }}

        {% if transform.id %}{{ hiddenInput('transformId', transform.id) }}{% endif %}
    {% endif %}

    {{ forms.textField({
        first: true,
        label: "Name"|t('app'),
        id: 'name',
        name: 'name',
        value: transform.name,
        errors: transform.getErrors('name'),
        autofocus: true,
        required: true,
        disabled: readOnly,
    }) }}

    {{ forms.textField({
        label: "Handle"|t('app'),
        id: "handle",
        name: "handle",
        class: 'code',
        autocorrect: false,
        autocapitalize: false,
        value: transform.handle,
        errors: transform.getErrors('handle'),
        required: true,
        disabled: readOnly,
    }) }}

    {% embed '_includes/forms/field.twig' with {
        label: 'Mode'|t('app')
    } %}
        {% block input %}
            <div id="mode" class="flex items-start gap-l">
                <label class="nowrap">
                    <img class="mb-xs" src="{{ baseIconsUrl }}/crop.svg" width="80" height="60" alt="">
                    {{ input('radio', 'mode', 'crop', {
                        checked: transform.mode == 'crop',
                        disabled: readOnly,
                    }) }}
                    {{ "Crop"|t('app') }}
                </label>
                <label class="nowrap">
                    <img class="mb-xs" src="{{ baseIconsUrl }}/fit.svg" width="80" height="60" alt="">
                    {{ input('radio', 'mode', 'fit', {
                        checked: transform.mode == 'fit',
                        disabled: readOnly,
                    }) }}
                    {{ "Fit"|t('app') }}
                </label>
                <label class="nowrap">
                    <img class="mb-xs" src="{{ baseIconsUrl }}/letterbox.svg" width="80" height="60" alt="">
                    {{ input('radio', 'mode', 'letterbox', {
                        checked: transform.mode == 'letterbox',
                        disabled: readOnly,
                    }) }}
                    {{ "Letterbox"|t('app') }}
                </label>
                <label class="nowrap">
                    <img class="mb-xs" src="{{ baseIconsUrl }}/stretch.svg" width="80" height="60" alt="">
                    {{ input('radio', 'mode', 'stretch', {
                        checked: transform.mode == 'stretch',
                        disabled: readOnly,
                    }) }}
                    {{ "Stretch"|t('app') }}
                </label>
            </div>
        {% endblock %}
    {% endembed %}

    <div id="fill-color" class="field {% if transform.mode != 'letterbox' or transform.fill is null %}hidden{% endif %}">
        {{ forms.colorField({
            label: 'Fill Color',
            name: 'fill',
            value: transform.mode == 'letterbox' and transform.fill != 'transparent' ? transform.fill,
            errors: transform.getErrors('fill'),
            disabled: readOnly,
        }) }}
    </div>

    <div id="position-container"{% if transform.mode not in ['crop', 'letterbox'] %} class="hidden"{% endif %}>
        {% set positionLabel = transform.mode == 'letterbox' ? letterboxPositionLabel : defaultPositionLabel %}
        {{ forms.selectField({
            label: positionLabel,
            id: 'position',
            name: 'position',
            options: {
                'top-left': "Top-Left"|t('app'),
                'top-center': "Top-Center"|t('app'),
                'top-right': "Top-Right"|t('app'),
                'center-left': "Center-Left"|t('app'),
                'center-center': "Center-Center"|t('app'),
                'center-right': "Center-Right"|t('app'),
                'bottom-left': "Bottom-Left"|t('app'),
                'bottom-center': "Bottom-Center"|t('app'),
                'bottom-right': "Bottom-Right"|t('app')
            },
            value: transform.mode in ['crop', 'letterbox'] ? transform.position : 'center-center',
            disabled: readOnly,
        }) }}
    </div>

    {{ forms.textField({
        label: "Width"|t('app'),
        id: "width",
        name: "width",
        size: 5,
        value: transform.width,
        errors: transform.getErrors('width'),
        disabled: readOnly,
    }) }}

    {{ forms.textField({
        label: "Height"|t('app'),
        id: "height",
        name: "height",
        size: 5,
        value: transform.height,
        errors: transform.getErrors('height'),
        disabled: readOnly,
    }) }}

    {{ forms.lightswitchField({
        label: 'Allow Upscaling'|t('app'),
        id: 'upscale',
        name: 'upscale',
        on: transform.upscale ?? craft.app.config.general.upscaleImages,
        errors: transform.getErrors('upscale'),
        disabled: readOnly,
    }) }}

    {% embed '_includes/forms/field.twig' with {
        label: 'Quality'|t('app'),
        errors: transform.getErrors('quality'),
    } %}
        {% block input %}
            {% import '_includes/forms.twig' as forms %}
            <div class="flex flex-nowrap">
                <div>
                    {{ forms.select({
                        id: 'quality-picker',
                        options: [
                            {label: 'Auto'|t('app'), value: 0},
                        ]|merge(qualityPickerOptions),
                        value: qualityPickerValue,
                        describedBy: describedBy,
                        disabled: readOnly,
                    }) }}
                </div>
                <div class="flex-grow">
                    {{ forms.text({
                        id: 'quality',
                        class: [
                            'ltr',
                            transform.quality == 0 ? 'hidden',
                        ]|filter,
                        name: 'quality',
                        value: transform.quality,
                        size: 5,
                        type: 'number',
                        min: 1,
                        max: 100,
                        describedBy: describedBy,
                        disabled: readOnly,
                    }) }}
                </div>
            </div>
        {% endblock %}
    {% endembed %}

    {{ forms.selectField({
        label: "Interlacing"|t('app'),
        id: "interlace",
        name: "interlace",
        options: [
            {label: 'None'|t('app'), value: 'none'},
            {label: 'Line'|t('app'), value: 'line'},
            {label: 'Plane'|t('app'), value: 'plane'},
            {label: 'Partition'|t('app'), value: 'partition'},
        ],
        value: transform.interlace ?? 'none',
        errors: transform.getErrors('interlace'),
        disabled: readOnly,
    }) }}

    {% set formatOptions = [
        {label: 'Auto', value: null},
        {label: 'jpg', value: 'jpg'},
        {label: 'png', value: 'png'},
        {label: 'gif', value: 'gif'},
    ] %}

    {% if transform.format == 'webp' or craft.app.images.supportsWebP %}
        {% set formatOptions = formatOptions|merge([{label: 'webp', value: 'webp'}]) %}
    {% endif %}

    {% if transform.format == 'avif' or craft.app.images.supportsAvif %}
        {% set formatOptions = formatOptions|merge([{label: 'avif', value: 'avif'}]) %}
    {% endif %}

    {{ forms.selectField({
        label: "Image Format"|t('app'),
        id: "format",
        name: "format",
        instructions: "The image format that transformed images should use."|t('app'),
        value: transform.format,
        errors: transform.getErrors('format'),
        options: formatOptions,
        disabled: readOnly,
    }) }}

{% endblock %}


{% js %}
    {% if not transform.handle %}new Craft.HandleGenerator('#name', '#handle');{% endif %}

    $('#mode input').change(function() {
        const value = $(this).val();

        // Letterbox mode requires a position:
        if (value == 'letterbox') {
            $('#fill-color').removeClass('hidden');
            $('#position-container label[for="position"]').text(`{{ letterboxPositionLabel }}`);
        } else {
            $('#fill-color').addClass('hidden');
            $('#position-container label[for="position"]').text(`{{ defaultPositionLabel }}`);
        }

        // Crop and letterbox modes requires a position:
        if (value == 'crop' || value == 'letterbox') {
            $('#position-container').removeClass('hidden');
        } else {
            $('#position-container').addClass('hidden');
        }
    });

    const qualityPickerOptions = {{ qualityPickerOptions|map(o => o.value)|json_encode|raw }};
    const $qualityPicker = $('#quality-picker');
    const $qualityInput = $('#quality');

    $qualityPicker.on('change', (ev) => {
        const pickerValue = $qualityPicker.val();
        $qualityInput.val(pickerValue);

        if (pickerValue === '0') {
            $qualityInput.addClass('hidden');
        } else {
            $qualityInput.removeClass('hidden');
        }
    });

    $qualityInput.on('input', (ev) => {
        let quality = parseInt($qualityInput.val());
        if (isNaN(quality)) {
            quality = 0;
        }

        let pickerValue;
        if (quality) {
            // Default to Low, even if quality is < 10
            pickerValue = 10;
            for (let i = 0; i < qualityPickerOptions.length; i++) {
                if (quality >= qualityPickerOptions[i]) {
                    pickerValue = qualityPickerOptions[i];
                } else {
                    break;
                }
            }
        } else {
            // Auto
            pickerValue = 0;
        }

        $qualityPicker.val(pickerValue);
    });
{% endjs %}
