<script lang="ts">
import type { SvelteComponent } from 'svelte';
import { onMount } from 'svelte';
import { fade } from 'svelte/transition';


// This works and uses local storage:
// store_current_tab must be prefixed with $ to be reactive.
import { clipboard, FileDropzone, getModalStore, localStorageStore, ProgressRadial, TabGroup, Tab, TabAnchor } from '@skeletonlabs/skeleton';

import type { Writable } from 'svelte/store';

import Element_data_store from '$lib/element_data_store.svelte';

const store_current_tab: Writable<string> = localStorageStore('ae_events_speakers_current_tab', 'start');
console.log(`store_current_tab:`, $store_current_tab);

// This works, but does not uses local storage:
// store_current_tab is not reactive and should not be prefixed with $.
// let store_current_tab: string = 'start';
// console.log(`store_current_tab:`, store_current_tab);

// This does not work:
// let tab_set = $store_current_tab;
// let tab_set = store_current_tab;

// Stores
// import { getModalStore, FileDropzone, TabGroup, Tab, TabAnchor } from '@skeletonlabs/skeleton';

// Props
/** Exposes parent props to this component. */
export let parent: SvelteComponent;
export let container_class_li = '';

const modalStore = getModalStore();


import { ae_util } from '$lib/ae_utils';
import { api } from '$lib/api';
import { ae_loc, ae_sess, ae_api, slct, slct_trigger } from '$lib/ae_stores';
import type { key_val } from '$lib/ae_stores';


let ae_promises: key_val = {}; // Promise<any>;

$ae_loc.mod.events.submit_status = null;
$ae_loc.mod.events.disable_submit__event_presenter_obj = false;
let placeholder_li: key_val = {
    image_headshot: '-- No File Selected --',
    image_example: '-- No File Selected --',
};

if ($slct.event_presenter_id) {
    console.log(`Presenter ID selected: ${$slct.event_presenter_id}`);
    console.log(`Presenter object selected:`, $slct.event_presenter_obj);

    $slct_trigger = 'load__event_presenter_obj';
} else {
    $store_current_tab = 'start';

    $slct.event_presenter_id = null;
    $slct.event_presenter_obj = {
        event_id_random: $ae_loc.mod.events.event_id,

        title_names: null, // Usually their prefix name
        given_name: null,
        family_name: null,
        professional_title: null,
        full_name: null,
        full_name_override: null, // was called display_name

        email: null,
        phone_mobile: null,
        affiliations: null,

        biography: null,

        // picture_path: null,

        image_li_json: null,
        // media_li_json: null,

        // social_li_json: null,

        enable: null,
    };
}


onMount(() => {
    console.log('** Component Mounted: ** Edit Modal - Presenter Obj');

    if ($slct.event_presenter_id && $ae_loc.href_url) {
        // $ae_loc.mod.events.presenter_link = `${$ae_loc.href_url}/load?event_presenter_id=${$slct.event_presenter_id}`;
        $ae_loc.mod.events.presenter_link = `${$ae_loc.site_domain}/events_speakers/load?event_presenter_id=${$slct.event_presenter_id}`;
        console.log('Speaker link:', $ae_loc.mod.events.presenter_link);
    }
});


$: if ($slct.event_presenter_obj) {
    // Create HTML for showing pictures here?
    if ($slct.event_presenter_obj.image_li_json) {
        if ($slct.event_presenter_obj.image_li_json.headshot && $slct.event_presenter_obj.image_li_json.headshot.hosted_file_id_random) {
            placeholder_li.image_headshot = ae_util.create_img_element({
                account_id: $ae_loc.account_id,
                base_url: $ae_api.base_url,
                hosted_file_id: $slct.event_presenter_obj.image_li_json.headshot.hosted_file_id_random,
                filename: `${$slct.event_presenter_obj.full_name} [headshot].${$slct.event_presenter_obj.image_li_json.headshot.extension}`,
                style: 'max-width: 20em;',
                inc_link: true,
            })

            // `<img src="https://dev-demo.oneskyit.com/hosted_file/download/${$slct.event_presenter_obj.image_li_json.headshot.hosted_file_id_random}" class="max-w-64">${$slct.event_presenter_obj.image_li_json.headshot.filename}`;
        }
    }
    //     if ($slct.event_presenter_obj.logo_li_json.secondary.hosted_file_id_random) {
    //         placeholder_li.file_logo_secondary = `<img src="https://dev-demo.oneskyit.com/hosted_file/download/${$slct.event_presenter_obj.logo_li_json.secondary.hosted_file_id_random}">${$slct.event_presenter_obj.logo_li_json.secondary.filename}`;
    //     }
    // }

    // Create HTML for showing other media file types here?
    // if ($slct.event_presenter_obj.media_li_json) {
    //     if ($slct.event_presenter_obj.media_li_json.promo_video && $slct.event_presenter_obj.media_li_json.promo_video.hosted_file_id_random) {
    //         placeholder_li.file_media_promo_video = `<video src="https://dev-demo.oneskyit.com/hosted_file/download/${$slct.event_presenter_obj.media_li_json.promo_video.hosted_file_id_random}" controls></video>${$slct.event_presenter_obj.media_li_json.promo_video.filename}`;
    //     }
    // }
}

