<script setup>
import Swal from 'sweetalert2';
import { ref, onMounted, computed ,watch } from 'vue';
import LogoIkea from '@/assets/price-tag.svg';
import {
    FwbSelect,
    FwbNavbar,
    FwbNavbarCollapse,
    FwbNavbarLink,
    FwbNavbarLogo,
    FwbButton,
    FwbDropdown,
    FwbListGroup,
    FwbListGroupItem,
    FwbMegaMenu,
    FwbMegaMenuDropdown,
    FwbRadio,
    FwbFooter,
    FwbFooterCopyright,
    FwbFooterLink,
    FwbFooterLinkGroup,
} from 'flowbite-vue';

import Multiselect from "vue-multiselect";
import { settingsStore } from '../settingsStore.js';
const menu = ref([])
const geoip = ref(null)
const ccodes = ref([])
const rates = ref([])
const currency = ref([])
const countryCurrency = ref([])
const currencyHash = ref([])

const ccountry = ref([])

const ccountry_list = computed(() => {
    let computed_list = settingsStore.ccountry_list.filter((c) => (c.offline == (settingsStore.online ? 'N' : 'Y')) || settingsStore.online == true);
    console.log('COMPUTED_LIST',computed_list);
    return computed_list;
})

const scountry_list = computed(() => {
    let computed_list = settingsStore.ccountry_list.filter((c) => (c.offline == (settingsStore.online ? 'N' : 'Y')) || settingsStore.online == true);
    console.log('COMPUTED_LIST',computed_list);
    return computed_list;
})

let tsettings = computed(() => {
    let country = "GB";
    console.log('AAAAA',settingsStore.country);
    if (settingsStore.country != "") country = settingsStore.country.code;

    if (settingsStore.currency != "EUR")
        settingsStore.currencyCoef = currencyHash.value[settingsStore.currency];
    else settingsStore.currencyCoef = 1.0;

    return `${country} / ${settingsStore.currency}`;
});


const fetch_menu = async () => {
    try {
        const response = await axios.get(route('menu.user'))
        menu.value = response.data;
    } catch (e) {
        const response = await Swal.fire({
            title: __('are you want to try again') + '?',
            text: __(`${e}`),
            icon: 'question',
            showCancelButton: true,
            showCloseButton: true,
        })

        response.isConfirmed && fetch()
    }
}

const fetch_ccodes = async () => {
  try {
    const response2 = await axios.get(route("geo.ip.get"));
    geoip.value = response2.data;

    const response = await axios.get(route("ccountry.codes"));
    ccodes.value = response.data;
    ccodes.value = Object.entries(ccodes.value)
      .map(([k, v]) => {
        if (v !== null) return { country: k, code: v };
      })
      .filter((n) => n);
    console.log("ccodes=", ccodes.value);
  } catch (e) {
    const response = await Swal.fire({
      title: __("are you want to try again") + "?",
      text: __(`${e}`),
      icon: "question",
      showCancelButton: true,
      showCloseButton: true,
    });

    response.isConfirmed && fetch();
  }
};

const fetch_rates = async () => {
  try {
    const response = await axios.get(route("rates.index"));
    rates.value = response.data;
    currency.value = rates.value.map((currency) => currency.currency);
    countryCurrency.value = Object.fromEntries(
      rates.value.map((currency) => [currency.country_name, currency.currency])
    );
    currencyHash.value = Object.fromEntries(
      rates.value.map((currency) => [currency.currency, currency.rate])
    );

    currency.value.unshift("EUR");
    console.log("RATE=", rates.value);
    console.log("HASH=", currencyHash.value);
  } catch (e) {
    const response = await Swal.fire({
      title: __("are you want to try again") + "?",
      text: __(`${e}`),
      icon: "question",
      showCancelButton: true,
      showCloseButton: true,
    });

    response.isConfirmed && fetch();
  }
};


const fetch = async () => {
  try {
    const response = await axios.get(route("ccountry.active"));
    ccountry.value = response.data;
    let aCntry = ccountry.value.map((country) => [country.country_name]);
    settingsStore.ccountry_filter.push(...aCntry);

    console.log('CCOUNTRY=',ccountry);
    settingsStore.ccountry_list = ccountry.value.map((country) => {
        return {
          name: country.country_name,
          code: country.country_code,
          status: country.status,
          offline: country.only_offline,
         };
    });

  } catch (e) {
    const response = await Swal.fire({
      title: __("are you want to try again") + "?",
      text: __(`${e}`),
      icon: "question",
      showCancelButton: true,
      showCloseButton: true,
    });

    response.isConfirmed && fetch();
  }
};

