<template>
  <teleport to="body">
    <div v-if="isOpen" class="fixed inset-0 bg-black/75 flex items-center justify-center z-[9999] pt-serif-regular-italic text-D">
      <div class="print-area bg-white w-[1224px] h-[528px] shadow-lg relative overflow-hidden">
        <!-- Header Kuning -->
        <div class="bg-yellow-500 h-8 w-full"><div class="bg-D h-6 w-full"></div></div>

        <div class="p-6 text-sm flex flex-col h-full">
          <!-- Info Toko + Logo + Data Pembeli -->
          <div class="relative flex justify-between pb-1 mb-2">
            <div class="flex flex-col gap-2 -mt-5">
              <p class="flex items-center gap-2"><i class="fab fa-instagram text-pink-600 text-xl"></i> tokomas_Jakartacitayam</p>
              <p class="flex items-center gap-2"><i class="fab fa-tiktok text-black text-xl"></i> tokomas_Jakartacitayam</p>
              <p class="flex items-center gap-2"><i class="fab fa-whatsapp text-green-500 text-xl"></i> 08158851178</p>
              <p class="text-sm">{{ transaksi.kode_transaksi || 'N/A' }}</p>
            </div>

            <div class="absolute inset-x-0 top-[-48px] flex justify-center">
              <img :src="logo" alt="Logo" class="h-40" />
            </div>

            <div class="grid grid-cols-[130px_1fr] gap-y-1 text-xs items-center -mt-5 z-10">
              <div class="text-right font-semibold pr-3">Tanggal :</div><div>{{ formatDate(transaksi.created_at) }}</div>
              <div class="text-right font-semibold pr-3">Nama :</div><div>{{ transaksi.nama_pembeli || '-' }}</div>
              <div class="text-right font-semibold pr-3">Alamat :</div><div>{{ transaksi.alamat || '-' }}</div>
              <div class="text-right font-semibold pr-3">No.Hp :</div><div>{{ transaksi.no_hp || '-' }}</div>
            </div>
          </div>

          <!-- Logo Bank -->
          <div class="flex justify-between mb-1">
            <div class="flex gap-4">
              <img :src="logo_bca" class="h-5" /><img :src="logo_bri" class="h-5" /><img :src="logo_bni" class="h-5" />
            </div>
            <div class="flex gap-4">
              <img :src="logo_mastercard" class="h-5" /><img :src="logo_visa" class="h-5" /><img :src="logo_mandiri" class="h-5" />
            </div>
          </div>

          <!-- Tabel Item -->
          <table class="w-full border-D text-sm table-fixed border-b">
            <thead>
              <tr class="border-b border-t border-D">
                <th class="w-[40px] border-r border-D text-lg">Jml</th>
                <th class="w-[425px] py-2 border-r border-D text-lg">Item</th>
                <th class="w-[70px] border-r border-D text-lg">Posisi</th>
                <th class="w-[40px] border-r border-D text-lg">Berat</th>
                <th class="w-[40px] border-r border-D text-lg">Kadar</th>
                <th class="w-[175px] text-lg">Harga</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in items" :key="item.id" class="text-center" :style="rowStyle">
                <td class="border-r border-D"><span v-if="item.harga_deal">1</span></td>
                <td class="flex items-center gap-2 p-2 border-r border-D" :style="rowStyle">
                  <img :src="item.produk?.foto?.[0]?.url || placeholder" :class="imgClass" class="object-cover rounded" />
                  <span :class="textClass">{{ item.produk?.nama || '' }}</span>
                </td>
                <td class="border-r border-D">{{ item.posisi_asal || 'Brankas' }}</td>
                <td class="border-r border-D">{{ item.produk?.berat ? formatNumber(item.produk.berat) + 'g' : '' }}</td>
                <td class="border-r border-D">{{ item.produk?.kadar ? item.produk.kadar + 'k' : '' }}</td>
                <td>Rp{{ item.harga_deal ? formatNumber(item.harga_deal) : '' }}</td>
              </tr>
            </tbody>
          </table>

          <!-- Footer: Perhatian + Sales + Harga + Tombol -->
          <div class="flex text-sm mt-2">
            <div class="w-[40%] p-2 text-left">
              <p class="font-semibold">PERHATIAN</p>
              <ol class="list-decimal ml-4 text-xs space-y-1">
                <li>Berat barang telah ditimbang dan disaksikan oleh pembeli.</li>
                <li>Barang yang dikembalikan menurut harga pasaran dan dipotong ongkos bikin, barang rusak lain harga.</li>
                <li>Barang yang sudah dibeli berarti sudah diperiksa dan disetujui.</li>
                <li class="text-red-500">Surat ini harap dibawa pada saat menjual kembali.</li>
              </ol>
            </div>

            <div class="w-[20%] p-2 flex flex-col items-center justify-center">
              <p><strong>Hormat Kami</strong></p>
              <p class="mt-16 font-semibold">{{ transaksi.nama_sales || '-' }}</p>
            </div>

            <div class="ml-auto w-[25%] p-2 flex flex-col justify-between">
              <div class="space-y-4">
                <div class="flex items-start justify-between">
                  <div>
                    <p class="font-semibold">Ongkos bikin</p>
                    <p class="text-red-500 text-xs">diluar harga jual</p>
                  </div>
                  <div class="flex p-1 items-center w-40 bg-B rounded-sm text-sm">
                    <span>Rp</span>
                    <span class="w-full text-left pl-1">{{ (transaksi.ongkos_bikin || 0).toLocaleString() }},-</span>
                  </div>
                </div>
                <div class="flex items-center justify-between -mt-4">
                  <p class="font-semibold">Total Harga</p>
                  <div class="flex items-center w-40 text-sm">
                    <span>Rp</span>
                    <span class="w-full text-left pl-1 py-1">{{ (transaksi.total_harga || 0).toLocaleString() }},-</span>
                  </div>
                </div>
              </div>

              <div class="flex justify-end gap-2 mt-4 no-print">
                <button @click="$emit('close')" class="bg-gray-400 text-white px-6 py-2 rounded">Tutup</button>
                <button @click="handlePrint" class="bg-C text-white px-6 py-2 rounded">Print</button>
              </div>
            </div>
          </div>
        </div>

        <p class="absolute bottom-0 left-0 w-full bg-D text-white text-xs py-1 pl-8">
          Terima kasih sudah berbelanja dengan kami
        </p>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { computed } from 'vue'