async function handle_submit_form(event) {
    console.log('*** handle_submit_form() ***');

    $ae_loc.mod.events.disable_submit__event_presenter_obj = true;
    $ae_loc.mod.events.submit_status = 'saving';

    // Data in
    let form_data = new FormData(event.target);
    console.log(form_data);

    let event_presenter_di: key_val = ae_util.extract_prefixed_form_data({prefix: null, form_data: form_data, trim_values: true, bool_tf_str: true, log_lvl: 0});
    console.log(event_presenter_di);

    // Data out
    let event_presenter_do: key_val = {};

    if (!$slct.event_presenter_id) {
        event_presenter_do['event_id_random'] = $ae_loc.mod.events.event_id;
        event_presenter_do['event_session_id_random'] = $ae_loc.mod.events.default_session_id;
    }

    // Check if the title_names form field exists (is defined) and if so, assign it to the new object
    console.log(event_presenter_di.title_names);
    console.log(event_presenter_di.comments);

    if (typeof event_presenter_di.title_names !== 'undefined') {
        event_presenter_do['title_names'] = event_presenter_di.title_names;
    }

    if (typeof event_presenter_di.given_name !== 'undefined') {
        event_presenter_do['given_name'] = event_presenter_di.given_name;
    }
    if (typeof event_presenter_di.family_name !== 'undefined') {
        event_presenter_do['family_name'] = event_presenter_di.family_name;
    }

    if (typeof event_presenter_di.professional_title !== 'undefined') {
        event_presenter_do['professional_title'] = event_presenter_di.professional_title;
    }

    // if (event_presenter_di.given_name && event_presenter_di.family_name) {
    //     event_presenter_do['full_name_overide'] = ;
    // }

    if (typeof event_presenter_di.affiliations !== 'undefined') {
        event_presenter_do['affiliations'] = event_presenter_di.affiliations;
    }

    if (typeof event_presenter_di.email !== 'undefined') {
        event_presenter_do['email'] = event_presenter_di.email;
    }

    if (typeof event_presenter_di.biography !== 'undefined') {
        event_presenter_do['biography'] = event_presenter_di.biography;
    }

    // if (event_presenter_di.social_media_facebook || event_presenter_di.social_media_twitter || event_presenter_di.social_media_instagram || event_presenter_di.social_media_linkedin) {
    //     event_presenter_do['social_li_json'] = {
    //         facebook: event_presenter_di.social_media_facebook,
    //         twitter: event_presenter_di.social_media_twitter,
    //         instagram: event_presenter_di.social_media_instagram,
    //         linkedin: event_presenter_di.social_media_linkedin,
    //     };
    // }

    // if (event_presenter_di.image_headshot) {
    //     event_presenter_do['picture_path'] = event_presenter_di.image_headshot;
    // }

    if (typeof event_presenter_di.agree !== 'undefined') {
        event_presenter_do['agree'] = !!event_presenter_di.agree;
    }


    // Marketing for social media and email related questions
    if (typeof event_presenter_di.website_url !== 'undefined') {
        // This is also stored under social_li_json.
        event_presenter_do['website_url'] = event_presenter_di.website_url;
    }

    if (event_presenter_di.social_media_facebook || event_presenter_di.social_media_twitter || event_presenter_di.social_media_instagram || event_presenter_di.social_media_linkedin) {
        event_presenter_do['social_li_json'] = {
            facebook: event_presenter_di.social_media_facebook,
            twitter: event_presenter_di.social_media_twitter,
            instagram: event_presenter_di.social_media_instagram,
            linkedin: event_presenter_di.social_media_linkedin,
            org: event_presenter_di.website_url,
        };
    }


    if (typeof event_presenter_di.comments !== 'undefined') {
        event_presenter_do['comments'] = event_presenter_di.comments;
    }

    if (typeof event_presenter_di.hide !== 'undefined') {
        event_presenter_do['hide'] = !!event_presenter_di.hide;
    }
    if (typeof event_presenter_di.priority !== 'undefined') {
        event_presenter_do['priority'] = !!event_presenter_di.priority;
    }
    if (typeof event_presenter_di.sort !== 'undefined') {
        // Change this to a number type
        event_presenter_do['sort'] = Number(event_presenter_di.sort);
    } else {
        event_presenter_do['sort'] = null;
    }
    if (typeof event_presenter_di.group !== 'undefined') {
        event_presenter_do['group'] = event_presenter_di.group;
    } else {
        event_presenter_do['group'] = null;
    }
    if (typeof event_presenter_di.enable !== 'undefined') {
        event_presenter_do['enable'] = !!event_presenter_di.enable;
    }

    if (typeof event_presenter_di.notes !== 'undefined') {
        event_presenter_do['notes'] = event_presenter_di.notes;
    }

    console.log(event_presenter_do);

    if (!$slct.event_presenter_id) {
        ae_promises.create__event_presenter = await handle_create__event_presenter({
            obj_type: 'event_presenter',
            data: event_presenter_do
        });
        console.log(ae_promises.create__event_presenter);
        if (ae_promises.create__event_presenter.event_presenter_id_random) {
            $slct.event_presenter_id = ae_promises.create__event_presenter.event_presenter_id_random;
            $slct.event_presenter_obj = ae_promises.create__event_presenter;

            $ae_loc.mod.events.presenter_link = `${$ae_loc.site_domain}/events_speakers/load?event_presenter_id=${$slct.event_presenter_id}`;
            console.log('Speaker link:', $ae_loc.mod.events.presenter_link);

            // This should no longer be needed! Will add a check later to trigger this or a second create if something does not look correct.
            // $slct_trigger = 'load__event_presenter_obj';

            $ae_sess.mod.events.submit_status = 'created';
        } else {
            console.log('No event_presenter_id_random was found. Something may have gone wrong.');
            $ae_sess.mod.events.submit_status = 'created_unknown';
        }
        $ae_loc.mod.events.disable_submit__event_presenter_obj = false;

    } else {
        ae_promises.update__event_presenter_obj = await handle_update__event_presenter({
            obj_type: 'event_presenter',
            obj_id: $slct.event_presenter_id,
            data: event_presenter_do
        });
        console.log(ae_promises.update__event_presenter_obj);
        if (ae_promises.update__event_presenter_obj.event_presenter_id_random) {
            $slct.event_presenter_obj = ae_promises.update__event_presenter_obj;

            // $slct_trigger = 'load__event_presenter_obj';
            $ae_sess.mod.events.submit_status = 'updated';
        } else {
            console.log('No event_presenter_id_random was found. Something may have gone wrong.');
            $ae_sess.mod.events.submit_status = 'updated_unknown';

            console.log('Trigger a reload of the object.');
            $slct_trigger = 'load__event_presenter_obj';
        }
        $ae_loc.mod.events.disable_submit__event_presenter_obj = false;
    }

    if ($slct.event_presenter_id) {
        if ($store_current_tab == 'start' && $slct.event_presenter_id) {
            $store_current_tab = 'biograhpy';
            if (!$slct.event_presenter_obj.updated_on) {
                send_init_confirm_email();
            }

        // Move on to files
        } else if ($store_current_tab == 'biograhpy' && $slct.event_presenter_id) {
            $store_current_tab = 'files';

        // Move on to summary
        } else if ($store_current_tab == 'files' && $slct.event_presenter_id) {
            $store_current_tab = 'summary';
        }

        $slct_trigger = 'load__event_presenter_obj_li';
    } else {
        console.log('No obj ID found!');
    }

}

