<script setup>
import { string } from 'alga-js'
import { toast } from 'bulma-toast'
import { SelectBox } from 'tedir-select'
import { DatePicker } from 'tedir-calendar'
import { AttachBox } from 'tedir-dropzone'
import CountryPickerModal from '../sales/CountryPickerModal.vue'


const { getMenuType } = useRoleMenu()

// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')


const props = defineProps({
  modelValue: Object,
  tab: String
})

const emit = defineEmits(['update:modelValue', 'update:tab', 'save'])

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')
const config = useRuntimeConfig()

// Org-bpartner isHideQty flag: hides the whole Quantities card.
const { showStockQty, load: loadHideQty } = useHideQty()

const clientName = ref('')
onMounted(() => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
  defaultSideBarMenu.value = getMenuType()
  setOptions('references/labelprinter', 'label_printers')
  loadHideQty()
})


const form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue.uid || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  strapiProductId: props.modelValue.strapiProductId || '',
  strapiProductDocumentId: props.modelValue.strapiProductDocumentId || '',
  name: props.modelValue.name || '',
  sku: props.modelValue.sku || '',
  upc: props.modelValue.upc || '',
  upc2: props.modelValue.upc2 || '',
  isActive: props.modelValue.isActive ?? true,
  value: props.modelValue.value || '',
  versionNo: props.modelValue.versionNo || '',
  description: props.modelValue.description || '',
  help: props.modelValue.help || '',
  documentNote: props.modelValue.documentNote || '',
  isSummary: props.modelValue.isSummary ?? false,
  isStocked: props.modelValue.isStocked ?? true,
  isPurchased: props.modelValue.isPurchased ?? true,
  isSold: props.modelValue.isSold ?? true,
  volume: props.modelValue.volume || 0,
  weight: props.modelValue.weight || 0,
  netWeight: props.modelValue.netWeight || 0,
  width: props.modelValue.width || 0,
  length: props.modelValue.length || 0,
  height: props.modelValue.height || 0,
  discontinued: props.modelValue.discontinued ?? false,
  isBOM: props.modelValue.isBOM ?? false,
  isEnabledBom: props.modelValue.isEnabledBom ?? false,
  isAutoCommission: props.modelValue.isAutoCommission ?? false,
  isInvoicePrintDetails: props.modelValue.isInvoicePrintDetails ?? false,
  isPickListPrintDetails: props.modelValue.isPickListPrintDetails ?? false,
  isVerified: props.modelValue.isVerified ?? false,
  guaranteeDaysMin: props.modelValue.guaranteeDaysMin || 0,
  isWebStoreFeatured: props.modelValue.isWebStoreFeatured ?? false,
  isSelfService: props.modelValue.isSelfService ?? false,
  isDropShip: props.modelValue.isDropShip ?? false,
  isExcludeAutoDelivery: props.modelValue.isExcludeAutoDelivery ?? false,
  unitsPerPack: props.modelValue.unitsPerPack || 0,
  lowLevel: props.modelValue.lowLevel || 0,
  isKanban: props.modelValue.isKanban ?? false,
  isManufactured: props.modelValue.isManufactured ?? false,
  isPhantom: props.modelValue.isPhantom ?? false,
  isOwnBox: props.modelValue.isOwnBox ?? false,
  isAutoProduce: props.modelValue.isAutoProduce ?? false,
  shelfWidth: props.modelValue.shelfWidth || 0,
  shelfHeight: props.modelValue.shelfHeight || 0,
  shelfDepth: props.modelValue.shelfDepth || 0,
  unitsPerPallet: props.modelValue.unitsPerPallet || 0,
  classification: props.modelValue.classification || '',
  customsTariffNumber: props.modelValue.customsTariffNumber || 0,
  originCountry: props.modelValue.originCountry || '',
  originCountryId: props.modelValue.originCountryId || '',
  taricCode: props.modelValue.taricCode || '',
  group1: props.modelValue.group1 || '',
  group2: props.modelValue.group2 || '',
  asin: props.modelValue.asin || '',
  mpn: props.modelValue.mpn || '',
  jfsku: props.modelValue.jfsku || '',
  fnsku: props.modelValue.fnsku || '',
  customFulfillmentPrice: props.modelValue.customFulfillmentPrice || 0,
  isCustomFulfillmentPrice: props.modelValue.isCustomFulfillmentPrice ?? false,
  fulfillmentProductPricingRules: props.modelValue.fulfillmentProductPricingRules || '',
  fulfillmentProductPricingRulesId: props.modelValue.fulfillmentProductPricingRulesId || '',
  uomId: props.modelValue.uomId || '',
  productCategoryId: props.modelValue.productCategoryId || '',
  taxCategoryId: props.modelValue.taxCategoryId || '',
  productTypeId: props.modelValue.productTypeId || 'I',
  attributeSetId: props.modelValue.attributeSetId || '',
  attributeSetInstanceId: props.modelValue.attributeSetInstanceId || '',
  revenueRecognitionId: props.modelValue.revenueRecognitionId || '',
  salesRep: props.modelValue.salesRep || user.value?.Name || '',
  salesRepId: props.modelValue.salesRepId || user.value?.id || userId.value || '',
  mailText: props.modelValue.mailText || '',
  mailTextId: props.modelValue.mailTextId || '',
  labelPrinter: props.modelValue.labelPrinter || 'labelprinter-2',
  labelPrinterId: props.modelValue.labelPrinterId || 'b',
  labelPrinterRma: props.modelValue.labelPrinterRma || '',
  labelPrinterRmaId: props.modelValue.labelPrinterRmaId || '',
  paketType: props.modelValue.paketType || '',
  paketTypeId: props.modelValue.paketTypeId || '',
  pickListCode: props.modelValue.pickListCode || '',
  qtyonhand: props.modelValue.qtyonhand || 0,
  returnQtyOnHand: props.modelValue.returnQtyOnHand || 0,
  qtyreserved: props.modelValue.qtyreserved || 0,
  qtyavilable: props.modelValue.qtyavilable || 0,
  qtypurchased: props.modelValue.qtypurchased || 0,
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false
  }
})

