<script lang="ts">
export let data;
// console.log(`ae_ Svelte Sponsorships +page data:`, data);

import { onMount } from 'svelte';


// https://github.com/skeletonlabs/skeleton/blob/master/packages/skeleton/src/lib/utilities/Modal/types.ts
// To retrieve the store, getModalStore must be invoked at the top level of your component!
import { getDrawerStore, getModalStore, ProgressRadial } from '@skeletonlabs/skeleton';
import type {
    DrawerSettings,
    ModalSettings,
    ModalComponent,
    ModalStore
    } from '@skeletonlabs/skeleton';
const modalStore = getModalStore();

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

import Edit_modal_sponsorship_obj from './10_edit_modal__sponsorship_obj.svelte';
import List_sponsorship_obj from './10_list__sponsorship_obj.svelte';
import View_modal_sponsorship_obj from './10_view_modal__sponsorship_obj.svelte';


// Editing
const modalComponentEditSponsorshipObj: ModalComponent = { ref: Edit_modal_sponsorship_obj, props: {container_class_li: 'w-full p-4 space-y-4 card ae_modal_scrollfix'} };

const modal_edit__sponsorship_obj: ModalSettings = {
	type: 'component',
	component: modalComponentEditSponsorshipObj,
    title: 'Sponsor Form', // Editing Sponsorship
    position: '', // default is "items-center"

    response: (r: boolean | undefined) => handle_modal_close(r)
};

// Viewing
const modalComponentViewSponsorshipObj: ModalComponent = { ref: View_modal_sponsorship_obj, props: {container_class_li: 'w-full p-4 space-y-4 card ae_modal_scrollfix'} };

const modal_view__sponsorship_obj: ModalSettings = {
	type: 'component',
	component: modalComponentViewSponsorshipObj,
    title: 'Sponsorship Submission', // Viewing Sponsorship
    position: '', // default is "items-center"

    // Provide arbitrary classes to the backdrop and modal elements:
	// backdropClasses: '!bg-green-500',
    // modalClasses: 'w-modal-wide',

    // Provide arbitrary metadata to your modal instance:
    // meta: { fn: do_something_function }

    response: (r: boolean | undefined) => handle_modal_close(r)
};

// This function waits for the response from one of the modals. Do stuff when the modal is closed.
function handle_modal_close(response: boolean | undefined) {
    console.log('Modal closed. Response:', response);

    ae_util.handle_url_and_message('sponsorship_id', null);

    // We do NOT want to keep these values if it is closed and not just switching from view to edit. A "smart" transition?
    // if (!$ae_loc.mod.sponsorships.show_edit__sponsorship_obj && !$ae_loc.mod.sponsorships.show_view__sponsorship_obj) {
        console.log('Clearing the modal store and the selected sponsorship object.');
        $slct.sponsorship_id = null;
        $slct.sponsorship_obj = null;
    // } else {
    //     console.log('Not clearing the modal store and the selected sponsorship object.');
    // }
}


$ae_loc.hostname = data.url.hostname;
$ae_loc.site_domain = data.url.origin;

// We don't want the edit or view to show up by default. Maybe if we see an object ID param in the URL, we can show a modal.
$ae_loc.mod.sponsorships.show_edit__sponsorship_obj = false;
$ae_loc.mod.sponsorships.show_view__sponsorship_obj = false;
if ($ae_loc.trusted_access) {
    $ae_loc.mod.sponsorships.show_list__sponsorship_obj_li = true;
} else {
    $ae_loc.mod.sponsorships.show_list__sponsorship_obj_li = false;
}

let ae_sponsorship_cfg_obj_get_promise: Promise<any>;
let ae_sponsorship_obj_li_get_promise: Promise<any>;
let ae_sponsorship_obj_get_promise: Promise<any>;


// This might need to be reviewed and compared to speakers version again
if ($ae_loc.account_id) {
    $slct.account_id = $ae_loc.account_id;
	// handle_load_ae_obj_id__account({account_id: $slct.account_id, try_cache: false});
    handle_load_ae_obj_li__sponsorship({account_id: $slct.account_id, try_cache: false});
}