async function handle_submit_form_files(event) {
    console.log('*** handle_submit_form() ***');

    $ae_sess.mod.events.disable_submit__event_presenter_obj = true;
    $ae_sess.mod.events.submit_status = 'saving';

    let event_presenter_do: key_val = {};

    // if ($slct.event_presenter_obj.logo_li_json) {
    //     console.log('The logo_li_json was found.');
    //     event_presenter_do.logo_li_json = $slct.event_presenter_obj.logo_li_json;
    // } else {
    //     console.log('The logo_li_json was not found or is empty.');
    //     event_presenter_do.logo_li_json = {};
    // }

    // if ($slct.event_presenter_obj.media_li_json) {
    //     console.log('The media_li_json was found.');
    //     event_presenter_do.media_li_json = $slct.event_presenter_obj.media_li_json;
    // } else {
    //     console.log('The media_li_json was not found or is empty.');
    //     event_presenter_do.media_li_json = {};
    // }

    let hosted_file_results;
    // let logo_li_json = {};
    // let media_li_json =  {};

    if (event.target.image_headshot.files.length > 0) {
        console.log('The headshot image file was found.');

        hosted_file_results = await handle_input_upload_files(event.target.image_headshot.files);

        event_presenter_do.image_li_json = {};

        if (hosted_file_results) {
            event_presenter_do.image_li_json.headshot = hosted_file_results[0];
            console.log(event_presenter_do.image_li_json);
            placeholder_li.image_headshot = ae_util.create_img_element({
                account_id: $ae_loc.account_id,
                base_url: $ae_api.base_url,
                hosted_file_id: event_presenter_do.image_li_json.headshot.hosted_file_id_random,
                filename: `${$slct.event_presenter_obj.full_name} [headshot].${event_presenter_do.image_li_json.headshot.extension}`,
                // style: 'max-width: 20em;',
                inc_link: true,
            })

            // `<img src="/hosted_file/download/${event_presenter_do.image_li_json.headshot.hosted_file_id_random}">${event_presenter_do.image_li_json.headshot.filename}`;
        }
    }


    console.log(event_presenter_do);


    ae_promises.update__event_presenter_obj = await handle_update__event_presenter({
        obj_type: 'event_presenter',
        obj_id: $slct.event_presenter_id,
        data: event_presenter_do
    });
    console.log(ae_promises.update__event_presenter_obj);
    if (ae_promises.update__event_presenter_obj.event_presenter_id_random) {
        $slct.event_presenter_obj = ae_promises.update__event_presenter_obj;

        // $slct_trigger = 'load__event_presenter_obj';
        $ae_sess.mod.events.submit_status = 'updated';
    } else {
        console.log('No event_presenter_id_random was found. Something may have gone wrong.');
        $ae_sess.mod.events.submit_status = 'updated_unknown';

        console.log('Trigger a reload of the object.');
        $slct_trigger = 'load__event_presenter_obj';
    }
    $ae_sess.mod.events.disable_submit__event_presenter_obj = false;

    if ($store_current_tab == 'files' && $slct.event_presenter_id) {
        $store_current_tab = 'summary';
    }

    console.log('Trigger a reload of the object list.');
    $slct_trigger = 'load__event_presenter_obj_li';
}


async function handle_input_upload_files(input_upload_files) {
    console.log('*** handle_input_upload_files() ***');

    const form_data = new FormData();

    form_data.append('account_id', $ae_loc.account_id);
    form_data.append('link_to_type', 'event_presenter');
    form_data.append('link_to_id', $slct.event_presenter_id);

    for (let i = 0; i < input_upload_files.length; i++) {
        form_data.append(`file_list`, input_upload_files[i]);
    }

    let params = null;

    let endpoint = '/hosted_file/upload_files';

    console.log(form_data);

    params = null;

    // Uncomment and the post_promise is not seen by the "await" below
    // post_promise = await api.post_object({api_cfg: $cfg.api, endpoint: endpoint, params: params, data:form_data});
    // Uncomment so that the post_promise is not seen by the "await" below
    ae_promises.upload__hosted_file_obj = await api.post_object({api_cfg: $ae_api, endpoint: endpoint, params: params, form_data: form_data});
    console.log(ae_promises.upload__hosted_file_obj);
    let hosted_file_result = ae_promises.upload__hosted_file_obj;

    return hosted_file_result;
}


async function handle_create__event_presenter({
    obj_type,
    data
    }) {
    console.log('*** handle_create__event_presenter() ***');

    ae_promises.api_create__event_presenter_obj = api.create_ae_obj_crud({
        api_cfg: $ae_api,
        obj_type: obj_type,
        fields: data,
        key: $ae_api.api_crud_super_key,
        return_obj: true,
        log_lvl: 2
        })
    .then(async function (create__obj_result) {
        if (!create__obj_result) {
            console.log('The result was null or false.');
            return false;
        }
        return create__obj_result;
    })
    .catch(function (error) {
        console.log('Something went wrong.');
        console.log(error);
        return false;
    });

    return ae_promises.api_create__event_presenter_obj;
}


async function handle_update__event_presenter({
    obj_type,
    obj_id,
    data
    }) {
    console.log('*** handle_update__event_presenter() ***');

    ae_promises.update__event_presenter_obj = api.update_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: obj_type,
        obj_id: obj_id,
        fields: data,
        key: $ae_api.api_crud_super_key,
        return_obj: true,
        log_lvl: 2
        })
    .then(async function (update__obj_result) {
        if (!update__obj_result) {
            console.log('The result was null or false.');
            return false;
        }
        return update__obj_result;
    })
    .catch(function (error) {
        console.log('Something went wrong.');
        console.log(error);
        return false;
    });

    return ae_promises.update__event_presenter_obj;
}