// Origin country (M_Product.C_Country_ID) — picked via CountryPickerModal; the flag is
// resolved from the cached countries lookup (the FK identifier alone carries no CountryCode).
const { data: countriesData } = useLookup('/api/models/c_country')
const originCountryCode = computed(() => {
  const rec = (countriesData.value?.records || []).find(c => String(c.id) === String(form.value.originCountryId))
  return rec?.CountryCode || ''
})
const countryPickerOpen = ref(false)
const openOriginCountryPicker = () => {
  if (defaultSideBarMenu.value === 'c') return
  countryPickerOpen.value = true
}
const onOriginCountrySelect = (country) => {
  form.value.originCountryId = String(country.id)
  form.value.originCountry = country.Name || ''
  save()
}
const clearOriginCountry = () => {
  form.value.originCountryId = ''
  form.value.originCountry = ''
  save()
}

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    /*if(key === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }*/
    
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const strapiProduct = ref({})
const getStrapiProduct = async () => {
  strapiProduct.value = {}
  if(form.value.strapiProductDocumentId) {
    const res = await $fetch(`/api/materials/products/${form.value.strapiProductDocumentId}/galleries`)
    if(res?.data) {
      strapiProduct.value = res.data
    }
  }
}
const productGalleries = ref([])
const getProductGalleries = async () => {
  productGalleries.value = []
  if(form.value.strapiProductDocumentId) {
    const res = await $fetch(`/api/materials/products/${form.value.strapiProductDocumentId}/galleries/images`)
    if(res) {
      productGalleries.value = res
    }
  }
}
// Limited roles ('c') may not receive Strapi_Product_documentId from iDempiere
// (column security), which left the main image + gallery empty for them. Resolve
// the Strapi product by M_Product_ID (service token, role-independent) and
// backfill the ids so the existing gallery loaders work for every role.
const resolveStrapiLink = async () => {
  if(form.value.strapiProductDocumentId || !form.value.id) return
  try {
    const res = await $fetch(`/api/materials/products/${form.value.id}/strapi-link`, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res?.documentId) {
      form.value.strapiProductId = String(res.id || '')
      form.value.strapiProductDocumentId = String(res.documentId || '')
    }
  } catch (e) {}
}

const loadGallery = async () => {
  await resolveStrapiLink()
  getStrapiProduct()
  getProductGalleries()
}
onMounted(loadGallery)

watch(() => props.modelValue, () => {
  form.value = props.modelValue
  loadGallery()
})

const productGalleryFiles = ref([])
const productGalleryHandler = async (files) => {
  //console.log(files)
  if(form.value.id && form.value.strapiProductId) {
    files.forEach(async (file) => {
      const formData = new FormData()
      formData.append('field', 'image')
      formData.append('ref', 'api::m-product.m-product')
      formData.append('refId', form.value.strapiProductId)
      formData.append('files', file)
      formData.append('fileInfo', JSON.stringify({
        caption: String(form.value.id), 
        alternativeText: String(form.value.uid), 
        //name: file.name
      }))
      const res = await fetch(config.public.strapi+'/media-api/upload', {
        method: 'POST',
        headers: {
          Authorization: 'Bearer '+config.public.strapitoken
        },
        body: formData
      })

      /*const res = await $fetch(`/api/materials/products/${form.value.id}/galleries`, {
        method: 'POST',
        headers: { 'Content-Type': 'multipart/form-data' },
        body: formData
      })*/
      if(res) {
        getProductGalleries()
        getStrapiProduct()
      }
    })
  }
  setTimeout(() => {
    productGalleryFiles.value = []
  }, 700)
}

const defaultGallery = computed(() => {
  let newGallery = productGalleries.value?.[0] ?? {}
  if(strapiProduct.value?.Main_Image && strapiProduct.value?.Main_Image != 0) {
    newGallery = productGalleries.value.filter(i => i.id == strapiProduct.value.Main_Image)?.[0] ?? {}
  }
  return newGallery
})