onMount(() => {
    console.log('Sponsorships: +page.svelte');

    // console.log(`$ae_loc = `, $ae_loc);

	let href_url = window.location.href;
	// console.log(href_url);

    $ae_loc.href_url = href_url;
    // console.log(`$ae_loc.href_url = `, $ae_loc.href_url);

    // $slct_trigger = 'msg_parent';
    ae_util.handle_url_and_message('sponsorship_cfg_id', $slct.sponsorship_cfg_id);
    ae_util.handle_url_and_message('sponsorship_id', $slct.sponsorship_id);
    if ($slct.sponsorship_id) {
        console.log(`Got an ID. Let's clear the modal store just in case!`);
        modalStore.clear();
        // Showing this modal like this seems to cause problems. The styles do not load or something.
        // console.log(`Got an ID. Let's clear the modal store and show the modal!`);
        // modalStore.trigger(modal_edit__sponsorship_obj);
    }
});


$: if ($slct_trigger == 'show_edit__sponsorship_obj' && $ae_loc.mod.sponsorships.show_edit__sponsorship_obj) {
    console.log('Show Modal Edit');
    $slct_trigger = null;

    if ($slct.sponsorship_id) {
        let location = window.location.href;
        const url = new URL(location);
        url.searchParams.set('sponsorship_id', $slct.sponsorship_id);
        // history.pushState({}, '', url);

        let message = {'sponsorship_id': $slct.sponsorship_id};
        window.parent.postMessage(message, "*");
        // console.log('Message sent to parent (iframe):', message);
    }

    // modalStore.clear();
    modalStore.trigger(modal_edit__sponsorship_obj);
}

$: if ($slct_trigger == 'show_view__sponsorship_obj' && $ae_loc.mod.sponsorships.show_view__sponsorship_obj) {
    console.log('Show Modal View');
    $slct_trigger = null;

    let location = window.location.href;
    const url = new URL(location);
    url.searchParams.set('sponsorship_id', $slct.sponsorship_id);
    // history.pushState({}, '', url);

    // modalStore.clear();
    modalStore.trigger(modal_view__sponsorship_obj);

    let message = {'sponsorship_id': $slct.sponsorship_id};
    window.parent.postMessage(message, "*");
    // console.log('Message sent to parent (iframe):', message);
}


$: if ($slct_trigger == 'load__sponsorship_obj_li') {
    console.log(`load__sponsorship_obj_li account_id=${$slct.account_id}`);

    $slct_trigger = null;

    handle_load_ae_obj_li__sponsorship({account_id: $slct.account_id, try_cache: false});
}

async function handle_load_ae_obj_li__sponsorship({account_id, try_cache=true}) {
    console.log('*** handle_load_ae_obj_li__sponsorship() ***');
    // console.log($ae_loc.mod.sponsorships);

    let enabled = $ae_loc.mod.sponsorships.enabled;
    let hidden = $ae_loc.mod.sponsorships.hidden;
    let limit = $ae_loc.mod.sponsorships.limit;
    let offset = $ae_loc.mod.sponsorships.offset;

    let params = {};

    let params_json: key_val = {};

    // console.log('params_json:', params_json);
    // console.log(params_json);

    $ae_loc.mod.sponsorships.qry_status = 'loading';
    ae_sponsorship_obj_li_get_promise = api.get_ae_obj_li_for_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'sponsorship',
        for_obj_type: 'account',
        for_obj_id: account_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        enabled: enabled,
        hidden: hidden,
        order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'updated_on': 'DESC', 'created_on': 'DESC'},
        // order_by_li: {'priority': 'DESC', 'sort': 'DESC', 'created_on': 'DESC', 'updated_on': 'DESC'},
        limit: limit,
        offset: offset,
        params_json: params_json,
        params: params,
        log_lvl: 0
        })

    .then(function (sponsorship_obj_li_get_result) {
        if (sponsorship_obj_li_get_result) {
            $slct.sponsorship_obj_li = sponsorship_obj_li_get_result;
        } else {
            $slct.sponsorship_obj_li = [];
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    })
    .finally(function () {
        $ae_loc.mod.sponsorships.qry_status = 'done';
        console.log('Object list:', $slct.sponsorship_obj_li);
    });

    return ae_sponsorship_obj_li_get_promise;
}


