<template>
  <PageLayout title="Featured Listings" description="Generate and configure the shortcode of various styles featured Listings page, then create a new WordPress page and insert the shortcode into it.">
    <template #button>
      <span v-if="copied">Copied!</span>
      <button v-else class="btn-save" @click.prevent="onCopy">Copy to clipboard</button>
    </template>
    <div class="form-groups">
      <MetaTags class="listing-groups" ref="metaTags" v-model="metaTagHtml" isShortCode/>
      <ListingFilter @ready="dateFields=$event" style="padding-left: 0" ref="listingRef" />
      <StyleConfig :config="defaultStyleConfig" @update="updateStyleConfig" ref="styleConfig" style="padding-left: 0"></StyleConfig>
    </div>
  </PageLayout>
</template>

<script setup>
import { ref, provide, useTemplateRef } from 'vue'
import ListingFilter from '@/admin/common/ListingFilter.vue';
import StyleConfig from "@/admin/idx-pages/featured-listings/styleConfig.vue";
import PageLayout from "@/admin/common/PageLayout.vue";
import { useCopy } from '@/hooks/useCopy.js'
import defaultStyleConfig from './default-style-config';
import MetaTags from "@/admin/common/MetaTags.vue";
import { formatShortConditions, saveShortCodeLog ,types} from "@/admin/shortcodes/common.js";

const allConditions = ref([])
provide('allConditions', allConditions)
// page-config
const metaTagHtml = ref('')
const metaTagsRef = useTemplateRef('metaTags')
const { copied, copyCode} = useCopy()
const styleConfigRef = useTemplateRef('styleConfig')
const listingFilter = useTemplateRef('listingRef');
const styleData = ref({})
function updateStyleConfig(styleConfigData){
  styleData.value=styleConfigData
}
let dateFields = []
function onCopy(){
  const curStyleConfig = styleConfigRef.value.getCurrentConfig()
  const layout = curStyleConfig.featuredListingStyle
  const layoutConfig = JSON.parse(JSON.stringify(curStyleConfig[layout] || {}));
  const data = {
    layout: layout,
    layout_config: layoutConfig,
    meta: metaTagsRef.value.getValueString(),
    conditions: formatShortConditions(allConditions.value, dateFields),
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    sort: listingFilter.value.sortCondition
  }
  const shortcode=`[lofty_idx_featured_listing][[${JSON.stringify(data, null, 2)}]][/lofty_idx_featured_listing]`
  copyCode(shortcode);
  saveShortCodeLog(types.FeaturedListings, shortcode);
}
</script>

<style lang="scss" scoped>
.form-groups {
  padding: 22px 20px 20px;
}
.form-group {
  display: flex;
  flex-direction: column;
  row-gap: 8px;
  margin-bottom: 20px;
  input {
    width: max-content;
  }
  label {
    width: 100px;
    font-weight: 500;
    font-size: 11px;
    color: $gray-800;
  }
}
</style>