import { usePrintStruk } from '@/composables/usePrintStruk'

// === Assets ===
import logo from '@/../images/logo.png'
import logo_bca from '@/../images/logo_bca.png'
import logo_bri from '@/../images/logo_bri.png'
import logo_bni from '@/../images/logo_bni.png'
import logo_mastercard from '@/../images/logo_mastercard.png'
import logo_visa from '@/../images/logo_visa.png'
import logo_mandiri from '@/../images/logo_mandiri.png'
const placeholder = 'https://via.placeholder.com/50x50?text=No+Img'

// === Props & Emits ===
const props = defineProps({
  isOpen: Boolean,
  transaksi: { type: Object, default: () => ({}) }
})
const emit = defineEmits(['close'])

// === Helpers ===
const formatDate = (d) => {
  if (!d) return '-'
  const date = new Date(d)
  const days = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu']
  const months = ['01','02','03','04','05','06','07','08','09','10','11','12']
  return `${days[date.getDay()]}, ${String(date.getDate()).padStart(2,'0')}-${months[date.getMonth()]}-${date.getFullYear()}`
}

const formatNumber = (n) => n ? parseFloat(n).toLocaleString('id-ID') : ''

// === Items ===
const items = computed(() => {
  const raw = props.transaksi.itemTransaksi ||
              props.transaksi.items ||
              props.transaksi.item_transaksi || []
  const arr = [...raw].filter(i => i.harga_deal > 0)
  return arr.length ? arr : [{ produk: {}, harga_deal: 0, posisi_asal: '' }]
})

// === Dynamic Styles ===
const isSingle = computed(() => items.value.length === 1)
const rowStyle = computed(() => ({ height: isSingle.value ? '126px' : '63px' }))
const imgClass = computed(() => isSingle.value ? 'w-25 h-25' : 'w-12 h-12')
const textClass = computed(() => isSingle.value ? 'text-lg font-medium' : 'text-sm')

// === Print ===
const { handlePrint } = usePrintStruk(
  computed(() => props.transaksi),
  items,
  formatDate,
  formatNumber
)
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=PT+Serif:ital,wght@0,400;0,700;1,400;1,700&display=swap');
.pt-serif-regular-italic { font-family: "PT Serif", serif; font-weight: 400; }

@media print {
  @page { size: A4; margin: 0; }
  * { visibility: hidden !important; }
  .print-area, .print-area * { visibility: visible !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
  .print-area {
    position: fixed !important; top: 0 !important; left: 0 !important;
    width: 1224px; height: 528px; transform: scale(0.6673); transform-origin: top left;
  }
  .no-print { display: none !important; }
}
</style>
