const { useState } = React;
const { 
  Search, Trash2, Calendar, FileText, ShoppingCart, User, 
  ChevronDown, ChevronUp, RefreshCw, Table, AlertCircle, CheckCircle2, 
  FileSpreadsheet, Download 
} = window.lucide;

function ScanHistory({ records, onRecordDeleted, onRecordSyncUpdated }) {
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [expandedId, setExpandedId] = useState(null);
  const [syncingId, setSyncingId] = useState(null);
  const [clearing, setClearing] = useState(false);
  const [showExportDropdown, setShowExportDropdown] = useState(false);

  const filteredRecords = records.filter(record => {
    const matchesSearch = 
      (record.orderId || '').toLowerCase().includes(search.toLowerCase()) ||
      (record.customerName || '').toLowerCase().includes(search.toLowerCase()) ||
      (record.fileName || '').toLowerCase().includes(search.toLowerCase()) ||
      (record.items || []).some(item => (item.productName || '').toLowerCase().includes(search.toLowerCase())) ||
      (record.trackingNumber || '').toLowerCase().includes(search.toLowerCase()) ||
      (record.shippingProvider || '').toLowerCase().includes(search.toLowerCase()) ||
      (record.routeCode || '').toLowerCase().includes(search.toLowerCase());

    const matchesCategory = selectedCategory === 'All' || record.category === selectedCategory;

    return matchesSearch && matchesCategory;
  });

  const totalAmount = filteredRecords
    .filter(r => r.status === 'success')
    .reduce((sum, r) => sum + r.totalAmount, 0);

  const stats = {
    total: filteredRecords.length,
    lazada: filteredRecords.filter(r => r.category === 'Lazada').length,
    shopee: filteredRecords.filter(r => r.category === 'Shopee').length,
    tiktok: filteredRecords.filter(r => r.category === 'TikTok Shop').length,
    others: filteredRecords.filter(r => r.category === 'Other').length
  };

  const exportToCSV = (mode) => {
    if (filteredRecords.length === 0) return;

    let headers = [];
    let rows = [];

    if (mode === 'items') {
      headers = [
        'วันที่แสกน', 'หมวดหมู่', 'เลขที่คำสั่งซื้อ', 'วันที่สั่งซื้อ', 'บริษัทขนส่ง',
        'หมายเลขพัสดุ (Tracking)', 'รหัสเส้นทาง', 'ช่องทางการชำระเงิน', 'ชื่อสินค้า',
        'ราคาต่อหน่วย (บาท)', 'จำนวน', 'จำนวนเงินรวม (บาท)', 'ชื่อร้านค้าผู้ส่ง',
        'ที่อยู่ผู้ส่ง', 'เบอร์โทรศัพท์ผู้ส่ง', 'ชื่อผู้รับ/ลูกค้า', 'ที่อยู่ผู้รับ', 'เบอร์โทรศัพท์ผู้รับ'
      ];

      filteredRecords.forEach(record => {
        const baseData = [
          new Date(record.timestamp).toLocaleString('th-TH'),
          record.category, record.orderId || '', record.orderDate || '', record.shippingProvider || '',
          record.trackingNumber || '', record.routeCode || '', record.paymentMethod || ''
        ];
        
        const senderReceiverData = [
          record.senderName || '', (record.senderAddress || '').replace(/"/g, '""').replace(/\n/g, ' '), record.senderPhone || '',
          record.customerName || '', (record.receiverAddress || '').replace(/"/g, '""').replace(/\n/g, ' '), record.receiverPhone || ''
        ];

        if (record.items && record.items.length > 0) {
          record.items.forEach(item => {
            rows.push([
              ...baseData,
              item.productName.replace(/"/g, '""').replace(/\n/g, ' '),
              item.price.toString(), item.quantity.toString(), item.amount.toString(),
              ...senderReceiverData
            ]);
          });
        } else {
          rows.push([...baseData, '', '0', '0', '0', ...senderReceiverData]);
        }
      });
    } else {
      headers = [
        'วันที่แสกน', 'หมวดหมู่', 'เลขที่คำสั่งซื้อ', 'วันที่สั่งซื้อ', 'บริษัทขนส่ง',
        'หมายเลขพัสดุ (Tracking)', 'รหัสเส้นทาง', 'ช่องทางการชำระเงิน', 'ยอดชำระสุทธิ (บาท)',
        'จำนวนรายการสินค้าทั้งหมด', 'ชื่อร้านค้าผู้ส่ง', 'ที่อยู่ผู้ส่ง', 'เบอร์โทรศัพท์ผู้ส่ง',
        'ชื่อผู้รับ/ลูกค้า', 'ที่อยู่ผู้รับ', 'เบอร์โทรศัพท์ผู้รับ', 'รายการสินค้าด่วน'
      ];

      filteredRecords.forEach(record => {
        const itemsSummary = (record.items || []).map(item => `${item.productName} (x${item.quantity})`).join(' | ');
        rows.push([
          new Date(record.timestamp).toLocaleString('th-TH'),
          record.category, record.orderId || '', record.orderDate || '', record.shippingProvider || '',
          record.trackingNumber || '', record.routeCode || '', record.paymentMethod || '',
          record.totalAmount.toString(), (record.items || []).length.toString(),
          record.senderName || '', (record.senderAddress || '').replace(/"/g, '""').replace(/\n/g, ' '), record.senderPhone || '',
          record.customerName || '', (record.receiverAddress || '').replace(/"/g, '""').replace(/\n/g, ' '), record.receiverPhone || '',
          itemsSummary.replace(/"/g, '""').replace(/\n/g, ' ')
        ]);
      });
    }

    const csvContent = [headers.join(','), ...rows.map(r => r.map(val => `"${val}"`).join(','))].join('\n');
    const blob = new Blob([new Uint8Array([0xEF, 0xBB, 0xBF]), csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `sheetocr_export_${mode}_${Date.now()}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    setShowExportDropdown(false);
  };

  const exportSingleRecordToCSV = (record) => {
    const headers = [
      'เลขที่คำสั่งซื้อ', 'วันที่สั่งซื้อ', 'บริษัทขนส่ง', 'หมายเลขพัสดุ', 'รหัสเส้นทาง', 'ช่องการชำระเงิน',
      'ชื่อผู้ส่ง', 'ที่อยู่ผู้ส่ง', 'เบอร์ผู้ส่ง', 'ชื่อผู้รับ', 'ที่อยู่ผู้รับ', 'เบอร์ผู้รับ',
      'ชื่อสินค้า', 'ราคาต่อหน่วย', 'จำนวน', 'รวมราคา'
    ];
    
    const rows = [];
    const baseData = [
      record.orderId || '', record.orderDate || '', record.shippingProvider || '', record.trackingNumber || '', record.routeCode || '', record.paymentMethod || '',
      record.senderName || '', (record.senderAddress || '').replace(/"/g, '""').replace(/\n/g, ' '), record.senderPhone || '',
      record.customerName || '', (record.receiverAddress || '').replace(/"/g, '""').replace(/\n/g, ' '), record.receiverPhone || ''
    ];

    if (record.items && record.items.length > 0) {
      record.items.forEach(item => {
        rows.push([
          ...baseData,
          item.productName.replace(/"/g, '""').replace(/\n/g, ' '),
          item.price.toString(), item.quantity.toString(), item.amount.toString()
        ]);
      });
    } else {
      rows.push([...baseData, '', '0', '0', '0']);
    }

    const csvContent = [headers.join(','), ...rows.map(r => r.map(val => `"${val}"`).join(','))].join('\n');
    const blob = new Blob([new Uint8Array([0xEF, 0xBB, 0xBF]), csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `sheetocr_order_${record.orderId || record.id}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleDelete = async (id, e) => {
    e.stopPropagation();
    if (!confirm('ยืนยันต้องการลบประวัติการสแกนรายการนี้หรือไม่?')) return;

    try {
      const res = await fetch(`api.php?action=history_delete&id=${id}`, { method: 'DELETE' });
      if (res.ok) {
        onRecordDeleted();
      }
    } catch (error) {
      console.error('Failed to delete history record:', error);
    }
  };

  const handleClearAll = async () => {
    if (!confirm('คุณแน่ใจหรือไม่ว่าต้องการล้างประวัติการสแกนทั้งหมด? การกระทำนี้ไม่สามารถเรียกคืนได้')) return;
    
    setClearing(true);
    try {
      const res = await fetch('api.php?action=history_clear', { method: 'POST' });
      if (res.ok) {
        onRecordDeleted();
      }
    } catch (e) {
      console.error(e);
    } finally {
      setClearing(false);
    }
  };

  const handleReSyncSheets = async (recordId, e) => {
    e.stopPropagation();
    setSyncingId(recordId);

    try {
      const res = await fetch('api.php?action=re_sync_sheets', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ recordId })
      });
      if (res.ok) {
        onRecordSyncUpdated();
      }
    } catch (err) {
      console.error(err);
    } finally {
      setSyncingId(null);
    }
  };

  const toggleExpand = (id) => {
    setExpandedId(expandedId === id ? null : id);
  };

  const getCategoryTheme = (category) => {
    switch (category) {
      case 'Lazada': return 'bg-blue-100 text-blue-800 border-blue-200';
      case 'Shopee': return 'bg-orange-100 text-orange-800 border-orange-200';
      case 'TikTok Shop': return 'bg-slate-100 text-slate-800 border-slate-200';
      default: return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  return (
    <div className="space-y-6">
      {/* Analytics Dashboard Grid */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 text-center">
          <span className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">สแกนทั้งหมด</span>
          <span className="text-xl font-black text-gray-900">{stats.total}</span>
          <span className="block text-[9px] text-gray-400 mt-1">ไฟล์</span>
        </div>
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 text-center border-l-4 border-l-blue-500">
          <span className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Lazada</span>
          <span className="text-xl font-black text-blue-600">{stats.lazada}</span>
          <span className="block text-[9px] text-gray-400 mt-1">ใบปะหน้า</span>
        </div>
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 text-center border-l-4 border-l-orange-500">
          <span className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Shopee</span>
          <span className="text-xl font-black text-orange-600">{stats.shopee}</span>
          <span className="block text-[9px] text-gray-400 mt-1">ใบปะหน้า</span>
        </div>
        <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 text-center border-l-4 border-l-black">
          <span className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">TikTok Shop</span>
          <span className="text-xl font-black text-slate-900">{stats.tiktok}</span>
          <span className="block text-[9px] text-gray-400 mt-1">ใบปะหน้า</span>
        </div>
        <div className="bg-indigo-600 rounded-xl shadow-sm p-4 text-center text-white col-span-2 md:col-span-1">
          <span className="block text-[10px] font-bold text-indigo-200 uppercase tracking-wider mb-1">มูลค่ารวมที่สแกน</span>
          <span className="text-base font-black font-mono block truncate">{totalAmount.toLocaleString('th-TH', { maximumFractionDigits: 0 })}</span>
          <span className="block text-[9px] text-indigo-200 mt-1">บาท (฿)</span>
        </div>
      </div>

      {/* Control bar */}
      <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-4">
        {/* Search */}
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="ค้นหาด้วยเลขที่ออเดอร์, ชื่อลูกค้า, ชื่อสินค้า, รหัสพัสดุ..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full text-xs pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none transition-all"
          />
        </div>

        {/* Filters & Export */}
        <div className="flex flex-wrap items-center gap-2">
          {['All', 'Lazada', 'Shopee', 'TikTok Shop', 'Other'].map((cat) => (
            <button
              key={cat}
              onClick={() => setSelectedCategory(cat)}
              className={`px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap transition-colors outline-none ${
                selectedCategory === cat
                  ? 'bg-indigo-600 text-white shadow-xs'
                  : 'bg-gray-50 text-gray-600 hover:bg-gray-100 border border-gray-100'
              }`}
            >
              {cat === 'All' ? 'ทั้งหมด (All)' : cat === 'Other' ? 'อื่นๆ' : cat}
            </button>
          ))}

          {/* Export Dropdown */}
          {filteredRecords.length > 0 && (
            <div className="relative">
              <button
                onClick={() => setShowExportDropdown(!showExportDropdown)}
                className="px-3.5 py-1.5 text-xs font-bold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-100 rounded-lg transition-colors flex items-center gap-1.5 outline-none"
              >
                <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
                ส่งออก Excel / CSV
                <ChevronDown className="w-3.5 h-3.5 text-emerald-500" />
              </button>

              {showExportDropdown && (
                <>
                  <div className="fixed inset-0 z-10" onClick={() => setShowExportDropdown(false)} />
                  <div className="absolute right-0 mt-1.5 w-60 bg-white border border-gray-150 rounded-lg shadow-xl py-1 z-20 animate-fade-in text-left">
                    <button
                      onClick={() => exportToCSV('items')}
                      className="w-full text-left px-4 py-2.5 text-xs text-gray-700 hover:bg-slate-50 font-bold flex items-center gap-2 border-b border-gray-50"
                    >
                      <Table className="w-4 h-4 text-emerald-600" />
                      แบบละเอียด (รายสินค้า - 1 แถวต่อชิ้น)
                    </button>
                    <button
                      onClick={() => exportToCSV('orders')}
                      className="w-full text-left px-4 py-2.5 text-xs text-gray-700 hover:bg-slate-50 font-bold flex items-center gap-2"
                    >
                      <FileText className="w-4 h-4 text-emerald-600" />
                      แบบสรุปย่อ (รายออเดอร์ - 1 แถวต่อบิล)
                    </button>
                  </div>
                </>
              )}
            </div>
          )}

          {records.length > 0 && (
            <button
              onClick={handleClearAll}
              disabled={clearing}
              className="px-3 py-1.5 text-xs font-semibold text-rose-600 bg-rose-50 hover:bg-rose-100 rounded-lg border border-rose-100 transition-colors flex items-center gap-1.5"
            >
              <Trash2 className="w-3.5 h-3.5" />
              ล้างทั้งหมด
            </button>
          )}
          
          <a
            href="data/orders_archive.csv"
            download="orders_archive.csv"
            className="px-3 py-1.5 text-xs font-semibold text-indigo-700 bg-indigo-50 hover:bg-indigo-100 rounded-lg border border-indigo-100 transition-colors flex items-center gap-1.5 outline-none"
            title="ดาวน์โหลดไฟล์ CSV ที่เก็บแบบถาวรบนเซิร์ฟเวอร์"
          >
            <Download className="w-3.5 h-3.5" />
            ไฟล์สำรอง CSV บนเซิร์ฟเวอร์
          </a>
        </div>
      </div>

      {/* History table list */}
      <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
        {filteredRecords.length === 0 ? (
          <div className="text-center py-16 text-gray-400">
            <Table className="w-12 h-12 text-gray-200 mx-auto mb-3" />
            <p className="text-sm font-semibold">ไม่พบข้อมูลประวัติสแกนที่ตรงกับเงื่อนไข</p>
            <p className="text-xs text-gray-400 mt-1">เริ่มต้นอัปโหลดใบปะหน้าหรือใบเสร็จรับเงินเพื่อสแกนแยกข้อมูลด้วย AI</p>
          </div>
        ) : (
          <div className="divide-y divide-gray-100">
            {filteredRecords.map((record) => {
              const isExpanded = expandedId === record.id;
              const isFailed = record.status === 'failed';
              
              return (
                <div 
                  key={record.id} 
                  className={`transition-colors ${isExpanded ? 'bg-gray-50/30' : 'hover:bg-gray-50/20'}`}
                >
                  {/* Summary bar */}
                  <div 
                    onClick={() => toggleExpand(record.id)}
                    className="p-5 flex flex-col md:flex-row md:items-center justify-between gap-4 cursor-pointer"
                  >
                    <div className="flex items-start gap-3.5 min-w-0">
                      <div className={`px-2.5 py-1 rounded-md text-[10px] font-black uppercase tracking-wider text-center border shrink-0 ${getCategoryTheme(record.category)}`}>
                        {record.category}
                      </div>

                      <div className="min-w-0">
                        <div className="flex items-center gap-2 flex-wrap mb-1">
                          <span className="text-sm font-bold text-gray-900 truncate font-mono">
                            {record.orderId ? `#${record.orderId}` : record.fileName}
                          </span>
                          {!isFailed && (
                            <span className="text-xs font-semibold text-gray-600 truncate max-w-[150px]">
                              ({record.customerName || 'ไม่ระบุชื่อ'})
                            </span>
                          )}
                        </div>

                        <div className="flex items-center gap-4 text-[10px] text-gray-400 font-bold">
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3.5 h-3.5" />
                            {new Date(record.timestamp).toLocaleString('th-TH', { dateStyle: 'short', timeStyle: 'short' })}
                          </span>
                          <span className="hidden md:inline">|</span>
                          <span className="truncate max-w-[200px]">ไฟล์: {record.fileName}</span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-4 justify-between md:justify-end border-t md:border-t-0 pt-3.5 md:pt-0 border-gray-100/80">
                      {isFailed ? (
                        <div className="flex items-center gap-1.5 text-xs text-rose-600 font-bold bg-rose-50 px-2.5 py-1 rounded-lg border border-rose-100">
                          <AlertCircle className="w-4 h-4" />
                          สแกนล้มเหลว
                        </div>
                      ) : (
                        <div className="text-right">
                          <span className="block text-[10px] font-bold text-gray-400 uppercase tracking-wider">ยอดรวมสุทธิ</span>
                          <span className="text-sm font-black font-mono text-gray-900">{record.totalAmount.toLocaleString('th-TH', { minimumFractionDigits: 2 })} บาท</span>
                        </div>
                      )}

                      <div className="flex items-center gap-2.5 shrink-0">
                        {/* Sheets Status Tag */}
                        {!isFailed && record.sheetsStatus !== 'not_configured' && (
                          <button
                            onClick={(e) => handleReSyncSheets(record.id, e)}
                            disabled={syncingId === record.id}
                            className={`p-1.5 rounded-lg border text-xs font-bold transition-all outline-none flex items-center gap-1 ${
                              record.sheetsStatus === 'success'
                                ? 'bg-emerald-50 text-emerald-600 border-emerald-100 hover:bg-emerald-100/50'
                                : 'bg-rose-50 text-rose-600 border-rose-100 hover:bg-rose-100/50'
                            }`}
                            title={record.sheetsStatus === 'success' ? 'ซิงค์เข้า Google Sheets สำเร็จ - กดเพื่อส่งข้อมูลไป Sheet ซ้ำได้' : 'ซิงค์ล้มเหลว - กดเพื่อลองส่งใหม่อีกครั้ง'}
                          >
                            {syncingId === record.id ? (
                              <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                            ) : record.sheetsStatus === 'success' ? (
                              <CheckCircle2 className="w-3.5 h-3.5" />
                            ) : (
                              <AlertCircle className="w-3.5 h-3.5" />
                            )}
                            <span className="text-[9px] uppercase tracking-wider hidden md:inline">
                              {record.sheetsStatus === 'success' ? 'SHEET OK' : 'SYNC FAIL'}
                            </span>
                          </button>
                        )}

                        {/* Expand Toggle */}
                        <div className="p-1 text-gray-400 hover:text-gray-600 bg-gray-50 border border-gray-100 rounded-lg">
                          {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Expanded Detail Panel */}
                  {isExpanded && (
                    <div className="px-5 pb-6 border-t border-gray-100 bg-gray-50/15 animate-slide-down">
                      {isFailed ? (
                        <div className="mt-4 p-4 bg-rose-50/80 border border-rose-100 rounded-xl text-xs text-rose-800 flex items-start gap-2">
                          <AlertCircle className="w-4 h-4 text-rose-600 shrink-0 mt-0.5" />
                          <div>
                            <span className="font-bold block mb-0.5">รายละเอียดข้อผิดพลาด:</span>
                            {record.errorMessage || 'ระบบสแกน OCR ไม่สามารถอ่านค่าเอกสารอย่างสมเหตุสมผลได้ กรุณาตรวจเช็กคุณภาพไฟล์อัปโหลด'}
                          </div>
                        </div>
                      ) : (
                        <div className="mt-4 space-y-5">
                          {/* Rich Logistics and Customer Information Panels */}
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            {/* Panel 1: Order & Logistics Metadata */}
                            <div className="bg-white rounded-xl border border-gray-100 shadow-xs p-4 space-y-3">
                              <h5 className="font-bold text-xs text-gray-700 border-b border-gray-50 pb-2 flex items-center gap-1.5 text-indigo-600">
                                <ShoppingCart className="w-4 h-4 text-indigo-500" />
                                ข้อมูลคำสั่งซื้อและการจัดส่ง (Order & Logistics)
                              </h5>
                              <div className="space-y-2 text-xs">
                                <div className="flex justify-between">
                                  <span className="text-gray-400 font-medium">บริษัทขนส่ง:</span>
                                  <span className="font-bold text-gray-900 bg-slate-100 px-1.5 py-0.5 rounded border border-slate-200">{record.shippingProvider || 'ไม่ระบุ/LEX/SPX'}</span>
                                </div>
                                <div className="flex justify-between items-center">
                                  <span className="text-gray-400 font-medium">หมายเลขพัสดุ (Tracking):</span>
                                  <span className="font-black text-slate-800 font-mono select-all bg-slate-50 border border-slate-150 px-2 py-0.5 rounded text-[11px] leading-none">
                                    {record.trackingNumber || 'ไม่ระบุ'}
                                  </span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-gray-400 font-medium">รหัสเส้นทาง (Route Code):</span>
                                  <span className="font-black text-indigo-600 font-mono text-[11px]">{record.routeCode || 'ไม่ระบุ'}</span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-gray-400 font-medium">หมายเลขคำสั่งซื้อ:</span>
                                  <span className="font-bold text-gray-900 font-mono">{record.orderId || 'ไม่ระบุ'}</span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-gray-400 font-medium">วันที่สั่งซื้อ:</span>
                                  <span className="font-bold text-gray-900">{record.orderDate || 'ไม่ระบุ'}</span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-gray-400 font-medium">ช่องทางการชำระเงิน:</span>
                                  <span className="font-bold text-emerald-600 bg-emerald-50 border border-emerald-100 px-1.5 py-0.5 rounded text-[10px] uppercase">{record.paymentMethod || 'ไม่ระบุ'}</span>
                                </div>
                              </div>
                            </div>

                            {/* Panel 2: Sender & Receiver Addresses */}
                            <div className="bg-white rounded-xl border border-gray-100 shadow-xs p-4 space-y-3">
                              <h5 className="font-bold text-xs text-gray-700 border-b border-gray-50 pb-2 flex items-center gap-1.5 text-emerald-600">
                                <User className="w-4 h-4 text-emerald-500" />
                                ที่อยู่ผู้ส่งและผู้รับสินค้า (Addresses)
                              </h5>
                              <div className="space-y-3 text-xs">
                                <div className="bg-slate-50 p-2.5 rounded-lg border border-slate-100 space-y-1">
                                  <span className="text-[9px] font-bold text-slate-400 uppercase tracking-wider block">ผู้ส่ง (Sender)</span>
                                  <div className="font-bold text-slate-800">{record.senderName || 'ไม่ระบุชื่อร้านค้า'}</div>
                                  {record.senderPhone && <div className="text-slate-500 text-[11px] font-mono">โทร: {record.senderPhone}</div>}
                                  {record.senderAddress && <div className="text-slate-500 text-[11px] leading-relaxed mt-0.5">{record.senderAddress}</div>}
                                </div>

                                <div className="bg-slate-50 p-2.5 rounded-lg border border-slate-100 space-y-1">
                                  <span className="text-[9px] font-bold text-slate-400 uppercase tracking-wider block">ผู้รับ (Receiver)</span>
                                  <div className="font-bold text-slate-800">{record.customerName || 'ไม่ระบุชื่อผู้รับ'}</div>
                                  {record.receiverPhone && <div className="text-slate-500 text-[11px] font-mono">โทร: {record.receiverPhone}</div>}
                                  {record.receiverAddress && <div className="text-slate-500 text-[11px] leading-relaxed mt-0.5">{record.receiverAddress}</div>}
                                </div>
                              </div>
                            </div>
                          </div>

                          {/* Items Table Section */}
                          <div className="space-y-2">
                            <div className="flex items-center justify-between border-b border-gray-100 pb-2">
                              <h4 className="text-xs font-bold text-gray-500 uppercase tracking-wider flex items-center gap-1.5">
                                <Table className="w-4 h-4 text-gray-400" />
                                ตารางวิเคราะห์รายการสินค้า (Extracted Rows)
                              </h4>

                              {record.sheetsStatus === 'not_configured' && (
                                <button
                                  onClick={(e) => handleReSyncSheets(record.id, e)}
                                  disabled={syncingId === record.id}
                                  className="px-3 py-1 border border-gray-200 hover:border-indigo-200 text-[10px] font-bold rounded-lg text-gray-600 hover:text-indigo-600 transition-colors flex items-center gap-1 outline-none"
                                >
                                  {syncingId === record.id ? (
                                    <RefreshCw className="w-3 h-3 animate-spin" />
                                  ) : (
                                    <RefreshCw className="w-3 h-3" />
                                  )}
                                  ส่งแถวข้อมูลไป Google Sheet
                                </button>
                              )}
                            </div>

                            <div className="border border-gray-100 rounded-xl overflow-hidden bg-white shadow-inner">
                              <table className="w-full text-xs text-left">
                                <thead className="bg-gray-50 text-gray-600 font-semibold border-b border-gray-100">
                                  <tr>
                                    <th className="py-2.5 px-4">ชื่อสินค้า</th>
                                    <th className="py-2.5 px-4 text-right" style={{ width: '120px' }}>ราคา/หน่วย</th>
                                    <th className="py-2.5 px-4 text-center" style={{ width: '80px' }}>จำนวน</th>
                                    <th className="py-2.5 px-4 text-right" style={{ width: '130px' }}>จำนวนเงินรวม</th>
                                  </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-50 text-gray-600">
                                  {record.items.map((item, idx) => (
                                    <tr key={item.id || idx} className="hover:bg-gray-50/20">
                                      <td className="py-2.5 px-4 font-medium text-gray-900">{item.productName}</td>
                                      <td className="py-2.5 px-4 text-right font-mono">{item.price.toFixed(2)} บาท</td>
                                      <td className="py-2.5 px-4 text-center font-mono font-bold">{item.quantity}</td>
                                      <td className="py-2.5 px-4 text-right font-mono font-bold text-gray-900">{item.amount.toFixed(2)} บาท</td>
                                    </tr>
                                  ))}
                                </tbody>
                                <tfoot className="bg-gray-50/30 border-t border-gray-100 font-bold text-gray-900">
                                  <tr>
                                    <td colSpan="3" className="py-3 px-4 text-right text-[10px] text-gray-400 uppercase tracking-wider">มูลค่ารวมสุทธิของออเดอร์:</td>
                                    <td className="py-3 px-4 text-right font-mono text-sm text-rose-600">{record.totalAmount.toLocaleString('th-TH', { minimumFractionDigits: 2 })} บาท</td>
                                  </tr>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      )}

                      {/* Record action buttons */}
                      <div className="mt-4 flex justify-between gap-4 border-t border-gray-100/80 pt-4">
                        {!isFailed ? (
                          <button
                            onClick={() => exportSingleRecordToCSV(record)}
                            className="px-3.5 py-1.5 text-xs text-emerald-700 hover:text-emerald-800 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-colors border border-emerald-150 flex items-center gap-1.5 font-bold outline-none"
                            title="ส่งออกแถวข้อมูลรายการสินค้านี้ไปยัง Excel หรือโปรแกรม Spreadsheet"
                          >
                            <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
                            ส่งออกออเดอร์นี้เป็น Excel (.csv)
                          </button>
                        ) : (
                          <span />
                        )}
                        <button
                          onClick={(e) => handleDelete(record.id, e)}
                          className="px-3 py-1.5 text-xs text-rose-600 hover:text-rose-700 bg-rose-50 hover:bg-rose-100 rounded-lg transition-colors border border-rose-100 flex items-center gap-1.5 font-semibold outline-none"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                          ลบประวัติรายการนี้
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

window.ScanHistory = ScanHistory;