// Load the Sponsorship Cfg Obj with ID based on the URL param.
if (data.url.searchParams.get('sponsorship_cfg_id')) {
    $slct.sponsorship_cfg_id = data.url.searchParams.get('sponsorship_cfg_id');
    $slct_trigger = 'load__sponsorship_cfg_obj';
} else {
    $slct.sponsorship_cfg_id = $ae_loc.mod.sponsorships.cfg_id;
}
$slct_trigger = 'load__sponsorship_cfg_obj';

$: if ($slct_trigger == 'load__sponsorship_cfg_obj' && $slct.sponsorship_cfg_id) {
    console.log('Selected Sponsorship Cfg ID:', $slct.sponsorship_cfg_id);

    $slct_trigger = null;

    $ae_loc.mod.sponsorships.cfg_id = $slct.sponsorship_cfg_id;

    handle_load_ae_obj_id__sponsorship_cfg({sponsorship_cfg_id: $slct.sponsorship_cfg_id, try_cache: false});
}

async function handle_load_ae_obj_id__sponsorship_cfg({sponsorship_cfg_id, try_cache=false}) {
    console.log(`*** handle_load_ae_obj_id__sponsorship_cfg() *** sponsorship_cfg_id=${sponsorship_cfg_id}`);

    let params = {};

	// $ae_loc.mod.sponsorships.qry_status = 'loading';
    ae_sponsorship_cfg_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'sponsorship_cfg',
        obj_id: sponsorship_cfg_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        params: params,
        log_lvl: 1
        })
    .then(function (sponsorship_cfg_obj_get_result) {
        if (sponsorship_cfg_obj_get_result) {
            $slct.sponsorship_cfg_obj = sponsorship_cfg_obj_get_result;
            console.log(`sponsorship_cfg object:`, $slct.sponsorship_cfg_obj);
        }

        // Auto show the selected sponsorship ID
        // Is this pushState needed here?
        // Set the URL param "sponsorship_cfg_id" to the current sponsorship ID.
        // const url = new URL(location);
        // url.searchParams.set('sponsorship_cfg_id', $slct.sponsorship_cfg_id);
        // history.pushState({}, '', url);

        // Is this postMessage needed here?
        // let message = {'sponsorship_cfg_id': $slct.sponsorship_cfg_id};
        // window.parent.postMessage(message, "*");

        // modalStore.trigger(modal_view__sponsorship_cfg_obj);
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    })
    .finally(function () {
        // For CHOW 2024 only
        $ae_loc.mod.sponsorships.level_guest_max_li = {
            0: 0,
            1: 4, // CHOW 2024 - Friend
            2: 8, // CHOW 2024 - Supporter
            3: 8, // CHOW 2024 - Advocate
            4: 8, // CHOW 2024 - Champion
            5: 8, // CHOW 2024 - Presenting Partner
            6: 16, // CHOW 2024 - Signature Partner
            7: 16, // CHOW 2024 - Premier Partner
        };
        // $ae_loc.mod.sponsorships.level_guest_max_li = {
        //     '0': 0,
        //     '1': 4,
        //     '2': 8,
        //     '3': 8,
        //     '4': 8,
        //     '5': 16, // This is a guess for CHOW 2024!!!
        //     '6': 16, // This is a guess for CHOW 2024!!!
        // };
        // if ($slct.sponsorship_cfg_obj.info_about_levels) {
        //     $slct.sponsorship_cfg_obj.info_about_levels = JSON.parse($slct.sponsorship_cfg_obj.info_about_levels);
        // }
        // $ae_loc.hub.sponsorship_cfg_id_qry_status = 'done';
    });

    return ae_sponsorship_cfg_obj_get_promise;
}


