/**
 * ExtendModal.jsx — Extend Storage Invoice
 *
 * REVISI BESAR sesuai requirement user:
 * 1. Invoice LUNAS sekarang BISA di-extend (use case: pickup terlambat
 *    karena macet, akibatnya harus bayar storage tambahan)
 * 2. Step 1: pilih invoice via search nomor KW (force-fetch by KW)
 * 3. Step 2: pilih CHECKBOX container/CBM mana saja yang kena extend
 *    (kalau pickup bertahap, hanya container tertentu yang lewat tanggal)
 * 4. Step 3: input tanggal aktual gate-out & sistem auto-calc storage tambahan
 * 5. LCL: input CBM yang ter-extend & jumlah hari keterlambatan
 *
 * Format nomor extend tetap: <originalKW>/EXT-<n>/<bulanRoman>/<tahun>
 */
import { useState, useMemo, useEffect } from 'react'
import { useApp } from '../context/AppContext'
import { formatRupiah } from '../utils/formatRupiah'
import { TARIF_DEFAULT, getTppFclTarif } from '../data/tarifDefault'
import {
  X, ChevronRight, ChevronLeft, Clock, Calculator, CheckCircle2,
  AlertCircle, Calendar, Package, Search, Lock,
} from 'lucide-react'

const ROMAN = ['','I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII']

const fmtTgl = (t) => {
  if (!t) return '—'
  try {
    const d = new Date(t)
    return `${String(d.getDate()).padStart(2,'0')} ${['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'][d.getMonth()]} ${d.getFullYear()}`
  } catch { return t }
}

function generateNomorExtend(parentNomorKW, seq = 1) {
  try {
    const parts = parentNomorKW.split('/')
    const now = new Date()
    return `${parts[0]}/EXT-${seq}/${ROMAN[now.getMonth()+1]}/${now.getFullYear()}`
  } catch {
    return `EXT-${seq}/${new Date().getFullYear()}`
  }
}

// Extract containers dari invoice (dukung berbagai struktur)
function getContainers(inv) {
  return inv?.detail?.form?.containers
    || inv?.detail?.selectedDoc?.containers
    || inv?.detail?.doc?.containers
    || []
}

// Reference date untuk container
function getContainerRefDate(c, inv) {
  if (c?.tglKeluar) return c.tglKeluar.slice(0, 10)
  return inv?.tanggalInvoice?.slice(0, 10) || ''
}

// Daily rate dari Master Tarif berdasarkan ukuran
function getDailyRate(tarif, ukuran, isFCL) {
  if (isFCL) {
    const t = getTppFclTarif(tarif || {}, ukuran || "20'")
    return t?.storagePerHari || TARIF_DEFAULT.tppFcl20.storagePerHari
  }
  const lclTarif = tarif?.lcl || TARIF_DEFAULT.lcl
  return lclTarif.storagePerCBMPerHari || 15_000
}

function daysBetween(from, to) {
  if (!from || !to) return 0
  return Math.max(0, Math.ceil((new Date(to) - new Date(from)) / 86400000))
}

// Cek apakah invoice termasuk LCL (dari berbagai indikator)
function isLclInvoice(inv) {
  if (!inv) return false
  const j = (inv.jenisLayanan || '').toUpperCase()
  return j.includes('LCL') || (inv.detail?.form?.cbm > 0)
}