function send_init_confirm_email() {
    console.log(`*** send_init_confirm_email() *** to ${$slct.event_presenter_obj.email}`);

    let subject = `CHOW 2024 Speaker Hub Link for ${$slct.event_presenter_obj.full_name} (ID: ${$slct.event_presenter_id})`;

    let body_html = `
    <div>${$slct.event_presenter_obj.full_name},
    <p>Thank you for your submission to the Capitol Hill Ocean Week Speaker Hub. You are an integral part of Capitol Hill Ocean Week and we appreciate your participation. If you need to make any changes or updates to your submission, you may access it via the link below.</p>
    </div>

    <div>
    Name: ${$slct.event_presenter_obj.full_name}<br>
    Professional title: ${$slct.event_presenter_obj.professional_title}<br>
    Affiliations: ${$slct.event_presenter_obj.affiliations}<br>
    Email: ${$slct.event_presenter_obj.email}
    </div>

    <br>

    <div>
    CHOW 2024 Speaker ID: ${$slct.event_presenter_id}<br>
    <p>Use this link to view or update your CHOW 2024 speaker information.<br>
    Copy and paste link: <a href="${$ae_loc.mod.events.presenter_link}">${$ae_loc.mod.events.presenter_link}</a></p>
    </div>`;

    api.send_email({
        api_cfg: $ae_api,
        from_email: 'noreply+chow@oneskyit.com',
        from_name: 'CHOW 2024 Speaker Hub',
        to_email: $slct.event_presenter_obj.email,
        subject: subject,
        body_html: body_html,
    });
}

function send_summary_email() {
    let subject = `CHOW 2024 Speaker Hub Link for ${$slct.event_presenter_obj.full_name} (ID: ${$slct.event_presenter_id})`;

    let body_html = `
    <div>${$slct.event_presenter_obj.full_name},
    <p>Thank you for your submission to the Capitol Hill Ocean Week Speaker Hub. You are an integral part of Capitol Hill Ocean Week and we appreciate your participation. If you need to make any changes or updates to your submission, you may access it via the link below.</p>
    </div>

    <div>
    Name: ${$slct.event_presenter_obj.full_name}<br>
    Professional title: ${$slct.event_presenter_obj.professional_title}<br>
    Affiliations: ${$slct.event_presenter_obj.affiliations}<br>
    Email: ${$slct.event_presenter_obj.email}
    </div>

    <div>Biography:<pre class="text-wrap">${$slct.event_presenter_obj.biography}</pre>
    </div>

    <div>
        Headshot:<div style="max-width: 20em">${placeholder_li.image_headshot}</div>
    </div>

    <br>

    <div>
    CHOW 2024 Speaker ID: ${$slct.event_presenter_id}<br>
    <p>Use this link to view or update your CHOW 2024 speaker information.<br>
    Copy and paste link: <a href="${$ae_loc.mod.events.presenter_link}">${$ae_loc.mod.events.presenter_link}</a></p>
    </div>`;

    api.send_email({
        api_cfg: $ae_api,
        from_email: 'noreply+chow@oneskyit.com',
        from_name: 'CHOW 2024 Speaker Hub',
        to_email: $slct.event_presenter_obj.email,
        subject: subject,
        body_html: body_html,
    });
}

// let delete_event_presenter_obj_promise: Promise<any>;
let delete_event_presenter_obj_promise;
async function handle_delete_event_presenter_obj({event_presenter_id, hosted_file_id=null, method='delete'}) {
    console.log('*** handle_delete_event_presenter_obj() ***');

    if (hosted_file_id) {
    //     let delete_hosted_file_obj_promise = api.delete_hosted_file({
    //         api_cfg: $ae_api,
    //         hosted_file_id: hosted_file_id,
    //         link_to_type: 'event_presenter',
    //         link_to_id: event_presenter_id,
    //         rm_orphan: true,
    //         // params: params,
    //         key: $ae_api.api_crud_super_key,
    //         log_lvl: 2
    //         })
    //     .then(function (hosted_file_obj_delete_result) {
    //         if (hosted_file_obj_delete_result) {
    //             // console.log(`Result:`, hosted_file_obj_delete_result);

    //             dispatch(
    //                 'deleted__hosted_file_obj',
    //                 {
    //                     hosted_file_id: hosted_file_id,
    //                 }
    //             );
    //         }
    //     })
    //     .catch(function (error) {
    //         console.log('The result was null or false when trying to delete.', error);
    //     });
    }

    delete_event_presenter_obj_promise = await api.delete_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'event_presenter',
        obj_id: event_presenter_id,
        method: method,
        // params: params,
        key: $ae_api.api_crud_super_key,
        log_lvl: 2
        })
    .then(function (event_presenter_obj_delete_result) {
        if (event_presenter_obj_delete_result) {
            // console.log(`Result:`, event_presenter_obj_delete_result);

        }
    })
    .catch(function (error) {
        console.log('The result was null or false when trying to delete.', error);
    });

    console.log('Trigger a reload of the object list.');
    $slct_trigger = 'load__event_presenter_obj_li';

    parent.onClose();

    return delete_event_presenter_obj_promise;
}
</script>

<!-- @component This is the Event Presenters modal edit form. -->