// Load the Sponsorship Obj with ID based on the URL param.
$: if ($slct_trigger == 'load__sponsorship_obj' && $slct.sponsorship_id) {
    console.log('Selected Sponsorship ID:', $slct.sponsorship_id);

    $slct_trigger = null;

    handle_load_ae_obj_id__sponsorship({sponsorship_id: $slct.sponsorship_id, try_cache: false});
}

async function handle_load_ae_obj_id__sponsorship({sponsorship_id, try_cache=false}) {
    console.log(`*** handle_load_ae_obj_id__sponsorship() *** sponsorship_id=${sponsorship_id}`);

    let params = {};

	// $ae_loc.hub.sponsorship_id_qry_status = 'loading';
    ae_sponsorship_obj_get_promise = api.get_ae_obj_id_crud({
        api_cfg: $ae_api,
        obj_type: 'sponsorship',
        obj_id: sponsorship_id,
        use_alt_table: false, // NOTE: This will use the table_name_alt value instead of the table_name value in the API config.
        use_alt_base: false, // NOTE: This will use the base_name_alt value instead of the base_name value in the API config.
        params: params,
        log_lvl: 0
        })
    .then(function (sponsorship_obj_get_result) {
        if (sponsorship_obj_get_result) {

            if (!sponsorship_obj_get_result.sponsorship_id_random || !sponsorship_obj_get_result.sponsorship_cfg_id_random) {
                console.log('WARNING: These results do not seem correct. Trigger a reload of the object.');
                $slct_trigger = 'load__sponsorship_obj';
                return false;
            }

            $slct.sponsorship_obj = sponsorship_obj_get_result;
            console.log(`sponsorship object:`, $slct.sponsorship_obj);
        }
    })
    .catch(function (error) {
        console.log('No results returned or failed.', error);
    });

    return ae_sponsorship_obj_get_promise;
}
</script>


<section class="ae_events_speakers md:container h-full mx-auto flex flex-col items-center space-y-4">

<header>
    <h1 class="h1 text-center">
        <!-- &AElig; - Sponsorships -->
        Sponsor Hub
    </h1>
</header>

<section>
    <button
        class="btn variant-ghost-primary"
        on:click={() => {
            // $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = true;
            $slct.sponsorship_id = null;
            $slct.sponsorship_obj = null;

            // modalStore.trigger(modal_edit__sponsorship_obj);
            $ae_loc.mod.sponsorships.show_edit__sponsorship_obj = true;
            $slct_trigger = 'show_edit__sponsorship_obj';
        }}
        >
        <span class="fas fa-edit mx-1"></span>
        Start Sponsor Submission Form
    </button>

    <!-- <button
        on:click={() => {
            console.log('Open drawer');
            drawerStore.open(drawer_settings_x);
        }}
        >
        Open Drawer X
    </button> -->

    <!-- <button
        on:click={() => {
            console.log('Open drawer');
            drawerStore.open(drawer_settings_y);
        }}
        >
        Open Drawer Y
    </button> -->

    <!-- <button
        on:click={() => {
            console.log('Open drawer');
            drawerStore.open(drawer_settings_edit);
        }}
        >
        Open Drawer Edit
    </button> -->
</section>

<section class="sponsorships_list ae_h_scrollfix">
    {#await ae_sponsorship_obj_li_get_promise}
    <div class="modal-loading">
        <span class="fas fa-spinner fa-spin"></span>
        <span class="loading-text">
            Loading...
        </span>
    </div>
    {/await}
{#if $slct.sponsorship_obj_li && $ae_loc.mod.sponsorships.show_list__sponsorship_obj_li}
<List_sponsorship_obj />
{/if}
</section>

</section>


<style lang="postcss">
</style>