const confirmGallery = ref({
  show: false,
  title: 'Delete Confirmation',
  subTitle: 'Are you sure, do you want to delete this image?',
  id: ''
})
const confirmDestroyGallery = async (item) => {
  if(item.id) {
    confirmGallery.value.show = true
    confirmGallery.value.id = item.id
  }
}
const destroyGallery = async (targetId) => {
  //productGalleries.value.splice(index, 1)
  if(targetId) {
    const res = await $fetch(`/api/materials/products/${targetId}/galleries`, {
      method: 'DELETE'
    })
    if(res) {
      confirmGallery.value.id = ''
      getProductGalleries()
      getStrapiProduct()
    }
  }
}

const selectedGallery = async (gallery) => {
  if(strapiProduct.value?.documentId) {
    const res = await $fetch(`/api/materials/products/${strapiProduct.value.documentId}/galleries`, {
      method: 'PUT',
      body: {
        imageId: gallery.id
      }
    })
    if(res) {
      //getProductGalleries()
      getStrapiProduct()
    }
  } else {
    toast({
      message: 'Currently Strapi Product is not being synced yet!',
      type: 'is-warning',
      duration: 2000
    })
  }
}

const showAttachmentViewer = ref(false)
const showAttachmentViewerData = ref({})
const viewAttachmentViewer = (fileData) => {
  showAttachmentViewer.value = true
  showAttachmentViewerData.value = fileData
}
watch(showAttachmentViewer, () => {
  if(!showAttachmentViewer.value) {
    showAttachmentViewerData.value = {}
  }
})

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const convertDecimal = (value) => {
  if (typeof value === 'string') {
    // Replace comma with dot for decimal separator
    return value.replace(',', '.')
  }
  return value
}

const handleDecimalInput = (field, event) => {
  const value = event.target.value
  const convertedValue = convertDecimal(value)
  form.value[field] = convertedValue
  save()
}

const save = debounce(() => {
  // Ensure all decimal fields are properly formatted before saving
  const formattedForm = {
    ...form.value,
    volume: convertDecimal(form.value.volume),
    weight: convertDecimal(form.value.weight),
    netWeight: convertDecimal(form.value.netWeight),
    width: convertDecimal(form.value.width),
    length: convertDecimal(form.value.length),
    height: convertDecimal(form.value.height),
    customFulfillmentPrice: convertDecimal(form.value.customFulfillmentPrice)
  }
  emit('update:modelValue', formattedForm)
  emit('save', formattedForm)
})

const createStrapi = async () => {
  const res = await $fetch('/api/materials/products/create-strapi', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      name: form.value.name,
      value: form.value.value
    }
  })
  if(res) {
    form.value.strapiProductId = res.id
    form.value.strapiProductDocumentId = res.documentId
  }
}

const openOtherTab = () => {
  if(props.tab === 'basic') {
    emit('update:tab', 'classification')
  } else if(props.tab === 'classification') {
    emit('update:tab', 'gallery')
  } else if(props.tab === 'gallery') {
    emit('update:tab', 'reference')
  } else if(props.tab === 'reference') {
    emit('update:tab', 'status')
  }
}

const copyToClipboard = async (text, label) => {
  if (!text) {
    toast({
      message: `No ${label} to copy`,
      type: 'is-warning',
      duration: 2000
    })
    return
  }

  try {
    await navigator.clipboard.writeText(text)
    toast({
      message: `${label} copied to clipboard!`,
      type: 'is-success',
      duration: 2000
    })
  } catch (err) {
    toast({
      message: 'Failed to copy to clipboard',
      type: 'is-danger',
      duration: 2000
    })
  }
}
</script>