{#if $modalStore[0]}
<section class="svelte_component ae_edit_modal ae_obj__event_presenter {container_class_li}">
    <header class="{parent.regionHeader}">
        <h2 class="h3">{$modalStore[0].title ?? '-- No Title --'}:
            {$slct.event_presenter_obj && $slct.event_presenter_obj.full_name ? $slct.event_presenter_obj.full_name : '-- Fill out and save --'}
        </h2>

        {#await ae_promises.update__event_presenter_obj}
            <div class="modal-loading">
                <span class="fas fa-spinner fa-spin"></span>
                <span class="loading-text">
                    <!-- <ProgressRadial value={undefined} /> -->
                    Saving...
                </span>
            </div>
        {:then update__event_presenter_obj_result}
            {#if update__event_presenter_obj_result}
            <div class="modal-loading">
                <span class="fas fa-check-circle"></span>
                <span class="loading-text">Successfully saved!</span>
            </div>
            {/if}
        {:catch error}
            <div class="modal-loading">
                <span class="fas fa-exclamation-triangle"></span>
                <span class="loading-text">Error: {error.message}</span>
            </div>
        {/await}

        <button class="btn variant-glass-primary float-end" on:click={parent.onClose}>
            <span class="fas fa-times mx-1"></span>
            Close
        </button>
    </header>


    <!-- {#if $slct.event_presenter_id && $ae_loc.mod.events.presenter_link}
    <div class="flex justify-center">
        <button
            class="btn variant-soft-secondary"
            use:clipboard={$ae_loc.mod.events.presenter_link}
            >
            <span class="fas fa-copy mx-1"></span>
            Copy link for {$slct.event_presenter_id}
        </button>

        <button
            class="btn variant-soft-secondary mx-1"
            on:click={() => {
                if (!confirm(`Are you sure you want to send this email to ${$slct.event_presenter_obj.email}?`)) {return false;}

                }}
            >
            <span class="fas fa-paper-plane mx-1"></span>
            Send Email
        </button>
    </div>
    {/if} -->


    <TabGroup
        justify="justify-center"
        active="variant-ghost-primary"
        hover="hover:variant-soft-primary"
        flex="flex-1 lg:flex-none"
        rounded=""
        border=""
        class="bg-surface-100-800-token w-full"
        >
        <Tab bind:group={$store_current_tab} name="tab_start" value={'start'}>
            <svelte:fragment slot="lead">
                {#if $slct.event_presenter_obj.event_presenter_id_random}
                    <span class="fas fa-check text-green-500"></span>
                {/if}
                <span class="fas fa-home"></span>
            </svelte:fragment>
            <span>Start</span>
        </Tab>
        <Tab
            bind:group={$store_current_tab}
            name="tab_biograhpy"
            value={'biograhpy'}
            disabled={!$slct.event_presenter_obj.event_presenter_id_random}
            regionTab={!$slct.event_presenter_obj.event_presenter_id_random ? 'text-slate-400' : ''}
            >
            <svelte:fragment slot="lead">
                {#if $slct.event_presenter_obj.biography && $slct.event_presenter_obj.biography.length > 50}
                    <span class="fas fa-check text-green-500"></span>
                {/if}
                <span class="fas fa-users"></span>
            </svelte:fragment>
            Biography
        </Tab>
        <Tab
            bind:group={$store_current_tab}
            name="tab_files"
            value={'files'}
            disabled={!$slct.event_presenter_obj.event_presenter_id_random}
            regionTab={!$slct.event_presenter_obj.event_presenter_id_random ? 'text-slate-400' : ''}
            >
            <svelte:fragment slot="lead">
                {#if $slct.event_presenter_obj.image_li_json}
                    <span class="fas fa-check text-green-500"></span>
                {/if}
                <span class="fas fa-file-upload"></span>
            </svelte:fragment>
            Headshot
        </Tab>
        <!-- <Tab
            bind:group={$store_current_tab}
            name="tab_social"
            value={'social'}
            disabled={!$slct.event_presenter_obj.event_presenter_id_random}
            regionTab={!$ae_loc.administrator_access || !$slct.event_presenter_obj.event_presenter_id_random ? 'text-slate-400' : ''}
            >
            {#if $slct.event_presenter_obj.social_li_json}
                <span class="fas fa-check text-green-500"></span>
            {/if}
            <svelte:fragment slot="lead">
                <span class="fas fa-share-alt"></span>
            </svelte:fragment>
            Social Media
        </Tab> -->
        <Tab
            bind:group={$store_current_tab}
            name="tab_summary"
            value={'summary'}
            disabled={!$slct.event_presenter_obj.event_presenter_id_random}
            regionTab={!$slct.event_presenter_obj.event_presenter_id_random ? 'text-slate-400' : ''}
            >
            <svelte:fragment slot="lead">
                <span class="fas fa-info"></span>
            </svelte:fragment>
            Summary
        </Tab>

    <!-- Tab Panels --->
	<svelte:fragment slot="panel">


    {#if $store_current_tab === 'start'}


    <section class="space-y-4">

    <h3 class="h4">CHOW 2024 Speaker Listing Information</h3>

    <p>Please enter your personal and professional information below.</p>

    <p>The details provided will be used to list you as a speaker in our CHOW promotional materials and during CHOW in the event mobile app, speaker introductions, etc.</p>

    <form
        class="modal-form {$ae_loc.hub.classes__form}"
        on:submit|preventDefault={handle_submit_form}
        >

    <fieldset class="mb-8 flex flex-wrap gap-4">
        <legend class="legend">Speaker</legend>

        <label for="title_names" class="label">Name prefix
            <input type="text" id="title_names" name="title_names" max="200" value={$slct.event_presenter_obj.title_names ?? ''} placeholder="Prefix" autocomplete="off" class="input" />
        </label>

        <label for="given_name">
            <!-- Given name -->
            <span class="input_required">First name</span>
            <input
                type="text"
                class="input variant-glass-warning"
                id="given_name" name="given_name"
                placeholder="First name"
                value={($slct.event_presenter_obj.given_name ? $slct.event_presenter_obj.given_name : '')}
                autocomplete="name"
                readonly={!$ae_loc.trusted_access && $slct.event_presenter_obj.event_presenter_id_random}
                required
                >
        </label>
        <label for="family_name">
            <!-- Family name -->
            <span class="input_required">Last name</span>
            <input
                type="text"
                class="input variant-glass-warning"
                id="family_name" name="family_name"
                placeholder="Last name"
                value={($slct.event_presenter_obj.family_name ? $slct.event_presenter_obj.family_name : '')}
                autocomplete="name"
                readonly={!$ae_loc.trusted_access && $slct.event_presenter_obj.event_presenter_id_random}
                required
                >
        </label>

        <label for="professional_title" class="label">
            <span class="input_required">Professional title</span>
            <input type="text" id="professional_title" name="professional_title" required max="200" value={$slct.event_presenter_obj.professional_title ?? ''} placeholder="Professional title" autocomplete="off" class="input variant-glass-warning" />
        </label>

        <label for="affiliations" class="label">
            <span class="input_required">Affiliations/Organization</span>
            <input type="text" id="affiliations" name="affiliations" required max="200" value={$slct.event_presenter_obj.affiliations ?? ''} placeholder="Affiliations or organization" autocomplete="off" class="input variant-glass-warning" />
        </label>

        <label for="email">
            <span class="input_required">Email</span>
            <input
                type="email"
                class="input variant-glass-warning"
                id="email"
                name="email"
                placeholder="Email"
                bind:value={$slct.event_presenter_obj.email}
                autocomplete="email"
                readonly={!$ae_loc.trusted_access && $slct.event_presenter_obj.event_presenter_id_random}
                required
                >
        </label>

        <!-- <label for="phone_mobile">Mobile phone
            <input
                type="tel"
                class="input"
                id="phone_mobile"
                name="phone_mobile"
                placeholder="Mobile phone"
                value={($slct.event_presenter_obj.phone_mobile ? $slct.event_presenter_obj.phone_mobile : '')}
                autocomplete="tel"
                >
        </label> -->
    </fieldset>

    <!-- </section> -->

    <fieldset class="mb-8">
        <legend class="legend input_required">Agreements</legend>

        <!-- <Element_data_store
            ds_code="events_speakers__form__waiver_html"
            ds_type="html"
            for_type="devent"
            for_id={$slct.event_presenter_id}
            ds_name="Default: Events Speaker Form - Waiver HTML"
            display="block"
            class_li=""
            /> -->

        <label for="agree" class="label">
            <input
                type="checkbox"
                class="checkbox variant-glass-warning"
                id="agree"
                name="agree"
                value="1"
                checked={$slct.event_presenter_obj.agree}
                required
                >
            Yes, I grant the Foundation permission to use my biography, photo, and presentation, materials and verbal remarks on the Foundation website and promotional materials. I understand that summarized remarks will be sent to me for review prior to inclusion.
        </label>
        <!-- <label for="agree" class="label">
            <input
                type="checkbox"
                class="checkbox variant-glass-warning"
                id="agree"
                name="agree"
                value="1"
                checked={$slct.event_presenter_obj.agree}
                required
                >
            Yes, I understand the permissions.
        </label> -->

        <!-- <label for="accommodations" class="label">
            <input
                type="checkbox"
                class="checkbox"
                id="accommodations"
                name="accommodations"
                value="1"
                checked={$slct.event_presenter_obj.accommodations}
                >
            Yes, please have a member of the CHOW team reach out for special accommodations or assistance.
        </label> -->
    </fieldset>

    <!-- <button
        type="submit"
        class="btn variant-glass-primary m-2"
        disabled={(!$slct.event_presenter_obj.email || $ae_sess.mod.events.disable_submit__event_presenter_obj)}
        on:click={() => {
            console.log('*** Start save and email button clicked ***');
            if (!confirm(`This will save your speaker information so far and a confirmation email will be sent to ${$slct.event_presenter_obj.email}.`)) {return false;}

            }}
            >
        <span class="fas fa-envelope mx-1"></span>
        Save and email
    </button> -->

    <button
        type="submit"
        class="btn variant-glass-primary m-2"
        disabled={($ae_loc.mod.events.disable_submit__event_presenter_obj)}
        on:click={() => {
            console.log('*** Save start button clicked ***');
            if (!$slct.event_presenter_obj.email) {
                if (alert(`You have not entered an email address.`)) {return false;}
            }

            if ($slct.event_presenter_obj.updated_on) {
                if (confirm(`Would you like an email with a link back to this for be sent to you at ${$slct.event_presenter_obj.email}? Your information will be saved either way.`)) {
                    send_init_confirm_email();
                } else {
                    return false;
                }
            }
        }}
        >
        <span class="fas fa-check mx-1"></span>
        Save and continue
    </button>

    </form>

    </section>


    {:else if $store_current_tab === 'biograhpy'}


    <section class="biograhpy space-y-4">

    <form
        class="modal-form {$ae_loc.hub.classes__form}"
        on:submit|preventDefault={handle_submit_form}
        >
       <label class="label ae_label event_presenter__biography required variant-glass-warning space-y-4">
            <span class="label">
                <h3 class="h4 input_required">Speaker Biography</h3>
                <!-- <p>This is required.</p> -->
            </span>
            <textarea
                name="biography"
                id="biography"
                class="textarea ae_value event_presenter__biography tinymce_editor editor_basic"
                class:variant-glass-error={($slct.event_presenter_obj.biography && $slct.event_presenter_obj.biography.length >1250 ? true : false)}
                required
                rows="16" cols="70"
                bind:value={$slct.event_presenter_obj.biography} placeholder="Enter brief biography here"></textarea>
        </label>
        <p>Biography length: {($slct.event_presenter_obj.biography ? ae_util.number_w_commas($slct.event_presenter_obj.biography.length) : 0)} characters; {($slct.event_presenter_obj.biography ? ae_util.number_w_commas(ae_util.count_words($slct.event_presenter_obj.biography)) : 0)} estimated words</p>
        <!-- <p>Biography length: </p> -->
        <p>The biography should be plain text only and be at most 250 words.</p>
        <!-- <p>1,250 characters is roughly 250 words</p> -->
        <!-- <p>1,375 characters is roughly 250 to 300 words</p> -->

        <div class="flex flex-wrap gap-2 p-1">
        <button
            type="submit"
            class="btn variant-glass-primary m-2"
            disabled={($ae_loc.mod.events.disable_submit__event_presenter_obj)}
            on:click={() => {
                console.log('*** Save button clicked ***');
                // if (!confirm('Are you sure you want to save this event_presenter?')) {return false;}
                // handle_submit_form();
                // handle_submit_form;
            }}
            >
            <span class="fas fa-check mx-1"></span>
            Save and continue
        </button>

        </div>

    </form>

    </section>


    {:else if $store_current_tab === 'files'}


    <form
        class="modal-form {$ae_loc.hub.classes__form}"
        on:submit|preventDefault={handle_submit_form_files}
        >

    <section class="space-y-4">
        <h2 class="h3 input_required">Headshot Photo</h2>
        <!-- <p>Upload your headshot photo here. This is required.</p> -->
        <label for="image_headshot">
            Upload a headshot photo
            <FileDropzone
                id="image_headshot"
                name="image_headshot"
                padding="p-1"
                accept="image/*"
                class="w-96 variant-glass-warning"
                required={$slct.event_presenter_obj.image_li_json && !$slct.event_presenter_obj.image_li_json.headshot}
                on:change={(e) => {
                    console.log('*** FileDropzone change event ***', e);

                    if (e.target.files.length) {
                        placeholder_li.image_headshot = `Ready to upload: ${e.target.files[0].name}`;
                    } else {
                        placeholder_li.image_headshot = 'No files selected.';
                    }
                }}
                >
                <svelte:fragment slot="lead"><span class="fas fa-file-upload"></svelte:fragment>
                <svelte:fragment slot="message"><strong>Upload your file</strong> (drag and drop)</svelte:fragment>
                <svelte:fragment slot="meta">High resolution image files only<br>(PNG, WEBP, JPG, etc)</svelte:fragment>
            </FileDropzone>
            {@html placeholder_li.image_headshot}
        </label>

    </section>

    <button
        type="submit"
        class="btn variant-glass-primary m-2"
        disabled={($ae_loc.mod.events.disable_submit__event_presenter_obj)}
        on:click={() => {
            console.log('*** Save button clicked ***');
            // if (!confirm('Are you sure you want to save this event_presenter?')) {return false;}
            // handle_submit_form();
            // handle_submit_form;
        }}
        >
        <span class="fas fa-check mx-1"></span>
        Save and continue
    </button>

    </form>


    {:else if $store_current_tab === 'social'}


    <form
        class="modal-form {$ae_loc.hub.classes__form}"
        on:submit|preventDefault={handle_submit_form}
        >

    <h3 class="h4">Website and Social Media</h3>
    <fieldset class="speaker__website_url space-y-4">
        <legend class="legend input_required">Website URL:</legend>

        <label for="website_url" class="label">
            <!-- Website URL -->
            <input type="url" id="website_url" name="website_url" class="input text-xs w-96 variant-glass-warning" placeholder="Website URL (https://example.org)" bind:value={$slct.event_presenter_obj.website_url} autocomplete="url" required />
        </label>

        <p class="text-xs italic variant-glass-tertiary max-w-96">The URLs should begin with "https://" or "http://"</p>
    </fieldset>

    <!-- Ask for common social media URLs. (Twitter, Facebook, Instagram, etc) -->
    <fieldset class="speaker__social_media space-y-4">
        <legend class="legend">Social Media:</legend>

        <label for="social_media_facebook" class="label">
            <!-- Facebook -->
            <input type="url" id="social_media_facebook" name="social_media_facebook" class="input text-xs w-96" placeholder="Facebook" value={$slct.event_presenter_obj.social_li_json && $slct.event_presenter_obj.social_li_json.facebook ? $slct.event_presenter_obj.social_li_json.facebook : ''} autocomplete="url" />
        </label>
        <label for="social_media_instagram" class="label">
            <!-- Instagram -->
            <input type="url" id="social_media_instagram" name="social_media_instagram" class="input text-xs w-96" placeholder="Instagram" value={$slct.event_presenter_obj.social_li_json && $slct.event_presenter_obj.social_li_json.instagram ? $slct.event_presenter_obj.social_li_json.instagram : ''} autocomplete="url" />
        </label>
        <label for="social_media_linkedin" class="label">
            <!-- LinkedIn -->
            <input type="url" id="social_media_linkedin" name="social_media_linkedin" class="input text-xs w-96" placeholder="LinkedIn" value={$slct.event_presenter_obj.social_li_json && $slct.event_presenter_obj.social_li_json.linkedin ? $slct.event_presenter_obj.social_li_json.linkedin : ''} autocomplete="url" />
        </label>
        <label for="social_media_twitter" class="label">
            <!-- X (Twitter) -->
            <input type="url" id="social_media_twitter" name="social_media_twitter" class="input text-xs w-96" placeholder="X (Twitter)" value={$slct.event_presenter_obj.social_li_json && $slct.event_presenter_obj.social_li_json.twitter ? $slct.event_presenter_obj.social_li_json.twitter : ''} autocomplete="url" />
        </label>
    </fieldset>

    <button
        type="submit"
        class="btn variant-glass-primary m-2"
        disabled={($ae_sess.mod.sponsorships.disable_submit__sponsorship_obj)}
        on:click={() => {
            console.log('*** Save marketing button clicked ***');
        }}
        >
        <span class="fas fa-check mx-1"></span>
        Save and continue
    </button>

    </form>


    {:else if $store_current_tab === 'summary'}

    <section class="summary space-y-4">
        <button
            class="btn variant-soft-secondary mx-1 float-right"
            disabled={(!$slct.event_presenter_obj.email)}
            title="Send confirmation email to speaker"
            on:click={() => {
                if (!confirm(`Are you sure you want to send this email to ${$slct.event_presenter_obj.email}?`)) {return false;}

                send_summary_email();
                }}
            >
            <span class="fas fa-paper-plane mx-1"></span>
            Send Confirmation Email
        </button>

        <h2 class="h3">Summary</h2>
        <div>Name: {$slct.event_presenter_obj.full_name ?? '-- No Name Given --'}</div>
        <div>Professional title: {$slct.event_presenter_obj.professional_title ?? '-- No Title Given --'}</div>
        <div>Affiliations: {$slct.event_presenter_obj.affiliations ?? '-- No Affiliations Given --'}</div>
        <div>Email: {$slct.event_presenter_obj.email ?? '-- No Email Given --'}</div>
        <div>Biography:
        <pre class="biography pre_wrap">{$slct.event_presenter_obj.biography ?? '-- Not Entered --'}</pre>
        </div>
        <div>
            Headshot:
            {@html placeholder_li.image_headshot}
        </div>


    <!-- <form
        class="modal-form {$ae_loc.hub.classes__form}"
        on:submit|preventDefault={handle_submit_form}
        > -->

    <!-- <fieldset class="event_presenter__more_questions">
        <legend class="legend">Questions and Comments</legend>

        <p>Please let us know if you have any questions or comments pertaining to your participation as a speaker at CHOW 2024. A member of the CHOW Team will follow up to assist.</p>

        <label class="label ae_label event_presenter__comments">Comments
            <textarea name="comments" id="comments" class="textarea ae_value event_presenter__comments tinymce_editor editor_basic" rows="5" cols="70" bind:value={$slct.event_presenter_obj.comments} placeholder="Any comments or questions about event_presenter."></textarea>
        </label>
    </fieldset> -->

    <!-- <button
        type="submit"
        class="btn variant-glass-primary m-2"
        disabled={($ae_loc.mod.events.disable_submit__event_presenter_obj)}
        on:click={() => {
            console.log('*** Save more button clicked ***');
            // if (!confirm('Are you sure you want to save this event_presenter?')) {return false;}
            // handle_submit_form();
            // handle_submit_form;
        }}
        >
        <span class="fas fa-check mx-1"></span>
        Save
    </button> -->

    <!-- </form> -->

    </section>

    {/if}

    </svelte:fragment>
    </TabGroup>

    <!-- </form> -->

    <footer class="{parent.regionFooter}">
        {#if $slct.event_presenter_id}
        <!-- {#if $ae_loc.trusted_access} -->
        <span class="ae_actions">

        {#if $slct.event_presenter_id}
        {#if $ae_loc.administrator_access}
        <button
            on:click={() => {
                if (!confirm('Are you sure you want to delete this speaker?')) {return false;}
                handle_delete_event_presenter_obj({event_presenter_id: $slct.event_presenter_id, method: 'delete'});

                $slct.event_presenter_id = null;
                $slct.event_presenter_obj = {};
            }}
            class="btn btn-sm variant-glass-warning mx-1" type="button"
            title="Delete record permanently"
            >
            <span class="fas fa-minus mx-1"></span> Delete
        </button>
        {:else if $ae_loc.trusted_access}
        <button
            on:click={() => {
                if (!confirm('Are you sure you want to disable this speaker?')) {return false;}
                handle_delete_event_presenter_obj({event_presenter_id: $slct.event_presenter_id, method: 'disable'});

                $slct.event_presenter_id = null;
                $slct.event_presenter_obj = {};
            }}
            class="btn btn-sm variant-glass-warning mx-1" type="button"
            title="Disable record to delete"
            >
            <span class="fas fa-minus mx-1"></span> Delete
        </button>
        {:else}
        <button
            on:click={() => {
                if (!confirm('Are you sure you want to hide this speaker?')) {return false;}
                handle_delete_event_presenter_obj({event_presenter_id: $slct.event_presenter_id, method: 'hide'});

                $slct.event_presenter_id = null;
                $slct.event_presenter_obj = {};
            }}
            class="btn btn-sm variant-glass-warning mx-1" type="button"
            title="Hide record to delete"
            >
            <span class="fas fa-comment-slash mx-1"></span> Delete
        </button>
        {/if}
        {/if}

        <button
            class="btn btn-sm variant-soft-secondary mx-1"
            use:clipboard={$ae_loc.mod.events.presenter_link}
            title={`Copy link to this speaker submission (ID: ${$slct.event_presenter_id})`}
            >
            <span class="fas fa-copy mx-1"></span>
            Copy link for speaker submission
        </button>
        </span>
        {/if}


        {#if $ae_sess.mod.events.submit_status == 'saving'}
            <div class="awaiting alert_msg_pulse" out:fade={{ duration: 2000 }}>Saving...</div>
        {:else if $ae_sess.mod.events.submit_status == 'saved'}
            <div class="awaiting" out:fade={{ duration: 2000 }}>Finished saving</div>
        {:else}
            <!-- <div class="awaiting" out:fade={{ duration: 2000 }}>Nothing here yet</div> -->
        {/if}

        {#await ae_promises.update__event_presenter_obj}
            <div class="modal-loading">
                <span class="fas fa-spinner fa-spin"></span>
                <span class="loading-text">
                    <!-- <ProgressRadial value={undefined} /> -->
                    Saving...
                </span>
            </div>
        {:then update__event_presenter_obj_result}
            {#if update__event_presenter_obj_result}
            <div class="modal-loading">
                <span class="fas fa-check-circle"></span>
                <span class="loading-text">Successfully saved!</span>
            </div>
            {/if}
        {:catch error}
            <div class="modal-loading">
                <span class="fas fa-exclamation-triangle"></span>
                <span class="loading-text">Error: {error.message}</span>
            </div>
        {/await}


        <button class="btn variant-glass-primary" on:click={parent.onClose}>
            <span class="fas fa-times mx-1"></span>
            Close
        </button>

        <!-- {#if $slct.event_presenter_id}
            <button
                type="submit"
                class="btn {parent.buttonPositive}"
                disabled={($ae_loc.mod.events.disable_submit__event_presenter_obj)}
                on:click={() => {
                    console.log('*** Save button clicked ***');
                    if (!confirm('Are you sure you want to save this event_presenter?')) {return false;}
                    handle_submit_form();
                }}
                >
                <span class="fas fa-check mx-1"></span>
                Save
            </button>
        {:else}
            <button
                type="submit"
                class="ae_btn btn_primary"
                disabled={($ae_loc.mod.events.disable_submit__event_presenter_obj)}
                on:click={() => {
                    if (!confirm('Are you sure you want to create this event_presenter?')) {return false;}
                }}
                >
                <span class="fas fa-plus mx-1"></span>
                Save New Event
            </button>
        {/if} -->
    </footer>
</section>
{/if}


<style>
</style>