function selectCurrency(item, id) {

    if (typeof countryCurrency.value[settingsStore.country.country] !== 'undefined') {
        settingsStore.currency = countryCurrency.value[settingsStore.country.country];
    } else {
        settingsStore.currency = "EUR";
    }

    if (settingsStore.currency != "EUR")
        settingsStore.currencyCoef = currencyHash.value[settingsStore.currency];
    else settingsStore.currencyCoef = 1.0;
}

function selectCountry(item, id) {
  let cCntry = [["Country"]];

  let aCntry = settingsStore.countries.map((country) => [country.name]);
  if (settingsStore.countries.length == 0) aCntry = ccountry.value.map((country) => [country.country_name]);

  settingsStore.ccountry_filter = cCntry;
  settingsStore.ccountry_filter.push(...aCntry);
}

watch(ccodes, (codes) => {
  console.log("NNN=", codes);
  console.log("IP=", geoip.value);

  let fonud = false;
  scountry_list.value.forEach((c) => {
    if (c.code == geoip.value.iso_code) {
        settingsStore.country = c;
        found = true;
    }
  });
  if (fonud == false) settingsStore.country = scountry_list.value.filter((c) => {return c.code == 'GB'})[0];
  console.log("FC=", settingsStore.country);
});

onMounted(fetch);
onMounted(fetch_rates);
onMounted(fetch_ccodes);
onMounted(fetch_menu);
</script>

<style>
@import "flag-icons/css/flag-icons.min.css";
</style>
<template>
    <fwb-navbar class="px-0">
        <template #logo>
            <fwb-navbar-logo alt="IKEA price comparison" :image-url="LogoIkea" :link="route('root')">
                IKEA price comparison
            </fwb-navbar-logo>
        </template>

        <template #default="{ isShowMenu }">
            <fwb-navbar-collapse :is-show-menu="isShowMenu" v-if="menu.length > 0">

                <fwb-navbar-link :link="route(menu[0].route_or_url)">
                    Home
                </fwb-navbar-link>
                <fwb-mega-menu link="#">
                    <template #default>{{ tsettings }}</template>
                </fwb-mega-menu>
                <template v-for="item in menu[0].childs" v-if="menu.length > 0">
                    <fwb-navbar-link :link="route(item.route_or_url)">
                        {{ item.name }}
                    </fwb-navbar-link>
                </template>
                <fwb-navbar-link link="#">
                    <form action="https://www.paypal.com/donate" method="post" target="_top">
                         <input type="hidden" name="hosted_button_id" value="U6QGUXVDUDBB8" />
                         <button type="sumbit">Donate</button>
                    </form>
                </fwb-navbar-link>
            </fwb-navbar-collapse>

        </template>
        <template #mega-menu-dropdown>
            <fwb-mega-menu-dropdown>

                    <div class="flex-auto">
                        <div class="flex flex-col start-0">
                            <span class="font-extrabold font-mono">Country in which search product</span>
                        </div>
                        <div class="">
                            <multiselect @select="selectCurrency" placeholder="All" :close-on-select="true" :multiple="false" v-model="settingsStore.country" :options="scountry_list" label="name" track-by="code">
                                <template #option="slotProps">
                                    <span :class="'pl-6 fi fi-' + slotProps.option.code.toLowerCase()">{{ slotProps.option.name }}</span>
                                </template>
                            </multiselect>
                        </div>
                    </div>
                    <div class="flex-auto">
                        <div class="flex flex-col start-0">
                            <span class="font-extrabold font-mono">Countries in which compare</span>
                        </div>
                        <div>
                            <multiselect placeholder="All" @remove="selectCountry" @select="selectCountry" :close-on-select="false" :multiple="true" v-model="settingsStore.countries" :options="ccountry_list" label="name" track-by="name">
                                <template #option="slotProps">
                                    <span :class="'pl-6 fi fi-' + slotProps.option.code.toLowerCase()">{{ slotProps.option.name }}</span>
                                </template>
                            </multiselect>
                        </div>
                    </div>

                    <div class="flex-auto">
                        <div class="flex flex-col start-0">
                            <span class="font-extrabold font-mono">Currency recalculation</span>
                        </div>
                        <fwb-radio v-for="c in currency" v-model="settingsStore.currency" name="radio" :label="c" :value="c" />
                    </div>

            </fwb-mega-menu-dropdown>
        </template>
    </fwb-navbar>
    <div class="m-3 pb-24">
        <slot />
    </div>
    <fwb-footer class="p-4 rounded-none bg-white shadow md:flex md:items-center md:justify-between md:p-6 dark:bg-gray-900 bottom-0 absolute w-full">
        All information without guarantee
    <fwb-footer-copyright
      by="JD a MH Slovakia™"
      href="/"
      copyright-message=""
    />
   </fwb-footer>
</template>
<style src="vue-multiselect/dist/vue-multiselect.css"></style>