<template>
  <div>
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <template v-if="tab === 'basic'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <!-- Product Information Card -->
            <fieldset class="card-wrapper">
              <legend class="card-legend">Product Information</legend>
              <div class="columns is-desktop mb-0">
                <div class="column pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Name *</legend>
                    <input type="text" v-model="form.name" class="input field-input" @keyup="save" />
                  </fieldset>
                </div>
              </div>
              <div class="columns is-desktop mb-0">
                <div class="column pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Description</legend>
                    <textarea v-model="form.description" class="input field-textarea" @keyup="save"></textarea>
                  </fieldset>
                </div>
              </div>
            </fieldset>

            <!-- Identifier Card -->
            <fieldset class="card-wrapper mt-4">
              <legend class="card-legend">Identifier</legend>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Search Key</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.value" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @keyup="save" />
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.value, 'Search Key')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">SKU</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.sku" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @keyup="save"/>
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.sku, 'SKU')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
              </div>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Barcode (UPC/EAN)</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.upc" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @keyup="save" />
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.upc, 'Barcode')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">ASIN</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.asin" class="input field-input" @keyup="save" />
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.asin, 'ASIN')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
              </div>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Manufacturer Product Number</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.mpn" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @keyup="save" />
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.mpn, 'MPN')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">JF SKU</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.jfsku" class="input field-input" @keyup="save" />
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.jfsku, 'JF SKU')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
              </div>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">FNSKU</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.fnsku" class="input field-input" @keyup="save" />
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.fnsku, 'FNSKU')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
                <div v-if="defaultSideBarMenu !== 'c'" class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Barcode 2 (UPC/EAN)</legend>
                    <div class="d-flex gap-5px items-center">
                      <input type="text" v-model="form.upc2" class="input field-input" @keyup="save" />
                      <button type="button" class="button is-small copy-btn" title="Copy" @click="copyToClipboard(form.upc2, 'Barcode 2')">
                        <span class="tf-icon ti ti-copy ti-xs"></span>
                      </button>
                    </div>
                  </fieldset>
                </div>
              </div>
            </fieldset>

            <!-- Customs (read-only for limited roles; admins edit these in the Classification tab) -->
            <fieldset v-if="defaultSideBarMenu === 'c'" class="card-wrapper mt-4">
              <legend class="card-legend">Customs</legend>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Origin Country</legend>
                    <div class="d-flex gap-5px items-center origin-country-readonly">
                      <img v-if="originCountryCode" :src="`/flags/${originCountryCode}.svg`" :alt="originCountryCode" class="origin-country-flag" />
                      <span>{{ form.originCountry || '—' }}</span>
                    </div>
                  </fieldset>
                </div>
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Taric-Code</legend>
                    <input type="text" :value="form.taricCode" readonly class="input field-input" />
                  </fieldset>
                </div>
              </div>
            </fieldset>

            <!-- Fulfillment Card -->
            <fieldset v-if="defaultSideBarMenu !== 'c'" class="card-wrapper mt-4">
              <legend class="card-legend">Fulfillment</legend>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Custom Fulfillment Price</legend>
                    <input type="text" v-model="form.customFulfillmentPrice" class="input field-input" @input="handleDecimalInput('customFulfillmentPrice', $event)" />
                  </fieldset>
                </div>
                <div v-if="defaultSideBarMenu !== 'c'" class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Label Printer</legend>
                    <ClientOnly>
                      <SelectBox v-model="form.labelPrinterId" :options="getOptions?.['label_printers']?.reflist || [{value: form.labelPrinterId, name: form.labelPrinter}]" prop="name" dataprop="value" datatype="string" :size="5" @click="setOptions('references/labelprinter', 'label_printers')" @change="(val, opt) => { form.labelPrinter = opt?.name || val; save(); }" :loading="loading?.['label_printers'] ?? true" />
                    </ClientOnly>
                  </fieldset>
                </div>
              </div>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Options</legend>
                    <div class="d-flex flexDirection-column gap-5px" style="height: 28px; justify-content: center;">
                      <div class="check">
                        <input type="checkbox" v-model="form.isCustomFulfillmentPrice" class="checkInput" id="isCustomFulfillmentPrice" :checked="form.isCustomFulfillmentPrice" @change="save">
                        <label class="checkLabel" for="isCustomFulfillmentPrice">Is Custom Fulfillment Price</label>
                      </div>
                    </div>
                  </fieldset>
                </div>
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Fulfillment Product Pricing Rules</legend>
                    <div class="d-flex gap-5px align-items-center">
                      <div style="flex: 1;">
                        <ClientOnly>
                          <SelectBox v-model="form.fulfillmentProductPricingRulesId" :options="getOptions?.['fulfillment_product_pricing_rules']?.records || [{id: form.fulfillmentProductPricingRulesId, Name: form.fulfillmentProductPricingRules}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/cust_fulfillmentproductpricingrules', 'fulfillment_product_pricing_rules')" @change="save" :loading="loading?.['fulfillment_product_pricing_rules'] ?? true" :disabled="defaultSideBarMenu === 'c'" />
                        </ClientOnly>
                      </div>
                      <a v-if="form.fulfillmentProductPricingRulesId" :href="`/fulfillment/product-pricing-rules/${form.fulfillmentProductPricingRulesId}/edit`" target="_blank" class="button is-small is-link" title="Open Pricing Rule" style="height: 28px;">
                        <span class="tf-icon ti ti-external-link ti-xs"></span>
                      </a>
                    </div>
                  </fieldset>
                </div>
              </div>
              <div class="columns is-desktop mb-0">
                <div v-if="defaultSideBarMenu !== 'c'" class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">RMA Label Printer</legend>
                    <ClientOnly>
                      <SelectBox v-model="form.labelPrinterRmaId" :options="getOptions?.['label_printers']?.reflist || [{value: form.labelPrinterRmaId, name: form.labelPrinterRma}]" prop="name" dataprop="value" datatype="string" :size="5" @click="setOptions('references/labelprinter', 'label_printers')" @change="(val, opt) => { form.labelPrinterRma = opt?.name || val; save(); }" :loading="loading?.['label_printers'] ?? true" />
                    </ClientOnly>
                  </fieldset>
                </div>
                <div v-if="defaultSideBarMenu !== 'c'" class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Package Type</legend>
                    <select v-model="form.paketTypeId" class="select field-input" @change="save">
                      <option value="">----</option>
                      <option :value="1000204">CODE1</option>
                      <option :value="1000205">CODE2</option>
                      <option :value="1000206">CODE3</option>
                      <option :value="1000213">CODE4</option>
                      <option :value="1000857">CODE5</option>
                      <option :value="1000911">CODE6</option>
                      <option :value="1000001">CODETEST</option>
                    </select>
                  </fieldset>
                </div>
              </div>
              <div class="columns is-desktop mb-0">
                <div class="column is-half pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Pick List Code</legend>
                    <input type="text" v-model="form.pickListCode" class="input field-input" @keyup="save" />
                  </fieldset>
                </div>
              </div>
            </fieldset>

          </div>

          <div class="column is-one-third">
            <!-- Organization & Status Card -->
            <fieldset class="card-wrapper">
              <legend class="card-legend">Organization & Status</legend>
              <div v-if="defaultGallery?.id" class="thumbnailBox mb-3">
                <img v-if="defaultGallery?.formats?.small" :src="config.public.strapi+'/files-api/'+defaultGallery?.formats?.small?.hash + defaultGallery?.formats?.small?.ext" :alt="defaultGallery?.name ?? ''" />
                <img v-else :src="config.public.strapi+'/files-api/'+defaultGallery?.formats?.thumbnail?.hash + defaultGallery?.formats?.thumbnail?.ext" :alt="defaultGallery?.name ?? ''" />
              </div>
              <div class="mb-2">
                <fieldset class="field-wrapper">
                  <legend class="field-legend">Organization *</legend>
                  <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {form.organization = opt.Name; save();}" :loading="loading?.['orgs'] ?? true" />
                </fieldset>
              </div>
              <div v-if="defaultSideBarMenu !== 'c'" class="mb-2">
                <fieldset class="field-wrapper">
                  <legend class="field-legend">Tenant *</legend>
                  <input type="text" :value="clientName" class="input field-input" readonly />
                </fieldset>
              </div>
              <div v-if="defaultSideBarMenu !== 'c'">
                <fieldset class="field-wrapper">
                  <legend class="field-legend">Status</legend>
                  <div class="d-flex flexDirection-column gap-5px" style="min-height: 28px; justify-content: center;">
                    <div class="check">
                      <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" @change="save">
                      <label class="checkLabel" for="isActive">Active</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isSummary" class="checkInput" id="isSummary" :checked="form.isSummary" @change="save">
                      <label class="checkLabel" for="isSummary">Summary Level</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isEnabledBom" class="checkInput" id="isEnabledBom" :checked="form.isEnabledBom" @change="save">
                      <label class="checkLabel" for="isEnabledBom" title="BOM-/Stücklisten-Artikel darf trotzdem als Auftragsposition gesucht und hinzugefügt werden">BOM Ordering Enabled</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isAutoCommission" class="checkInput" id="isAutoCommission" :checked="form.isAutoCommission" @change="save">
                      <label class="checkLabel" for="isAutoCommission">Auto Commission</label>
                    </div>
                  </div>
                </fieldset>
              </div>
            </fieldset>

            <!-- Quantities Card (hidden when the org's bpartner has isHideQty) -->
            <fieldset v-if="showStockQty" class="card-wrapper mt-4">
              <legend class="card-legend">Quantities</legend>
              <div class="columns mb-0">
                <div class="column pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Qty on Hand</legend>
                    <input type="text" v-model="form.qtyonhand" readonly class="input field-input" />
                  </fieldset>
                </div>
                <div class="column pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Return Qty on Hand</legend>
                    <input type="text" v-model="form.returnQtyOnHand" readonly class="input field-input" />
                  </fieldset>
                </div>
              </div>
              <div class="columns mb-0">
                <div class="column pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Qty Reserved</legend>
                    <input type="text" v-model="form.qtyreserved" readonly class="input field-input" />
                  </fieldset>
                </div>
                <div class="column pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Qty Available</legend>
                    <input type="text" v-model="form.qtyavilable" readonly class="input field-input" />
                  </fieldset>
                </div>
              </div>
              <div class="columns mb-0">
                <div class="column pb-2">
                  <fieldset class="field-wrapper">
                    <legend class="field-legend">Qty Purchased</legend>
                    <input type="text" v-model="form.qtypurchased" readonly class="input field-input" />
                  </fieldset>
                </div>
                <div class="column pb-2"></div>
              </div>
            </fieldset>

            <!-- Weight Card -->
            <template v-if="!form.isSummary">
              <fieldset class="card-wrapper mt-4">
                <legend class="card-legend">Weight</legend>
                <div class="columns mb-0">
                  <div class="column pb-2">
                    <fieldset class="field-wrapper">
                      <legend class="field-legend">Weight</legend>
                      <input type="text" v-model="form.weight" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @input="handleDecimalInput('weight', $event)" />
                    </fieldset>
                  </div>
                  <div v-if="defaultSideBarMenu !== 'c'" class="column pb-2">
                    <fieldset class="field-wrapper">
                      <legend class="field-legend">Net Weight</legend>
                      <input type="text" v-model="form.netWeight" class="input field-input" @input="handleDecimalInput('netWeight', $event)" />
                    </fieldset>
                  </div>
                </div>
              </fieldset>
            </template>

            <!-- Dimensions Card -->
            <template v-if="!form.isSummary">
              <fieldset class="card-wrapper mt-4">
                <legend class="card-legend">Dimensions</legend>
                <div class="columns mb-0">
                  <div class="column pb-2">
                    <fieldset class="field-wrapper">
                      <legend class="field-legend">Width</legend>
                      <input type="text" v-model="form.width" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @input="handleDecimalInput('width', $event)" />
                    </fieldset>
                  </div>
                  <div class="column pb-2">
                    <fieldset class="field-wrapper">
                      <legend class="field-legend">Length</legend>
                      <input type="text" v-model="form.length" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @input="handleDecimalInput('length', $event)" />
                    </fieldset>
                  </div>
                  <div class="column pb-2">
                    <fieldset class="field-wrapper">
                      <legend class="field-legend">Height</legend>
                      <input type="text" v-model="form.height" :readonly="defaultSideBarMenu === 'c'" class="input field-input" @input="handleDecimalInput('height', $event)" />
                    </fieldset>
                  </div>
                </div>
              </fieldset>
            </template>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'classification'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Product Type *</label>
                <select v-model="form.productTypeId" class="select" @change="save">
                  <option value="A">Asset</option>
                  <option value="E">Expense type</option>
                  <option value="I">Item</option>
                  <option value="R">Resource</option>
                  <option value="S">Service</option>
                </select>

                <label class="label d-block mt-2">Stock Unit *</label>
                <ClientOnly>
                  <SelectBox v-model="form.uomId" :options="getOptions?.['uoms']?.records || [{id: form.uomId, Name: form.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_uom', 'uoms')" @change="save" :loading="loading?.['uoms'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Revenue Recognition</label>
                <ClientOnly>
                  <SelectBox v-model="form.revenueRecognitionId" :options="getOptions?.['revenue_recognitions']?.records || [{id: form.revenueRecognitionId, Name: form.revenueRecognition}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_revenuerecognition', 'revenue_recognitions')" @change="save" :loading="loading?.['revenue_recognitions'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Customs Tariff Number</label>
                <input type="text" v-model="form.customsTariffNumber" class="input" @keyup="save" />

                <label class="label d-block mt-2">Origin Country</label>
                <div class="d-flex gap-5px items-center">
                  <button type="button" class="button origin-country-btn" @click="openOriginCountryPicker">
                    <img v-if="originCountryCode" :src="`/flags/${originCountryCode}.svg`" :alt="originCountryCode" class="origin-country-flag" />
                    <span v-if="form.originCountry">{{ form.originCountry }}</span>
                    <span v-else class="has-text-grey">Select country…</span>
                  </button>
                  <button v-if="form.originCountryId" type="button" class="button is-small" title="Clear country" @click="clearOriginCountry">
                    <span class="tf-icon ti ti-x ti-xs"></span>
                  </button>
                </div>

                <label class="label d-block mt-2">Taric-Code</label>
                <input type="text" v-model="form.taricCode" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Product Category *</label>
                <ClientOnly>
                  <SelectBox v-model="form.productCategoryId" :options="getOptions?.['product_categories']?.records || [{id: form.productCategoryId, Name: form.productCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product_category', 'product_categories')" @change="save" :loading="loading?.['product_categories'] ?? true" />
                </ClientOnly>

                <template v-if="!form.isSummary">
                  <label class="label d-block mt-2">Tax Category *</label>
                  <ClientOnly>
                    <SelectBox v-model="form.taxCategoryId" :options="getOptions?.['tax_categories']?.records || [{id: form.taxCategoryId, Name: form.taxCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_taxcategory', 'tax_categories')" @change="save" :loading="loading?.['tax_categories'] ?? true" />
                  </ClientOnly>
                </template>

                <label class="label d-block mt-2">Mail Template</label>
                <ClientOnly>
                  <SelectBox v-model="form.mailTextId" :options="getOptions?.['mail_texts']?.records || [{id: form.mailTextId, Name: form.mailText}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_mailtext', 'mail_texts')" @change="save" :loading="loading?.['mail_texts'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Classification</label>
                <input type="text" v-model="form.classification" class="input" @keyup="save" />
              </div>
            </div>
              <label class="label d-block">Version Number</label>
              <input type="text" v-model="form.versionNo" class="input" @keyup="save" />
          </div>


          <div class="column is-one-third">
            <label class="label d-block">Classification Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isStocked" class="checkInput" id="isStocked" :checked="form.isStocked" @change="save">
                <label class="checkLabel" for="isStocked">Stocked</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isSold" class="checkInput" id="isSold" :checked="form.isSold" @change="save">
                <label class="checkLabel" for="isSold">Sold</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isPurchased" class="checkInput" id="isPurchased" :checked="form.isPurchased" @change="save">
                <label class="checkLabel" for="isPurchased">Purchased</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isOwnBox" class="checkInput" id="isOwnBox" :checked="form.isOwnBox" @change="save">
                <label class="checkLabel" for="isOwnBox">Own Box</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'gallery'">
        <div class="productGallery">
          <div v-for="(gallery, index) in productGalleries" :key="index">
            <div v-if="gallery?.formats?.thumbnail" class="galleryBox" @click.self="viewAttachmentViewer(gallery)">
<!--          <img :src="config.public.strapi+'/files-api/'+gallery.url.replace('/uploads/', '')" :alt="gallery.name" />-->
              <img :src="config.public.strapi+'/files-api/'+gallery?.formats?.thumbnail?.hash + gallery?.formats?.thumbnail?.ext" :alt="gallery.name" style="pointer-events: none;" />
              <span v-if="strapiProduct?.Main_Image == gallery.id" class="selectedGalleryBox tf-icon ti ti-square-rounded-check-filled ti-sm"></span>
              <span v-else class="chooseGalleryBox tf-icon ti ti-square-rounded ti-sm" @click="selectedGallery(gallery)"></span>
              <span class="destroyGalleryBox tf-icon ti ti-trash-x-filled ti-sm" @click="confirmDestroyGallery(gallery)"></span>
            </div>
          </div>
          <div v-if="Number(productGalleries.length || 0) === 0 && form.id !== '' && form.strapiProductId === ''">
            <button type="button" class="button" @click="createStrapi">Show Gallery Upload</button>
          </div>
          <AttachBox v-if="form.strapiProductId" v-model="productGalleryFiles" @handler="productGalleryHandler" accept="image/*">
            <div class="addGalleryBox">
              <span class="tf-icon ti ti-photo-plus ti-xl"></span>
            </div>
          </AttachBox>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Sales Representative</label>
                <ClientOnly>
                  <SelectBox v-model="form.salesRepId" :options="getOptions?.['sales_reps']?.records || [{id: form.salesRepId, Name: form.salesRep}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'sales_reps')" @change="save" :loading="loading?.['sales_reps'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Part Type</label>
                <ClientOnly>
                  <SelectBox v-model="form.partTypeId" :options="getOptions?.['part_types']?.records || [{id: form.partTypeId, Name: form.partType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_parttype', 'part_types')" @change="save" :loading="loading?.['part_types'] ?? true" />
                </ClientOnly>
              </div>
              <div class="column is-half">
                <template v-if="!form.isSummary">
                  <label class="label d-block">Freight Category</label>
                  <ClientOnly>
                    <SelectBox v-model="form.freightCategoryId" :options="getOptions?.['freight_categories']?.records || [{id: form.freightCategoryId, Name: form.freightCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_freightcategory', 'freight_categories')" @change="save" :loading="loading?.['freight_categories'] ?? true" />
                  </ClientOnly>
                </template>

                <template v-if="!form.isSummary && form.isStocked">
                  <label class="label d-block mt-2">Locator</label>
                  <ClientOnly>
                    <SelectBox v-model="form.locatorId" :options="getOptions?.['locators']?.records || [{id: form.locatorId, Value: form.locator}]" prop="Value" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_locator', 'locators')" @change="save" :loading="loading?.['locators'] ?? true" />
                  </ClientOnly>
                </template>
              </div>
            </div>

            <div v-if="!form.isSummary && form.isStocked" class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Shelf Width</label>
                <input type="text" v-model="form.shelfWidth" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Shelf Depth</label>
                <input type="text" v-model="form.shelfDepth" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Shelf Height</label>
                <input type="text" v-model="form.shelfHeight" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Units Per Pallet</label>
                <input type="text" v-model="form.unitsPerPack" class="input" @keyup="save" />
              </div>
            </div>

            <label class="label d-block mt-2">Help/Comment</label>
            <textarea v-model="form.help" class="input"></textarea>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Reference Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isStocked" class="checkInput" id="isStocked" :checked="form.isStocked" @change="save">
                <label class="checkLabel" for="isStocked">Stocked</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isDropShip" class="checkInput" id="isDropShip" :checked="form.isDropShip" @change="save">
                <label class="checkLabel" for="isDropShip">Drop Shipment</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'status'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div v-if="!form.isSummary" class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block">Attribute Set</label>
                <ClientOnly>
                  <SelectBox v-model="form.attributeSetId" :options="getOptions?.['attribute_sets']?.records || [{id: form.attributeSetId, Name: form.attributeSet}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_attributeset', 'attribute_sets')" @change="save" :loading="loading?.['attribute_sets'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Image URL</label>
                <input type="text" v-model="form.imageURL" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Guarantee Days</label>
                <input type="text" v-model="form.guaranteeDays" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block">Attribute Set Instance</label>
                <ClientOnly>
                  <SelectBox v-model="form.attributeSetInstanceId" :options="getOptions?.['attribute_set_instances']?.records || [{id: form.attributeSetInstanceId, Name: form.attributeSetInstance}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_attributesetinstance', 'attribute_set_instances')" @change="save" :loading="loading?.['attribute_set_instances'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Description URL</label>
                <input type="text" v-model="form.descriptionURL" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Min Guarantee Days</label>
                <input type="text" v-model="form.guaranteeDaysMin" class="input" @keyup="save" />
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block mt-2">Group 1</label>
                <input type="text" v-model="form.group1" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Group 2</label>
                <input type="text" v-model="form.group2" class="input" @keyup="save" />
              </div>
            </div>

            <label class="label d-block mt-2">Document Note</label>
            <textarea v-model="form.documentNote" class="input" @keyup="save"></textarea>
          </div>
          <div class="column is-one-third">
            <label class="label d-block">Document Status</label>
            <div class="d-flex flexDirection-column">
              <template v-if="!form.isSummary">
                <div class="check">
                  <input type="checkbox" v-model="form.discontinued" class="checkInput" id="discontinued" :checked="form.discontinued" @change="save">
                  <label class="checkLabel" for="discontinued">Discontinued</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isSelfService" class="checkInput" id="isSelfService" :checked="form.isSelfService" @change="save">
                  <label class="checkLabel" for="isSelfService">Self Service</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isExcludeAutoDelivery" class="checkInput" id="isExcludeAutoDelivery" :checked="form.isExcludeAutoDelivery" @change="save">
                  <label class="checkLabel" for="isExcludeAutoDelivery">Exclude Auto Delivery</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isWebStoreFeatured" class="checkInput" id="isWebStoreFeatured" :checked="form.isWebStoreFeatured" @change="save">
                  <label class="checkLabel" for="isWebStoreFeatured">Featured in Web Store</label>
                </div>
              </template>
              <div class="check">
                <input type="checkbox" v-model="form.isManufactured" class="checkInput" id="isManufactured" :checked="form.isManufactured" @change="save">
                <label class="checkLabel" for="isManufactured">Manufactured</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isPhantom" class="checkInput" id="isPhantom" :checked="form.isPhantom" @change="save">
                <label class="checkLabel" for="isPhantom">Phantom</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isKanban" class="checkInput" id="isKanban" :checked="form.isKanban" @change="save">
                <label class="checkLabel" for="isKanban">Kanban Controlled</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isAutoProduce" class="checkInput" id="isAutoProduce" :checked="form.isAutoProduce" @change="save">
                <label class="checkLabel" for="isAutoProduce">Auto Produce</label>
              </div>
            </div>
          </div>
        </div>
      </template>

    </div>
  </div>

  <CountryPickerModal
    v-model="countryPickerOpen"
    :countries="countriesData?.records || []"
    :currentCountryCode="originCountryCode"
    @select="onOriginCountrySelect"
  />

  <Teleport to="body">
    <ConfirmBox v-model="confirmGallery.show" :title="confirmGallery.title" :subTitle="confirmGallery.subTitle" :targetId="confirmGallery.id" @handler="destroyGallery" />
    <AttachmentViewer v-model="showAttachmentViewer" :type="showAttachmentViewerData?.mime ?? ''" :source="(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url) ? config.public.strapi+'/files-api/'+(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url).replace('/uploads/', '') : ''" :title="showAttachmentViewerData?.name ?? ''" :width="showAttachmentViewerData?.width ?? 1366" :height="showAttachmentViewerData?.height ?? 768" />
  </Teleport>
</template>

<style scoped>
/* Origin country (flag + name) */
.origin-country-btn {
  justify-content: flex-start;
  gap: 8px;
}
.origin-country-flag {
  width: 20px;
  height: auto;
  flex-shrink: 0;
}
.origin-country-readonly {
  min-height: 28px;
}

.field-input {
  border: none;
  box-shadow: none;
  height: 28px;
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}
.field-input:focus {
  outline: none;
  box-shadow: none;
}
.field-textarea {
  border: none;
  box-shadow: none;
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
  min-height: 60px;
}
.field-textarea:focus {
  outline: none;
  box-shadow: none;
}
.field-wrapper {
  border: 1px solid #dee2e6;
  border-radius: 4px;
  padding: 0.25rem 0.5rem 0.5rem 0.5rem;
}
.field-legend {
  color: #6c757d;
  font-size: 0.75rem;
  font-weight: 500;
  padding: 0 0.25rem;
  margin-left: 0.25rem;
}
.card-wrapper {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 1rem;
}
.card-legend {
  color: #495057;
  font-size: 0.875rem;
  font-weight: 600;
  padding: 0 0.5rem;
  margin-left: 0.5rem;
}
.copy-btn {
  height: 28px;
  min-width: 28px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dee2e6;
  background: #f8f9fa;
  cursor: pointer;
}
.copy-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}
</style>