// ════════════════════════════════════════════════════════════════════════════
export default function ExtendModal({ onClose }) {
  const { invoiceList, tambahExtendInvoice, showToast, tarif } = useApp()

  const [step, setStep]                   = useState(1)
  const [searchQuery, setSearchQuery]     = useState('')
  const [selectedInvId, setSelectedInvId] = useState('')
  // selectedContainers = Set of indices yang dipilih untuk extend
  const [selectedContainers, setSelectedContainers] = useState(new Set())
  // containerDates = { [idx]: 'YYYY-MM-DD' }
  const [containerDates, setContainerDates] = useState({})
  // Untuk LCL: input manual hari + cbm partial
  const [lclHari, setLclHari] = useState('')
  const [lclCbm, setLclCbm]   = useState('')
  const [catatan, setCatatan] = useState('')
  const [loading, setLoading] = useState(false)

  // ═══ ELIGIBILITY ═══════════════════════════════════════════════════════
  // FIX: Invoice LUNAS DIIZINKAN untuk extend (kasus delay setelah lunas)
  // Hanya filter: bukan invoice extend itu sendiri, dan layanan TPP/FCL/LCL
  // POIN-2: Invoice yang sudah punya extend child TIDAK bisa di-extend lagi (single-extend)
  const eligibleInvoices = useMemo(() => {
    // Collect parent IDs yang sudah punya extend child aktif
    const extendedParentIds = new Set(
      invoiceList
        .filter(inv => (inv.isExtend || inv.detail?.isExtend) && inv.status !== 'BATAL')
        .map(inv => inv.detail?.parentInvoiceId)
        .filter(Boolean)
    )

    return invoiceList.filter(inv => {
      if (inv.isExtend) return false              // Bukan extend dari extend
      if (inv.status === 'BATAL') return false    // Bukan invoice batal
      if (extendedParentIds.has(inv.id)) return false  // POIN-2: Sudah punya extend
      const j = (inv.jenisLayanan || '').toUpperCase()
      return (
        j.includes('TPP') ||
        j.includes('FCL') ||
        j.includes('LCL') ||
        j.includes('GUDANG')
      )
    })
  }, [invoiceList])

  // POIN-2: Filter by search — KOSONG jika belum search (cegah crash data banyak)
  const filteredInvoices = useMemo(() => {
    if (!searchQuery.trim()) return []  // Tidak tampilkan apa-apa sampai user search
    const q = searchQuery.toLowerCase()
    return eligibleInvoices.filter(inv =>
      inv.nomorKW?.toLowerCase().includes(q) ||
      inv.consignee?.toLowerCase().includes(q),
    ).slice(0, 30)
  }, [eligibleInvoices, searchQuery])

  const selectedInv = eligibleInvoices.find(i => i.id === selectedInvId)
  const containers  = selectedInv ? getContainers(selectedInv) : []
  const isLCL       = selectedInv ? isLclInvoice(selectedInv) : false
  const isFCL       = !isLCL
  const totalCbm    = selectedInv?.detail?.form?.cbm
                    || selectedInv?.detail?.doc?.cbm
                    || 0
  const isLunas     = selectedInv?.statusPembayaran === 'LUNAS'

  // ═══ KALKULASI per kontainer (FCL) atau total (LCL) ═══
  const perCtrCalc = useMemo(() => {
    if (!selectedInv) return []

    if (isFCL) {
      return containers
        .map((c, i) => {
          if (!selectedContainers.has(i)) return null
          const refDate = getContainerRefDate(c, selectedInv)
          const newDate = containerDates[i] || ''
          const hari    = daysBetween(refDate, newDate)
          const rate    = getDailyRate(tarif, c.ukuran, true)
          const biaya   = rate * hari
          return {
            idx: i,
            nomorContainer: c.nomorContainer || `Ctr ${i + 1}`,
            ukuran: c.ukuran || '',
            refDate, newDate, hari, rate, biaya,
          }
        })
        .filter(Boolean)
    }

    // LCL: hitung dari input manual hari & cbm
    const hari = parseInt(lclHari) || 0
    const cbm  = parseFloat(lclCbm) || totalCbm || 0
    if (hari <= 0 || cbm <= 0) return []
    const rate  = getDailyRate(tarif, null, false)
    const biaya = rate * hari * cbm
    return [{
      idx: 0,
      nomorContainer: `LCL ${cbm} CBM`,
      ukuran: 'LCL',
      refDate: selectedInv?.detail?.doc?.tglKeluar
            || selectedInv?.detail?.form?.tglKeluar
            || selectedInv?.tanggalInvoice?.slice(0, 10),
      newDate: '',
      hari, rate, biaya,
    }]
  }, [selectedInv, containers, selectedContainers, containerDates, tarif, isFCL, lclHari, lclCbm, totalCbm])

  const activeCalc = perCtrCalc.filter(c => c.hari > 0)
  const totalBiaya = activeCalc.reduce((s, c) => s + c.biaya, 0)
  const ppn        = Math.round(totalBiaya * 0.11)
  const grandTotal = totalBiaya + ppn

  const canNext1 = !!selectedInv
  const canNext2 = activeCalc.length > 0

  // Reset state saat invoice berubah
  useEffect(() => {
    if (selectedInv) {
      setSelectedContainers(new Set())
      setContainerDates({})
      setLclHari('')
      setLclCbm('')
    }
  }, [selectedInvId])

  // ═══ HANDLE TOGGLE ═══════════════════════════════════════════════════
  const toggleContainer = (idx) => {
    setSelectedContainers(prev => {
      const next = new Set(prev)
      if (next.has(idx)) {
        next.delete(idx)
        setContainerDates(d => {
          const newD = { ...d }
          delete newD[idx]
          return newD
        })
      } else {
        next.add(idx)
      }
      return next
    })
  }

  const toggleAllContainers = () => {
    if (selectedContainers.size === containers.length) {
      setSelectedContainers(new Set())
      setContainerDates({})
    } else {
      setSelectedContainers(new Set(containers.map((_, i) => i)))
    }
  }

  // ═══ HANDLE CONFIRM ═══════════════════════════════════════════════════
  const handleConfirm = async () => {
    if (!selectedInv || !canNext2) return
    setLoading(true)

    const existingExt = invoiceList.filter(i =>
      i.isExtend && i.detail?.parentInvoiceId === selectedInv.id,
    ).length
    const nomorKW = generateNomorExtend(selectedInv.nomorKW, existingExt + 1)

    try {
      await tambahExtendInvoice({
        nomorKW,
        parentInvoiceId: selectedInv.id,
        parentNomorKW:   selectedInv.nomorKW,
        consignee:       selectedInv.consignee,
        klienId:         selectedInv.klienId || null,
        jenisLayanan:    `${selectedInv.jenisLayanan} — EXTEND`,
        tanggalInvoice:  new Date().toISOString(),
        grandTotal,
        subTotal:        totalBiaya,
        ppn,
        catatan,
        // Backend POST /api/invoices butuh field-field ini juga:
        btdDokumenId:    selectedInv.btdDokumenId    || null,
        bdnDokumenId:    selectedInv.bdnDokumenId    || null,
        gudangDokumenId: selectedInv.gudangDokumenId || null,
        tpsAsal:         0,
        totalAkhir:      grandTotal,
        isExtend:        true,
        detailSnapshot: {
          isExtend: true,
          parentInvoiceId:  selectedInv.id,
          parentNomorKW:    selectedInv.nomorKW,
          parentDocId:      selectedInv.detail?.selectedDoc?.id || selectedInv.detail?.doc?.id,
          selectedDoc:      selectedInv.detail?.selectedDoc || selectedInv.detail?.doc,
          npwp:             selectedInv.detail?.npwp || selectedInv.detail?.klien?.npwp || '',
          alamat:           selectedInv.detail?.alamat || selectedInv.detail?.klien?.alamat || '',
          klien:            selectedInv.detail?.klien || null,
          isFCL,
          isLcl:            isLCL,
          cbm:              totalCbm,
          biayaStorage:     totalBiaya,
          perContainerExtend: activeCalc,
          parentLunas:      isLunas,
          kalkulasi: {
            perContainerExtend: activeCalc,
            baris: activeCalc.map(c => ({
              label: `${c.nomorContainer}${c.ukuran ? ` (${c.ukuran})` : ''} — +${c.hari} hari`,
              hari: c.hari,
              tarif: c.rate,
              jumlah: c.biaya,
            })),
            subTotal:   totalBiaya,
            ppn,
            grandTotal,
            totalAkhir: grandTotal,
          },
        },
        baris: activeCalc.map(c => ({
          label: `Storage Tambahan — ${c.nomorContainer}${c.ukuran ? ` (${c.ukuran})` : ''}`,
          hari: c.hari,
          tarif: c.rate,
          jumlah: c.biaya,
        })),
      })

      showToast(`Invoice Extend ${nomorKW} berhasil dibuat!`, 'sukses')
      onClose()
    } catch (err) {
      showToast(err.message || 'Gagal membuat invoice extend', 'error')
    } finally {
      setLoading(false)
    }
  }

  // ═════════════════════════════════════════════════════════════════════
  // RENDER
  // ═════════════════════════════════════════════════════════════════════
  const overlay = {
    position: 'fixed', inset: 0, zIndex: 300,
    background: 'rgba(10,22,40,0.82)', backdropFilter: 'blur(6px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
  }
  const card = {
    background: 'white', borderRadius: 18, width: '100%', maxWidth: 720,
    boxShadow: '0 24px 80px rgba(0,0,0,0.35)', overflow: 'hidden',
    animation: 'slideUpModal .2s ease',
    maxHeight: '92vh', display: 'flex', flexDirection: 'column',
  }

  return (
    <div style={overlay} onClick={onClose}>
      <div style={card} onClick={e => e.stopPropagation()}>

        {/* ═══ HEADER ═══ */}
        <div style={{
          background: 'linear-gradient(135deg,#0f172a,#1e293b)',
          padding: '18px 22px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexShrink: 0,
        }}>
          <div>
            <div style={{ fontSize: 15, fontWeight: 800, color: 'white', display: 'flex', alignItems: 'center', gap: 7 }}>
              <Clock size={17} color="#f59e0b" /> Extend Storage — Invoice Tambahan
            </div>
            <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.4)', marginTop: 3 }}>
              Hitung biaya storage tambahan per container/CBM akibat keterlambatan gate-out
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 30, height: 30, borderRadius: 7, border: 'none',
            background: 'rgba(255,255,255,0.1)', color: 'rgba(255,255,255,0.6)',
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <X size={15} />
          </button>
        </div>

        {/* ═══ STEPS INDICATOR ═══ */}
        <div style={{ display: 'flex', borderBottom: '1px solid #f1f5f9', flexShrink: 0 }}>
          {[
            ['1', 'Cari & Pilih Invoice'],
            ['2', 'Pilih Container & Tanggal'],
            ['3', 'Konfirmasi'],
          ].map(([n, lbl], i) => {
            const idx = i + 1
            const active = step === idx
            const done = step > idx
            return (
              <div key={n} style={{
                flex: 1, padding: '11px 0', textAlign: 'center', fontSize: 11.5,
                color: done ? '#10b981' : active ? '#0f172a' : '#cbd5e1',
                fontWeight: active || done ? 700 : 400,
                borderBottom: active ? '2.5px solid #0f172a' : '2.5px solid transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5,
              }}>
                <span style={{
                  width: 19, height: 19, borderRadius: '50%', fontSize: 9.5, fontWeight: 800,
                  background: done ? '#10b981' : active ? '#0f172a' : '#f1f5f9',
                  color: done || active ? 'white' : '#94a3b8',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                }}>{done ? '✓' : n}</span>
                {lbl}
              </div>
            )
          })}
        </div>

        {/* ═══ BODY ═══ */}
        <div style={{ padding: 22, overflowY: 'auto', flex: 1 }}>

          {/* ────── STEP 1: SEARCH & PILIH INVOICE ────── */}
          {step === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: '#0f172a', marginBottom: 8 }}>
                  Cari Invoice yang Akan Di-Extend
                </div>
                <div style={{ position: 'relative' }}>
                  <Search size={14} style={{
                    position: 'absolute', left: 12, top: '50%',
                    transform: 'translateY(-50%)', color: '#94a3b8',
                  }} />
                  <input
                    autoFocus
                    value={searchQuery}
                    onChange={e => setSearchQuery(e.target.value)}
                    placeholder="Ketik nomor KW atau nama consignee..."
                    style={{
                      width: '100%', height: 42, paddingLeft: 36, paddingRight: 12,
                      borderRadius: 10, border: '1.5px solid #e2e8f0',
                      fontSize: 13.5, fontFamily: 'inherit', outline: 'none',
                      boxSizing: 'border-box',
                    }}
                    onFocus={e => e.target.style.borderColor = '#0f172a'}
                    onBlur={e => e.target.style.borderColor = '#e2e8f0'}
                  />
                </div>
                <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 6 }}>
                  Tip: Anda bisa extend invoice yang <strong>SUDAH LUNAS</strong> jika pickup terlambat — sistem akan generate invoice baru untuk biaya storage tambahan.
                </div>
              </div>

              {/* List invoice */}
              {filteredInvoices.length === 0 ? (
                <div style={{ padding: 28, textAlign: 'center', color: '#94a3b8' }}>
                  <AlertCircle size={30} style={{ margin: '0 auto 8px', display: 'block', color: '#e2e8f0' }} />
                  <div style={{ fontSize: 13 }}>
                    {searchQuery ? `Tidak ditemukan invoice dengan kata kunci "${searchQuery}"` : 'Tidak ada invoice tersedia'}
                  </div>
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 7, maxHeight: 350, overflowY: 'auto' }}>
                  {filteredInvoices.map(inv => {
                    const ctrs = getContainers(inv)
                    const lcl = isLclInvoice(inv)
                    const selected = selectedInvId === inv.id
                    const lunas = inv.statusPembayaran === 'LUNAS'

                    return (
                      <label key={inv.id} style={{
                        display: 'flex', gap: 11, alignItems: 'flex-start',
                        padding: '12px 14px', borderRadius: 10,
                        border: `1.5px solid ${selected ? '#0f172a' : '#e2e8f0'}`,
                        background: selected ? '#f8fafc' : 'white',
                        cursor: 'pointer', transition: 'all .15s',
                      }}>
                        <input
                          type="radio"
                          value={inv.id}
                          checked={selected}
                          onChange={() => setSelectedInvId(inv.id)}
                          style={{ accentColor: '#0f172a', marginTop: 3 }}
                        />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                            <span style={{ fontFamily: 'monospace', fontSize: 13, fontWeight: 700, color: '#1d4ed8' }}>
                              {inv.nomorKW}
                            </span>
                            {lunas && (
                              <span style={{
                                fontSize: 10, fontWeight: 800, padding: '2px 7px', borderRadius: 4,
                                background: '#f0fdf4', color: '#166534',
                                display: 'flex', alignItems: 'center', gap: 3,
                              }}>
                                <Lock size={9} /> LUNAS
                              </span>
                            )}
                            {lcl && (
                              <span style={{
                                fontSize: 10, fontWeight: 800, padding: '2px 7px', borderRadius: 4,
                                background: '#faf5ff', color: '#7e22ce',
                              }}>
                                LCL
                              </span>
                            )}
                          </div>
                          <div style={{ fontSize: 11.5, color: '#64748b', marginTop: 3 }}>
                            {inv.consignee}
                          </div>
                          <div style={{ display: 'flex', gap: 6, marginTop: 5, flexWrap: 'wrap' }}>
                            <span style={{ fontSize: 10.5, padding: '2px 8px', borderRadius: 20, background: '#f1f5f9', color: '#64748b' }}>
                              {inv.jenisLayanan}
                            </span>
                            <span style={{ fontSize: 10.5, padding: '2px 8px', borderRadius: 20, background: '#fff7ed', color: '#c2410c' }}>
                              {fmtTgl(inv.tanggalInvoice)}
                            </span>
                            <span style={{ fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 20, background: '#f0fdf4', color: '#166534' }}>
                              {formatRupiah(inv.grandTotal)}
                            </span>
                            {ctrs.length > 0 && (
                              <span style={{
                                fontSize: 10.5, padding: '2px 8px', borderRadius: 20,
                                background: '#eff6ff', color: '#1d4ed8',
                                display: 'flex', alignItems: 'center', gap: 3,
                              }}>
                                <Package size={10} /> {ctrs.length} ctr
                              </span>
                            )}
                          </div>
                        </div>
                      </label>
                    )
                  })}
                </div>
              )}
            </div>
          )}

          {/* ────── STEP 2: PILIH CONTAINER & INPUT TANGGAL ────── */}
          {step === 2 && selectedInv && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

              {/* Info invoice */}
              <div style={{ padding: '11px 14px', background: '#f8fafc', borderRadius: 10, border: '1px solid #e2e8f0' }}>
                <div style={{ fontSize: 10.5, color: '#94a3b8', fontWeight: 700, marginBottom: 3 }}>INVOICE ASLI</div>
                <div style={{ fontFamily: 'monospace', fontSize: 13.5, fontWeight: 700, color: '#1d4ed8' }}>
                  {selectedInv.nomorKW}
                </div>
                <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>
                  {selectedInv.consignee} · {formatRupiah(selectedInv.grandTotal)}
                  {isLunas && <span style={{ color: '#16a34a', fontWeight: 700, marginLeft: 6 }}>· ✓ LUNAS</span>}
                </div>
              </div>

              {/* ─── FCL: Multi-checkbox container selection ─── */}
              {isFCL && containers.length > 0 && (
                <>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div style={{ fontSize: 12, fontWeight: 700, color: '#374151', display: 'flex', alignItems: 'center', gap: 5 }}>
                      <Calendar size={13} /> Pilih Container yang Terlambat Gate-Out
                    </div>
                    <button
                      onClick={toggleAllContainers}
                      style={{
                        fontSize: 11, padding: '4px 10px', borderRadius: 6,
                        border: '1px solid #e2e8f0', background: 'white',
                        color: '#0f172a', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600,
                      }}
                    >
                      {selectedContainers.size === containers.length ? 'Hapus Semua' : 'Pilih Semua'}
                    </button>
                  </div>

                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {containers.map((c, i) => {
                      const checked = selectedContainers.has(i)
                      const refDate = getContainerRefDate(c, selectedInv)
                      const newDate = containerDates[i] || ''
                      const hari    = checked ? daysBetween(refDate, newDate) : 0
                      const rate    = getDailyRate(tarif, c.ukuran, true)
                      const biaya   = rate * hari

                      return (
                        <div key={i} style={{
                          borderRadius: 10,
                          border: `1.5px solid ${hari > 0 ? '#f59e0b' : checked ? '#0f172a' : '#e2e8f0'}`,
                          background: hari > 0 ? '#fffbeb' : checked ? '#f8fafc' : 'white',
                          overflow: 'hidden', transition: 'all .2s',
                        }}>
                          {/* Container header dengan checkbox */}
                          <label style={{
                            padding: '10px 14px',
                            background: checked ? (hari > 0 ? '#fef3c7' : '#f1f5f9') : '#f8fafc',
                            borderBottom: checked ? `1px solid ${hari > 0 ? '#fcd34d' : '#e2e8f0'}` : 'none',
                            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                            cursor: 'pointer', userSelect: 'none',
                          }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                              <input
                                type="checkbox"
                                checked={checked}
                                onChange={() => toggleContainer(i)}
                                style={{ width: 16, height: 16, accentColor: '#0f172a', cursor: 'pointer' }}
                              />
                              <span style={{
                                fontSize: 10, fontWeight: 800, padding: '2px 8px', borderRadius: 5,
                                background: hari > 0 ? '#f59e0b' : checked ? '#0f172a' : '#e2e8f0',
                                color: hari > 0 || checked ? 'white' : '#64748b',
                              }}>
                                CTR {i + 1}
                              </span>
                              <span style={{ fontSize: 13, fontWeight: 700, color: '#0f172a', fontFamily: 'monospace' }}>
                                {c.nomorContainer || '—'}
                              </span>
                              {c.ukuran && (
                                <span style={{
                                  fontSize: 11, color: '#64748b', background: 'white',
                                  border: '1px solid #e2e8f0', borderRadius: 4, padding: '1px 7px',
                                }}>
                                  {c.ukuran}
                                </span>
                              )}
                            </div>
                            {hari > 0 && (
                              <span style={{ fontSize: 11, fontWeight: 800, color: '#92400e' }}>
                                +{hari} hari · {formatRupiah(biaya)}
                              </span>
                            )}
                          </label>

                          {/* Detail input — hanya muncul jika checked */}
                          {checked && (
                            <div style={{
                              padding: '11px 14px',
                              display: 'grid', gridTemplateColumns: '1fr 1fr',
                              gap: '8px 16px', alignItems: 'end',
                            }}>
                              <div>
                                <div style={{ fontSize: 10.5, color: '#94a3b8', marginBottom: 3 }}>
                                  Batas Gate-Out (Invoice)
                                </div>
                                <div style={{ fontSize: 12.5, fontWeight: 600, color: '#0f172a' }}>
                                  {refDate ? fmtTgl(refDate) : <span style={{ color: '#cbd5e1' }}>Tidak diset</span>}
                                </div>
                              </div>
                              <div>
                                <label style={{ fontSize: 10.5, color: '#374151', fontWeight: 600, display: 'block', marginBottom: 4 }}>
                                  Tgl Gate-Out Aktual <span style={{ color: '#ef4444' }}>*</span>
                                </label>
                                <input
                                  type="date"
                                  value={newDate}
                                  min={refDate || undefined}
                                  onChange={e => setContainerDates(prev => ({ ...prev, [i]: e.target.value }))}
                                  style={{
                                    width: '100%', height: 34, padding: '0 10px', borderRadius: 7,
                                    border: `1.5px solid ${hari > 0 ? '#f59e0b' : '#e2e8f0'}`,
                                    fontSize: 12.5, fontFamily: 'inherit', outline: 'none',
                                    boxSizing: 'border-box', background: 'white',
                                  }}
                                />
                                {newDate && hari <= 0 && (
                                  <div style={{ fontSize: 10.5, color: '#ef4444', marginTop: 3 }}>
                                    Harus lebih dari tanggal batas invoice
                                  </div>
                                )}
                              </div>
                            </div>
                          )}
                        </div>
                      )
                    })}
                  </div>
                </>
              )}

              {/* ─── LCL: Input hari + CBM ─── */}
              {isLCL && (
                <div style={{ background: '#faf5ff', border: '1.5px solid #e9d5ff', borderRadius: 10, padding: 14 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: '#7e22ce', marginBottom: 10 }}>
                    Data LCL — Storage Tambahan
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                    <div>
                      <label style={{ fontSize: 11, fontWeight: 600, color: '#581c87', display: 'block', marginBottom: 4 }}>
                        CBM yang Terlambat <span style={{ color: '#ef4444' }}>*</span>
                      </label>
                      <input
                        type="number"
                        step="0.01"
                        value={lclCbm}
                        onChange={e => setLclCbm(e.target.value)}
                        placeholder={`Total: ${totalCbm} CBM`}
                        style={{
                          width: '100%', height: 36, padding: '0 12px', borderRadius: 8,
                          border: '1.5px solid #d8b4fe', fontSize: 13, fontFamily: 'inherit',
                          outline: 'none', boxSizing: 'border-box', background: 'white',
                        }}
                      />
                      <div style={{ fontSize: 10.5, color: '#94a3b8', marginTop: 3 }}>
                        Bisa partial — tidak harus semua CBM
                      </div>
                    </div>
                    <div>
                      <label style={{ fontSize: 11, fontWeight: 600, color: '#581c87', display: 'block', marginBottom: 4 }}>
                        Jumlah Hari Keterlambatan <span style={{ color: '#ef4444' }}>*</span>
                      </label>
                      <input
                        type="number"
                        min="1"
                        value={lclHari}
                        onChange={e => setLclHari(e.target.value)}
                        placeholder="1"
                        style={{
                          width: '100%', height: 36, padding: '0 12px', borderRadius: 8,
                          border: '1.5px solid #d8b4fe', fontSize: 13, fontFamily: 'inherit',
                          outline: 'none', boxSizing: 'border-box', background: 'white',
                        }}
                      />
                      <div style={{ fontSize: 10.5, color: '#94a3b8', marginTop: 3 }}>
                        Hari di atas batas gate-out asal
                      </div>
                    </div>
                  </div>
                  {parseInt(lclHari) > 0 && (parseFloat(lclCbm) || totalCbm) > 0 && (
                    <div style={{ marginTop: 10, padding: '8px 12px', background: 'white', borderRadius: 7, fontSize: 11.5, color: '#581c87' }}>
                      Tarif: {formatRupiah(getDailyRate(tarif, null, false))}/CBM/hari ×{' '}
                      <strong>{parseFloat(lclCbm) || totalCbm} CBM</strong> ×{' '}
                      <strong>{parseInt(lclHari)} hari</strong> = <strong>{formatRupiah(totalBiaya)}</strong>
                    </div>
                  )}
                </div>
              )}

              {/* Catatan */}
              <div>
                <label style={{ fontSize: 11.5, fontWeight: 600, color: '#64748b', display: 'block', marginBottom: 5 }}>
                  Catatan / Alasan Keterlambatan (opsional)
                </label>
                <input
                  value={catatan}
                  onChange={e => setCatatan(e.target.value)}
                  placeholder="Misal: Macet di ruas tol Belmera, pickup mundur 1 hari..."
                  style={{
                    width: '100%', height: 34, padding: '0 11px', borderRadius: 7,
                    border: '1px solid #e2e8f0', fontSize: 12.5, fontFamily: 'inherit',
                    outline: 'none', boxSizing: 'border-box',
                  }}
                />
              </div>

              {/* Total preview */}
              {canNext2 && (
                <div style={{
                  background: '#fffbeb', border: '1.5px solid #fcd34d',
                  borderRadius: 10, overflow: 'hidden',
                }}>
                  <div style={{
                    background: '#f59e0b', padding: '8px 14px',
                    fontSize: 11, fontWeight: 800, color: 'white',
                    display: 'flex', alignItems: 'center', gap: 5,
                  }}>
                    <Calculator size={13} /> TOTAL BIAYA EXTEND ({activeCalc.length} item)
                  </div>
                  <div style={{ padding: '12px 14px' }}>
                    {activeCalc.map(c => (
                      <div key={c.idx} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '3px 0', borderBottom: '1px dashed #fef3c7' }}>
                        <span style={{ color: '#78350f' }}>
                          {c.nomorContainer}{c.ukuran && c.ukuran !== 'LCL' ? ` (${c.ukuran})` : ''} — +{c.hari} hari
                        </span>
                        <span style={{ fontWeight: 700 }}>{formatRupiah(c.biaya)}</span>
                      </div>
                    ))}
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '6px 0 3px', marginTop: 4, borderTop: '1px solid #fcd34d' }}>
                      <span style={{ color: '#92400e' }}>Sub Total</span>
                      <span style={{ fontWeight: 700 }}>{formatRupiah(totalBiaya)}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, padding: '3px 0' }}>
                      <span style={{ color: '#92400e' }}>PPN 11%</span>
                      <span style={{ fontWeight: 700 }}>{formatRupiah(ppn)}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, padding: '8px 0 0', borderTop: '2px solid #f59e0b' }}>
                      <span style={{ fontSize: 14, fontWeight: 800, color: '#78350f' }}>Grand Total Extend</span>
                      <span style={{ fontSize: 14, fontWeight: 800, color: '#78350f' }}>{formatRupiah(grandTotal)}</span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* ────── STEP 3: KONFIRMASI ────── */}
          {step === 3 && selectedInv && canNext2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div style={{ padding: 16, background: '#f0fdf4', borderRadius: 10, border: '1px solid #bbf7d0' }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#166534', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 5 }}>
                  <CheckCircle2 size={14} /> Ringkasan Invoice Extend
                </div>
                {[
                  ['Invoice Asli', selectedInv.nomorKW],
                  ['Status Asli', isLunas ? '✓ LUNAS' : 'TERBIT / BELUM BAYAR'],
                  ['Consignee', selectedInv.consignee],
                  ['Tipe Layanan', isFCL ? `FCL — ${activeCalc.length} container` : `LCL — ${parseFloat(lclCbm) || totalCbm} CBM`],
                  ['Storage Tambahan', formatRupiah(totalBiaya)],
                  ['PPN 11%', formatRupiah(ppn)],
                  ['Grand Total Extend', formatRupiah(grandTotal)],
                ].map(([lbl, val]) => (
                  <div key={lbl} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, padding: '5px 0', borderBottom: '1px dashed #d1fae5' }}>
                    <span style={{ color: '#065f46' }}>{lbl}</span>
                    <span style={{ fontWeight: lbl === 'Grand Total Extend' ? 800 : 600, color: '#0f172a' }}>{val}</span>
                  </div>
                ))}
                <div style={{ marginTop: 10 }}>
                  {activeCalc.map(c => (
                    <div key={c.idx} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, padding: '4px 0', color: '#374151' }}>
                      <span>↳ {c.nomorContainer}{c.ukuran && c.ukuran !== 'LCL' ? ` (${c.ukuran})` : ''} · +{c.hari} hari</span>
                      <span style={{ fontWeight: 600 }}>{formatRupiah(c.biaya)}</span>
                    </div>
                  ))}
                </div>
              </div>
              {catatan && (
                <div style={{ fontSize: 12, color: '#64748b', background: '#f0f9ff', padding: '9px 13px', borderRadius: 8, border: '1px solid #bae6fd' }}>
                  📝 {catatan}
                </div>
              )}
              <div style={{ fontSize: 11.5, color: '#94a3b8', background: '#f8fafc', padding: '9px 13px', borderRadius: 8 }}>
                ℹ️ Invoice Extend akan tampil di Daftar Invoice dengan status <strong>Terbit</strong> dan tag <strong>EXT</strong>. Konfirmasi lunas dilakukan terpisah.
              </div>
            </div>
          )}
        </div>

        {/* ═══ FOOTER ═══ */}
        <div style={{
          padding: '13px 22px', borderTop: '1px solid #f1f5f9',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          flexShrink: 0,
        }}>
          <button
            onClick={() => step > 1 ? setStep(s => s - 1) : onClose()}
            style={{
              height: 36, padding: '0 16px', borderRadius: 8,
              border: '1px solid #e2e8f0', background: 'white',
              color: '#64748b', fontSize: 13, fontWeight: 600,
              cursor: 'pointer', fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', gap: 5,
            }}
          >
            <ChevronLeft size={14} /> {step === 1 ? 'Batal' : 'Kembali'}
          </button>
          {step < 3 ? (
            <button
              onClick={() => setStep(s => s + 1)}
              disabled={step === 1 ? !canNext1 : !canNext2}
              style={{
                height: 36, padding: '0 20px', borderRadius: 8, border: 'none',
                background: (step === 1 ? canNext1 : canNext2) ? '#0f172a' : '#f1f5f9',
                color: (step === 1 ? canNext1 : canNext2) ? 'white' : '#94a3b8',
                fontSize: 13, fontWeight: 700,
                cursor: (step === 1 ? canNext1 : canNext2) ? 'pointer' : 'not-allowed',
                fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 5,
                transition: 'all .15s',
              }}
            >
              Lanjut <ChevronRight size={14} />
            </button>
          ) : (
            <button
              onClick={handleConfirm}
              disabled={loading}
              style={{
                height: 36, padding: '0 20px', borderRadius: 8, border: 'none',
                background: loading ? '#d1fae5' : 'linear-gradient(135deg,#059669,#047857)',
                color: 'white', fontSize: 13, fontWeight: 700,
                cursor: loading ? 'default' : 'pointer', fontFamily: 'inherit',
                display: 'flex', alignItems: 'center', gap: 5,
                boxShadow: '0 2px 10px rgba(5,150,105,0.3)',
              }}
            >
              {loading ? 'Membuat...' : <><CheckCircle2 size={14} /> Buat Invoice Extend</>}
            </button>
          )}
        </div>
      </div>

      <style>{`
        @keyframes slideUpModal {
          from { opacity: 0; transform: translateY(14px); }
          to   { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </div>
  )
}