const { useState, useEffect, useRef } = React;

// Safe format helpers
const formatMoney = (val) => {
  if (val === null || val === undefined || isNaN(val)) return '0.00';
  return Number(val).toLocaleString('th-TH', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const formatInt = (val) => {
  if (val === null || val === undefined || isNaN(val)) return '0';
  return Number(val).toLocaleString('th-TH', { maximumFractionDigits: 0 });
};

// Pure React SVG Icon Component (100% immune to removeChild DOM mutation errors)
function Icon({ name, className = "w-4 h-4" }) {
  const iconPaths = {
    'building-2': (
      <React.Fragment>
        <path d="M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z"/>
        <path d="M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/>
        <path d="M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"/>
        <path d="M10 6h4"/><path d="M10 10h4"/><path d="M10 14h4"/><path d="M10 18h4"/>
      </React.Fragment>
    ),
    'upload-cloud': (
      <React.Fragment>
        <path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/>
        <path d="M12 12v9"/><path d="m16 16-4-4-4 4"/>
      </React.Fragment>
    ),
    'file-spreadsheet': (
      <React.Fragment>
        <path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/>
        <path d="M14 2v4a2 2 0 0 0 2 2h4"/>
        <path d="M8 13h2"/><path d="M14 13h2"/><path d="M8 17h2"/><path d="M14 17h2"/>
      </React.Fragment>
    ),
    'shield-check': (
      <React.Fragment>
        <path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>
        <path d="m9 12 2 2 4-4"/>
      </React.Fragment>
    ),
    'lightbulb': (
      <React.Fragment>
        <path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/>
        <path d="M9 18h6"/><path d="M10 22h4"/>
      </React.Fragment>
    ),
    'presentation': (
      <React.Fragment>
        <path d="M2 3h20"/><path d="M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3"/>
        <path d="m7 21 5-5 5 5"/>
      </React.Fragment>
    ),
    'bot': (
      <React.Fragment>
        <path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/>
        <path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>
      </React.Fragment>
    ),
    'sparkles': (
      <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>
    ),
    'key': (
      <React.Fragment>
        <circle cx="7.5" cy="15.5" r="5.5"/>
        <path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>
      </React.Fragment>
    ),
    'layers': (
      <React.Fragment>
        <path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/>
        <path d="m22 12.5-9.17 4.16a2 2 0 0 1-1.66 0L2 12.5"/>
        <path d="m22 17.5-9.17 4.16a2 2 0 0 1-1.66 0L2 17.5"/>
      </React.Fragment>
    ),
    'file-text': (
      <React.Fragment>
        <path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/>
        <path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>
      </React.Fragment>
    ),
    'trash-2': (
      <React.Fragment>
        <path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/>
        <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/>
      </React.Fragment>
    ),
    'download': (
      <React.Fragment>
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
        <polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>
      </React.Fragment>
    ),
    'sliders': (
      <React.Fragment>
        <line x1="4" x2="4" y1="21" y2="14"/><line x1="4" x2="4" y1="10" y2="3"/>
        <line x1="12" x2="12" y1="21" y2="12"/><line x1="12" x2="12" y1="8" y2="3"/>
        <line x1="20" x2="20" y1="21" y2="16"/><line x1="20" x2="20" y1="12" y2="3"/>
        <line x1="1" x2="7" y1="14" y2="14"/><line x1="9" x2="15" y1="8" y2="8"/><line x1="17" x2="23" y1="16" y2="16"/>
      </React.Fragment>
    ),
    'trophy': (
      <React.Fragment>
        <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/>
        <path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/>
        <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/>
        <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/>
      </React.Fragment>
    ),
    'target': (
      <React.Fragment>
        <circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>
      </React.Fragment>
    ),
    'shield-alert': (
      <React.Fragment>
        <path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>
        <line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/>
      </React.Fragment>
    ),
    'check-circle-2': (
      <React.Fragment>
        <circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>
      </React.Fragment>
    ),
    'eye': (
      <React.Fragment>
        <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>
      </React.Fragment>
    ),
    'x': (
      <React.Fragment>
        <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
      </React.Fragment>
    )
  };

  return (
    <svg 
      xmlns="http://www.w3.org/2000/svg" 
      viewBox="0 0 24 24" 
      fill="none" 
      stroke="currentColor" 
      strokeWidth="2" 
      strokeLinecap="round" 
      strokeLinejoin="round" 
      className={className}
    >
      {iconPaths[name] || <circle cx="12" cy="12" r="10"/>}
    </svg>
  );
}

// React Error Boundary to eliminate White Screens completely
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, errorInfo) {
    console.error("React Error Boundary Caught:", error, errorInfo);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen bg-slate-100 flex items-center justify-center p-6 text-center">
          <div className="bg-white rounded-2xl p-8 max-w-lg shadow-xl border border-slate-200">
            <div className="w-12 h-12 rounded-2xl bg-rose-100 text-rose-600 flex items-center justify-center mx-auto mb-4 font-bold text-xl">!</div>
            <h2 className="text-lg font-bold text-slate-900 mb-2">เกิดข้อผิดพลาดในการแสดงผล</h2>
            <p className="text-xs text-slate-500 mb-4">{this.state.error?.toString()}</p>
            <button 
              onClick={() => { localStorage.clear(); window.location.reload(); }}
              className="px-5 py-2.5 bg-brand-navy text-white text-xs font-bold rounded-xl shadow hover:bg-brand-navy-light"
            >
              รีเฟรชและเริ่มใหม่
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

const API_BASE = '/api';

function App() {
  const [activeTab, setActiveTab] = useState('upload');
  
  // Clean initial state (Empty by default)
  const [suppliers, setSuppliers] = useState([]);
  const [priceMatrix, setPriceMatrix] = useState([]);
  const [commercialMatrix, setCommercialMatrix] = useState([]);
  const [vendorScores, setVendorScores] = useState([]);
  const [analysis, setAnalysis] = useState(null);
  const [weights, setWeights] = useState({
    price_weight: 50,
    credit_weight: 20,
    delivery_weight: 15,
    warranty_weight: 15
  });

  const [apiKey, setApiKey] = useState(() => localStorage.getItem('GEMINI_API_KEY') || '');
  const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [toastMessage, setToastMessage] = useState('');
  const [previewSupplier, setPreviewSupplier] = useState(null);
  const [activeSlide, setActiveSlide] = useState(1);

  // Copilot chat state
  const [chatMessages, setChatMessages] = useState([
    {
      sender: 'bot',
      text: 'สวัสดีครับ! ผมคือ **AI Procurement Copilot** ผู้ช่วยวิเคราะห์ใบเสนอราคา มีหน้าที่ตอบคำถาม ค้นหาข้อมูล เปรียบเทียบเงื่อนไข และวิเคราะห์ตัวเลขสถิติจากเอกสารที่ท่านอัปโหลด (ข้อมูลทั้งหมดจะอ้างอิงจากข้อเท็จจริงในเอกสาร 100% หากไม่มีข้อมูลจะแจ้งตรงๆ ว่า "ผมไม่พบข้อมูล" ครับ)',
      timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    }
  ]);
  const [chatInput, setChatInput] = useState('');
  const [chatLoading, setChatLoading] = useState(false);
  const chatEndRef = useRef(null);

  const showToast = (msg) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(''), 3500);
  };

  const handleClearAllData = () => {
    setSuppliers([]);
    setPriceMatrix([]);
    setCommercialMatrix([]);
    setVendorScores([]);
    setAnalysis(null);
    showToast('ล้างข้อมูลทั้งหมดในระบบเรียบร้อยแล้ว');
  };

  const handleLoadSample = async () => {
    setLoading(true);
    try {
      const res = await fetch(`${API_BASE}/sample-data`);
      if (!res.ok) throw new Error('Failed to load sample data');
      const data = await res.json();
      
      setSuppliers(data.suppliers || []);
      setPriceMatrix(data.price_matrix || []);
      setCommercialMatrix(data.commercial_matrix || []);
      setVendorScores(data.vendor_scores || []);
      setWeights(data.weights || { price_weight: 50, credit_weight: 20, delivery_weight: 15, warranty_weight: 15 });
      setAnalysis(data.analysis || null);
      showToast('โหลดข้อมูลใบเสนอราคาตัวอย่าง (3 Suppliers) สำเร็จ');
    } catch (err) {
      console.error(err);
      showToast('ไม่สามารถเชื่อมต่อ Backend API ได้');
    } finally {
      setLoading(false);
    }
  };

  const recomputeMatrix = async (currentSuppliers, currentWeights) => {
    if (!currentSuppliers || currentSuppliers.length === 0) return;
    try {
      const res = await fetch(`${API_BASE}/compare`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          suppliers: currentSuppliers,
          weights: currentWeights
        })
      });
      if (!res.ok) throw new Error('Compare error');
      const data = await res.json();

      setPriceMatrix(data.price_matrix || []);
      setCommercialMatrix(data.commercial_matrix || []);
      setVendorScores(data.vendor_scores || []);
      setAnalysis(data.analysis || null);
    } catch (err) {
      console.error(err);
    }
  };

  const handleUpdateWeights = (field, val) => {
    const num = Math.max(0, Math.min(100, Number(val)));
    const updated = { ...weights, [field]: num };
    setWeights(updated);
    recomputeMatrix(suppliers, updated);
  };

  const handleResetWeights = () => {
    const def = { price_weight: 50, credit_weight: 20, delivery_weight: 15, warranty_weight: 15 };
    setWeights(def);
    recomputeMatrix(suppliers, def);
  };

  const handleUploadFiles = async (e) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setLoading(true);
    try {
      const formData = new FormData();
      for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i]);
      }
      if (apiKey) formData.append('api_key', apiKey);

      const res = await fetch(`${API_BASE}/upload-and-extract`, {
        method: 'POST',
        body: formData
      });

      if (!res.ok) throw new Error('Upload failed');
      const extracted = await res.json();

      const newBatch = Array.isArray(extracted) ? extracted : [extracted];
      const updated = [...suppliers, ...newBatch];
      setSuppliers(updated);
      await recomputeMatrix(updated, weights);
      setActiveTab('matrix');
      showToast(`ถอดข้อมูลสำเร็จ ${newBatch.length} รายการ!`);
    } catch (err) {
      console.error(err);
      showToast('เกิดข้อผิดพลาดในการอัปโหลดไฟล์');
    } finally {
      setLoading(false);
      e.target.value = '';
    }
  };

  const handleDeleteSupplier = (supId) => {
    const updated = suppliers.filter(s => s.id !== supId);
    setSuppliers(updated);
    if (updated.length > 0) {
      recomputeMatrix(updated, weights);
    } else {
      setPriceMatrix([]);
      setCommercialMatrix([]);
      setVendorScores([]);
      setAnalysis(null);
    }
    showToast('ลบข้อมูลผู้ขายเรียบร้อยแล้ว');
  };

  const handleExportExcel = async () => {
    if (suppliers.length === 0) return;
    try {
      const res = await fetch(`${API_BASE}/export/excel`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ suppliers, weights })
      });
      if (!res.ok) throw new Error('Export Excel failed');
      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'Procurement_Quotation_Comparison.xlsx';
      document.body.appendChild(a);
      a.click();
      a.remove();
      showToast('ดาวน์โหลดไฟล์ Excel (.xlsx) สำเร็จ!');
    } catch (err) {
      console.error(err);
      showToast('เกิดข้อผิดพลาดในการดาวน์โหลด Excel');
    }
  };

  const handleExportPptx = async () => {
    if (suppliers.length === 0) return;
    try {
      const res = await fetch(`${API_BASE}/export/pptx`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ suppliers, weights })
      });
      if (!res.ok) throw new Error('Export PPTX failed');
      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'Executive_Procurement_Deck.pptx';
      document.body.appendChild(a);
      a.click();
      a.remove();
      showToast('ดาวน์โหลดไฟล์สไลด์ผู้บริหาร (.pptx) สำเร็จ!');
    } catch (err) {
      console.error(err);
      showToast('เกิดข้อผิดพลาดในการดาวน์โหลด PPTX');
    }
  };

  const handleSendChat = async (question) => {
    const q = question || chatInput;
    if (!q.trim() || chatLoading) return;

    const userMsg = {
      sender: 'user',
      text: q,
      timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    };

    setChatMessages(prev => [...prev, userMsg]);
    if (!question) setChatInput('');
    setChatLoading(true);

    try {
      const res = await fetch(`${API_BASE}/chat`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: q,
          suppliers,
          price_matrix: priceMatrix,
          vendor_scores: vendorScores,
          api_key: apiKey
        })
      });
      const botRes = await res.json();
      setChatMessages(prev => [...prev, {
        sender: 'bot',
        text: botRes.reply || "ผมไม่พบข้อมูล",
        sources: botRes.sources_cited || [],
        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      }]);
    } catch (err) {
      setChatMessages(prev => [...prev, {
        sender: 'bot',
        text: 'ผมไม่พบข้อมูล หรือระบบขัดข้องชั่วคราวครับ',
        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      }]);
    } finally {
      setChatLoading(false);
      setTimeout(() => chatEndRef.current?.scrollIntoView({ behavior: 'smooth' }), 100);
    }
  };

  // Render Chart.js on Deep Insights Tab
  const chartCanvasRef = useRef(null);
  useEffect(() => {
    let chartInstance = null;
    if (activeTab === 'insights' && chartCanvasRef.current && suppliers.length > 0 && analysis && window.Chart) {
      try {
        const labels = suppliers.map(s => (s.vendor_name || 'Supplier').split('(')[0].trim());
        const data = suppliers.map(s => s.grand_total || 0);
        const bgColors = suppliers.map(() => '#156082');

        if (analysis.optimal_split_total > 0) {
          labels.push('แยกซื้อต่ำสุด (Optimal Split)');
          data.push(analysis.optimal_split_total);
          bgColors.push('#10B981');
        }

        chartInstance = new window.Chart(chartCanvasRef.current, {
          type: 'bar',
          data: {
            labels: labels,
            datasets: [{
              label: 'งบประมาณรวมสุทธิ (บาท)',
              data: data,
              backgroundColor: bgColors,
              borderRadius: 8
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: { display: false },
              tooltip: {
                callbacks: {
                  label: (ctx) => ` ฿${formatMoney(ctx.raw)}`
                }
              }
            },
            scales: {
              y: {
                ticks: {
                  callback: (val) => `฿${(val / 1000).toFixed(0)}k`
                },
                grid: { color: '#F1F5F9' }
              },
              x: {
                grid: { display: false }
              }
            }
          }
        });
      } catch (e) {
        console.warn("Chart error:", e);
      }
    }
    return () => {
      if (chartInstance) {
        try { chartInstance.destroy(); } catch (e) {}
      }
    };
  }, [activeTab, suppliers, analysis]);

  const totalWeight = Number(weights.price_weight || 0) + Number(weights.credit_weight || 0) + Number(weights.delivery_weight || 0) + Number(weights.warranty_weight || 0);
  const topVendor = vendorScores.length > 0 ? vendorScores[0] : null;

  return (
    <ErrorBoundary>
      <div className="min-h-screen flex flex-col bg-slate-50">
        
        {/* Toast Alert */}
        {toastMessage && (
          <div className="fixed bottom-6 right-6 z-50 bg-slate-900 text-white text-xs font-semibold px-4 py-3 rounded-2xl shadow-xl border border-slate-700 flex items-center gap-2 animate-bounce">
            <Icon name="sparkles" className="w-4 h-4 text-amber-400 shrink-0" />
            <span>{toastMessage}</span>
          </div>
        )}

        {/* API Key Modal */}
        {isApiKeyModalOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-4 animate-fade-in">
            <div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl border border-slate-100 relative">
              <button 
                onClick={() => setIsApiKeyModalOpen(false)}
                className="absolute top-4 right-4 text-slate-400 hover:text-slate-600 p-1.5 rounded-lg hover:bg-slate-100"
              >
                <Icon name="x" className="w-5 h-5" />
              </button>
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-xl bg-brand-teal/10 flex items-center justify-center text-brand-teal">
                  <Icon name="key" className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="text-base font-bold text-slate-900">Google Gemini API Key</h3>
                  <p className="text-xs text-slate-500">สำหรับ AI Multimodal OCR & Deep Analysis</p>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-semibold text-slate-700 mb-1.5">API Key (Gemini 2.0 / 1.5 Flash)</label>
                  <input 
                    type="password"
                    value={apiKey}
                    onChange={(e) => setApiKey(e.target.value)}
                    placeholder="AIzaSy..."
                    className="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-brand-teal/40 text-xs font-mono"
                  />
                </div>
                <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 text-[11px] text-slate-600 space-y-1">
                  <p className="font-semibold text-slate-800 flex items-center gap-1">
                    <Icon name="shield-check" className="w-3.5 h-3.5 text-emerald-600" />
                    API Key ถูกเก็บเฉพาะใน Browser ของคุณ
                  </p>
                  <p>หากไม่มี API Key ระบบยังมี Smart Rule-Based Engine ทำงานให้อัตโนมัติ</p>
                </div>
                <div className="flex justify-end gap-2 pt-2">
                  <button
                    onClick={() => { localStorage.setItem('GEMINI_API_KEY', apiKey); setIsApiKeyModalOpen(false); showToast('บันทึก API Key แล้ว'); }}
                    className="px-5 py-2 bg-brand-navy hover:bg-brand-navy-light text-white text-xs font-bold rounded-xl shadow-sm"
                  >
                    บันทึก API Key
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Main Header */}
        <header className="bg-brand-navy text-white sticky top-0 z-40 shadow-lg border-b border-brand-navy-light/40">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-20">
              <div className="flex items-center gap-3.5">
                <div className="w-11 h-11 rounded-2xl bg-gradient-to-tr from-brand-teal to-brand-coral flex items-center justify-center shadow-md text-white">
                  <Icon name="building-2" className="w-6 h-6" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <h1 className="text-lg font-extrabold tracking-tight text-white flex items-center gap-1.5">
                      AI Quotation Intelligence
                      <span className="text-[10px] uppercase font-bold tracking-wider px-2 py-0.5 rounded-full bg-brand-coral/20 text-brand-coral border border-brand-coral/40">
                        Procurement Pro
                      </span>
                    </h1>
                  </div>
                  <p className="text-xs text-slate-300 font-medium">
                    ระบบถอดข้อมูลใบเสนอราคา วิเคราะห์ Matrix เปรียบเทียบเชิงลึก & สร้างสไลด์ผู้บริหาร
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-2.5">
                <div className="hidden md:flex items-center gap-2 bg-slate-800/80 px-3 py-1.5 rounded-xl border border-slate-700/60 text-xs">
                  <div className="flex items-center gap-1.5 text-slate-300">
                    <Icon name="layers" className="w-3.5 h-3.5 text-brand-teal" />
                    <span>ผู้ขาย: <strong className="text-white font-bold">{suppliers.length}</strong> ราย</span>
                  </div>
                  <div className="w-px h-3.5 bg-slate-700"></div>
                  <div className="flex items-center gap-1.5 text-slate-300">
                    <Icon name="file-text" className="w-3.5 h-3.5 text-amber-400" />
                    <span>รายการ: <strong className="text-white font-bold">{priceMatrix.length}</strong> รายการ</span>
                  </div>
                </div>

                {suppliers.length > 0 && (
                  <button
                    onClick={handleClearAllData}
                    className="flex items-center gap-1 px-2.5 py-2 bg-slate-800 hover:bg-rose-950/40 text-slate-300 hover:text-rose-300 rounded-xl text-xs font-semibold border border-slate-700 hover:border-rose-800/60 transition-all"
                    title="ล้างข้อมูลทั้งหมดและเริ่มใหม่"
                  >
                    <Icon name="trash-2" className="w-3.5 h-3.5" />
                    <span className="hidden sm:inline">ล้างข้อมูล</span>
                  </button>
                )}

                <button
                  onClick={handleLoadSample}
                  disabled={loading}
                  className="flex items-center gap-1.5 px-3.5 py-2 bg-slate-800 hover:bg-slate-700 text-slate-200 hover:text-white rounded-xl text-xs font-semibold border border-slate-700 transition-all active:scale-95"
                >
                  <Icon name="sparkles" className="w-3.5 h-3.5 text-amber-400" />
                  <span>โหลดตัวอย่าง (Demo)</span>
                </button>

                <button
                  onClick={() => setIsApiKeyModalOpen(true)}
                  className={`flex items-center gap-1.5 px-3 py-2 rounded-xl text-xs font-semibold border transition-all ${
                    apiKey ? 'bg-emerald-950/40 text-emerald-300 border-emerald-700/60' : 'bg-slate-800 text-slate-300 border-slate-700'
                  }`}
                >
                  <Icon name="key" className={`w-3.5 h-3.5 ${apiKey ? 'text-emerald-400' : 'text-slate-400'}`} />
                  <span className="hidden sm:inline">{apiKey ? 'Gemini AI Active' : 'ตั้งค่า API Key'}</span>
                </button>
              </div>
            </div>
          </div>
        </header>

        {/* Tabs Navigation */}
        <div className="bg-white border-b border-slate-200 sticky top-20 z-30 shadow-xs">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <nav className="flex space-x-1 sm:space-x-2 overflow-x-auto py-2.5">
              {[
                { id: 'upload', label: '1. นำเข้าเอกสาร', icon: 'upload-cloud' },
                { id: 'matrix', label: '2. เปรียบเทียบราคา Matrix', icon: 'file-spreadsheet' },
                { id: 'commercial', label: '3. เงื่อนไขสัญญา & ปรับค่าน้ำหนัก', icon: 'shield-check' },
                { id: 'insights', label: '4. วิเคราะห์เชิงลึก & กลยุทธ์', icon: 'lightbulb' },
                { id: 'pptx', label: '5. สไลด์ผู้บริหาร .pptx', icon: 'presentation' },
                { id: 'copilot', label: '6. ผู้ช่วยจัดซื้อ AI Copilot', icon: 'bot' }
              ].map((t) => (
                <button
                  key={t.id}
                  onClick={() => setActiveTab(t.id)}
                  className={`flex items-center gap-2 px-3.5 py-2 rounded-xl text-xs font-bold transition-all whitespace-nowrap ${
                    activeTab === t.id 
                      ? 'bg-brand-navy text-white shadow-sm' 
                      : 'text-slate-600 hover:text-slate-900 hover:bg-slate-100'
                  }`}
                >
                  <Icon name={t.icon} className={`w-4 h-4 ${activeTab === t.id ? 'text-amber-400' : 'text-slate-400'}`} />
                  <span>{t.label}</span>
                </button>
              ))}
            </nav>
          </div>
        </div>

        {/* Main Tab Content */}
        <main className="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-6">
          
          {/* TAB 1: UPLOAD */}
          {activeTab === 'upload' && (
            <div className="space-y-6">
              <div className="bg-gradient-to-r from-brand-navy to-brand-navy-light text-white rounded-2xl p-6 shadow-md relative overflow-hidden">
                <div className="max-w-3xl">
                  <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-brand-coral/20 border border-brand-coral/40 text-brand-coral text-xs font-bold mb-3">
                    <Icon name="sparkles" className="w-3.5 h-3.5" />
                    AI Document Extraction (Multimodal OCR)
                  </span>
                  <h2 className="text-xl sm:text-2xl font-bold tracking-tight mb-2">
                    อัปโหลดเอกสารใบเสนอราคาจาก Supplier หลายรายพร้อมกัน
                  </h2>
                  <p className="text-slate-300 text-xs sm:text-sm leading-relaxed">
                    รองรับไฟล์ PDF, รูปภาพ (PNG/JPG), ไฟล์ Excel (.xlsx), และ Word (.docx) ระบบ AI จะถอดข้อมูลราคา เงื่อนไขการค้า และจับคู่สินค้าให้อัตโนมัติ
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
                {/* Dropzone */}
                <div className="lg:col-span-7 bg-white rounded-2xl p-6 border border-slate-200 shadow-sm flex flex-col justify-between">
                  <div>
                    <h3 className="text-sm font-bold text-slate-800 flex items-center gap-2 mb-3">
                      <Icon name="upload-cloud" className="w-4 h-4 text-brand-teal" />
                      <span>พื้นที่อัปโหลดไฟล์ (Upload Dropzone)</span>
                    </h3>
                    <label className="border-2 border-dashed border-slate-300 hover:border-brand-teal rounded-2xl p-8 text-center cursor-pointer flex flex-col items-center justify-center min-h-[200px] hover:bg-slate-50 transition-all">
                      <input type="file" multiple accept=".pdf,.png,.jpg,.jpeg,.xlsx,.xls,.docx,.doc" onChange={handleUploadFiles} className="hidden" />
                      <div className="w-14 h-14 rounded-2xl bg-brand-teal/10 flex items-center justify-center text-brand-teal mb-3">
                        <Icon name="upload-cloud" className="w-7 h-7" />
                      </div>
                      <p className="text-sm font-bold text-slate-700">คลิกเพื่อเลือกไฟล์ใบเสนอราคา (หรือลากไฟล์มาวาง)</p>
                      <p className="text-xs text-slate-400 mt-1">PDF, JPG, PNG, XLSX, DOCX</p>
                      <div className="flex gap-2 mt-4">
                        <span className="px-2 py-0.5 rounded bg-rose-50 text-rose-600 border border-rose-200 text-[10px] font-semibold">PDF</span>
                        <span className="px-2 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-200 text-[10px] font-semibold">PNG/JPG</span>
                        <span className="px-2 py-0.5 rounded bg-emerald-50 text-emerald-600 border border-emerald-200 text-[10px] font-semibold">Excel .XLSX</span>
                        <span className="px-2 py-0.5 rounded bg-sky-50 text-sky-600 border border-sky-200 text-[10px] font-semibold">Word .DOCX</span>
                      </div>
                    </label>
                  </div>
                  <div className="mt-4 pt-4 border-t border-slate-100 flex items-center justify-between text-xs text-slate-500">
                    <span>ต้องการทดสอบด้วยชุดข้อมูลจำลอง?</span>
                    <button onClick={handleLoadSample} className="text-brand-teal hover:text-brand-navy font-bold flex items-center gap-1">
                      <Icon name="sparkles" className="w-3.5 h-3.5 text-amber-500" />
                      <span>โหลดตัวอย่าง 3 ใบเสนอราคา (Demo)</span>
                    </button>
                  </div>
                </div>

                {/* Status / Instruction Box */}
                <div className="lg:col-span-5 bg-white rounded-2xl p-6 border border-slate-200 shadow-sm flex flex-col justify-between">
                  <div>
                    <h3 className="text-sm font-bold text-slate-800 flex items-center gap-2 mb-3">
                      <Icon name="shield-check" className="w-4 h-4 text-emerald-600" />
                      <span>ขั้นตอนการทำงานอัตโนมัติ</span>
                    </h3>
                    <div className="space-y-3 text-xs text-slate-600">
                      <div className="flex items-start gap-2.5 p-2.5 bg-slate-50 rounded-xl">
                        <span className="w-5 h-5 rounded-full bg-brand-teal text-white flex items-center justify-center font-bold text-[10px] shrink-0">1</span>
                        <p><strong>Upload เอกสาร:</strong> นำเข้าไฟล์ใบเสนอราคาจาก Supplier แต่ละราย</p>
                      </div>
                      <div className="flex items-start gap-2.5 p-2.5 bg-slate-50 rounded-xl">
                        <span className="w-5 h-5 rounded-full bg-brand-teal text-white flex items-center justify-center font-bold text-[10px] shrink-0">2</span>
                        <p><strong>AI Multimodal Extraction:</strong> สกัดชื่อสินค้า สเปค ราคา เครดิตเทอม และการรับประกัน</p>
                      </div>
                      <div className="flex items-start gap-2.5 p-2.5 bg-slate-50 rounded-xl">
                        <span className="w-5 h-5 rounded-full bg-brand-teal text-white flex items-center justify-center font-bold text-[10px] shrink-0">3</span>
                        <p><strong>Matrix & Strategic Analysis:</strong> เปรียบเทียบราคาข้างกัน และสร้างรายงานสไลด์ .pptx</p>
                      </div>
                    </div>
                  </div>

                  {loading && (
                    <div className="mt-4 p-3 bg-brand-teal/10 rounded-xl border border-brand-teal/30 text-brand-teal text-xs font-semibold flex items-center gap-2">
                      <div className="w-4 h-4 border-2 border-brand-teal border-t-transparent rounded-full animate-spin"></div>
                      <span>AI กำลังถอดข้อมูลและจับคู่รายการสินค้า...</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Extracted Suppliers Cards */}
              <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                <div className="flex items-center justify-between mb-5">
                  <h3 className="text-base font-bold text-slate-900 flex items-center gap-2">
                    <Icon name="check-circle-2" className="w-5 h-5 text-emerald-500" />
                    <span>ผู้ขายที่ถอดข้อมูลแล้ว ({suppliers.length} รายการ)</span>
                  </h3>
                </div>

                {suppliers.length === 0 ? (
                  <div className="text-center py-12 text-slate-400 bg-slate-50 rounded-xl border border-dashed border-slate-200">
                    <Icon name="file-spreadsheet" className="w-10 h-10 text-slate-300 mx-auto mb-2" />
                    <p className="text-sm font-semibold text-slate-600">ยังไม่มีข้อมูลใบเสนอราคาในระบบ</p>
                    <p className="text-xs text-slate-400 mt-1">กรุณาอัปโหลดไฟล์ใบเสนอราคาด้านบน หรือคลิก "โหลดตัวอย่าง (Demo)" เพื่อเริ่มต้น</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                    {suppliers.map(sup => (
                      <div key={sup.id} className="rounded-2xl border border-slate-200 bg-white p-5 hover:shadow-md transition-all flex flex-col justify-between">
                        <div>
                          <div className="flex items-start justify-between gap-2 mb-2">
                            <span className="px-2 py-0.5 rounded bg-slate-100 text-slate-600 text-[10px] font-mono font-semibold">
                              {sup.quotation_number || 'QT-REF'}
                            </span>
                            <button onClick={() => handleDeleteSupplier(sup.id)} className="text-slate-300 hover:text-rose-500">
                              <Icon name="trash-2" className="w-4 h-4" />
                            </button>
                          </div>
                          <h4 className="text-sm font-bold text-slate-900 line-clamp-2">{sup.vendor_name}</h4>
                          <p className="text-[11px] text-slate-400 mt-0.5 flex items-center gap-1">
                            <Icon name="file-text" className="w-3 h-3" />
                            <span className="truncate">{sup.source_filename}</span>
                          </p>

                          <div className="bg-slate-50 rounded-xl p-3 my-3 space-y-1 text-xs">
                            <div className="flex justify-between text-slate-500">
                              <span>ก่อน VAT:</span>
                              <span className="font-semibold text-slate-700">฿{formatMoney(sup.subtotal)}</span>
                            </div>
                            <div className="flex justify-between font-bold pt-1 border-t border-slate-200 text-brand-navy">
                              <span>ยอดรวมสุทธิ:</span>
                              <span className="font-extrabold text-sm">฿{formatMoney(sup.grand_total)}</span>
                            </div>
                          </div>

                          <div className="grid grid-cols-3 gap-1.5 text-center text-[10px] my-2">
                            <div className="bg-slate-100 p-1.5 rounded-lg">
                              <span className="text-slate-400 block">เครดิต</span>
                              <strong className="text-slate-800">{sup.commercial_terms?.credit_term_days || 30} วัน</strong>
                            </div>
                            <div className="bg-slate-100 p-1.5 rounded-lg">
                              <span className="text-slate-400 block">ส่งมอบ</span>
                              <strong className="text-slate-800">{sup.commercial_terms?.delivery_lead_days || 14} วัน</strong>
                            </div>
                            <div className="bg-slate-100 p-1.5 rounded-lg">
                              <span className="text-slate-400 block">รับประกัน</span>
                              <strong className="text-slate-800">{sup.commercial_terms?.warranty_months || 12} ด.</strong>
                            </div>
                          </div>
                        </div>

                        <button
                          onClick={() => setPreviewSupplier(sup)}
                          className="w-full mt-3 py-1.5 bg-slate-100 hover:bg-brand-teal hover:text-white text-slate-700 rounded-xl text-xs font-semibold transition-all flex items-center justify-center gap-1"
                        >
                          <Icon name="eye" className="w-3.5 h-3.5" />
                          <span>ดูรายละเอียดเต็ม</span>
                        </button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* TAB 2: PRICE MATRIX */}
          {activeTab === 'matrix' && (
            <div className="space-y-6">
              <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                  <h2 className="text-base sm:text-lg font-bold text-slate-900 flex items-center gap-2">
                    <Icon name="file-spreadsheet" className="w-5 h-5 text-brand-teal" />
                    <span>ตารางเปรียบเทียบราคา Matrix (Side-by-Side Comparison)</span>
                  </h2>
                  <p className="text-xs text-slate-500 mt-1">
                    เปรียบเทียบราคาต่อหน่วยและราคารวมข้างกันชัดเจน พร้อมไฮไลต์ราคาต่ำสุด (เขียว) และส่วนต่างราคา
                  </p>
                </div>

                <button
                  onClick={handleExportExcel}
                  disabled={suppliers.length === 0}
                  className="flex items-center gap-1.5 px-4 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold shadow-sm transition-all active:scale-95 disabled:opacity-50"
                >
                  <Icon name="download" className="w-4 h-4" />
                  <span>Export เป็น Excel (.xlsx)</span>
                </button>
              </div>

              {suppliers.length === 0 ? (
                <div className="bg-white rounded-2xl p-16 text-center text-slate-400 border border-slate-200">
                  <Icon name="file-spreadsheet" className="w-12 h-12 text-slate-300 mx-auto mb-2" />
                  <p className="font-semibold text-slate-600">ยังไม่มีข้อมูลสำหรับเปรียบเทียบราคา</p>
                  <p className="text-xs text-slate-400 mt-1">กรุณาอัปโหลดใบเสนอราคาในแท็บ "1. นำเข้าเอกสาร" หรือคลิก "โหลดตัวอย่าง (Demo)"</p>
                </div>
              ) : (
                <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
                  <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse text-xs">
                      <thead>
                        <tr className="bg-brand-navy text-white divide-x divide-brand-navy-light/60">
                          <th className="p-3.5 w-12 text-center font-bold">ลำดับ</th>
                          <th className="p-3.5 min-w-[220px] font-bold">รายการสินค้ามาตรฐาน</th>
                          <th className="p-3.5 w-20 text-center font-bold">จำนวน</th>
                          {suppliers.map(sup => (
                            <th key={sup.id} className="p-3.5 min-w-[230px] text-center font-bold bg-brand-navy">
                              <div className="text-amber-300 font-extrabold truncate max-w-[200px] mx-auto">{sup.vendor_name}</div>
                              <div className="text-[10px] text-slate-300 font-normal mt-0.5">{sup.source_filename}</div>
                            </th>
                          ))}
                          <th className="p-3.5 w-24 text-center font-bold bg-slate-900">ส่วนต่าง (%)</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-200 text-slate-700">
                        {priceMatrix.map(row => (
                          <tr key={row.row_no} className="hover:bg-slate-50/70 divide-x divide-slate-100">
                            <td className="p-3.5 text-center font-mono text-slate-400">{row.row_no}</td>
                            <td className="p-3.5">
                              <div className="font-bold text-slate-900">{row.standard_name}</div>
                              <div className="text-[10px] text-slate-400">เฉลี่ยตลาด: ฿{formatMoney(row.average_unit_price)}</div>
                            </td>
                            <td className="p-3.5 text-center font-semibold">{row.quantity} {row.unit}</td>
                            {suppliers.map(sup => {
                              const itemData = row.supplier_data?.[sup.id];
                              if (!itemData || itemData.unit_price === 0) {
                                return <td key={sup.id} className="p-3.5 text-center text-slate-300 italic">-</td>;
                              }
                              return (
                                <td key={sup.id} className={`p-3.5 ${itemData.is_lowest ? 'bg-emerald-50/70 font-semibold' : ''}`}>
                                  <div className="flex items-center justify-between text-[11px] mb-1">
                                    <span className="text-slate-400 truncate max-w-[130px]">{itemData.item_name_offered}</span>
                                    {itemData.is_lowest && <span className="px-1.5 py-0.2 rounded bg-emerald-600 text-white text-[9px] font-bold">ต่ำสุด</span>}
                                  </div>
                                  <div className="flex justify-between items-baseline">
                                    <span className="text-slate-500 text-[10px]">ต่อหน่วย:</span>
                                    <span className={`font-mono font-bold ${itemData.is_lowest ? 'text-emerald-700 text-sm' : 'text-slate-800'}`}>
                                      ฿{formatMoney(itemData.unit_price)}
                                    </span>
                                  </div>
                                  <div className="flex justify-between items-baseline text-[10px] text-slate-500 pt-0.5 border-t border-slate-100">
                                    <span>รวม:</span>
                                    <span className="font-mono">฿{formatMoney(itemData.total_price)}</span>
                                  </div>
                                </td>
                              );
                            })}
                            <td className="p-3.5 text-center font-mono font-bold">
                              <span className={`px-2 py-0.5 rounded text-xs ${(row.price_spread_pct || 0) > 15 ? 'bg-rose-100 text-rose-700' : 'bg-slate-100 text-slate-600'}`}>
                                {(row.price_spread_pct || 0).toFixed(1)}%
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                      <tfoot>
                        <tr className="bg-slate-100 font-bold divide-x divide-slate-200 border-t-2 border-slate-300">
                          <td colSpan={3} className="p-4 text-right text-slate-800">ราคารวมสุทธิ (Grand Total + VAT 7%):</td>
                          {suppliers.map(sup => (
                            <td key={sup.id} className="p-4 text-right font-mono text-sm font-extrabold text-brand-navy">
                              ฿{formatMoney(sup.grand_total)}
                            </td>
                          ))}
                          <td className="p-4 bg-slate-200"></td>
                        </tr>
                      </tfoot>
                    </table>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* TAB 3: COMMERCIAL TERMS & WEIGHTS */}
          {activeTab === 'commercial' && (
            <div className="space-y-6">
              {/* Weight Sliders */}
              <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4 pb-3 border-b border-slate-100">
                  <div>
                    <h3 className="text-base font-bold text-slate-900 flex items-center gap-2">
                      <Icon name="sliders" className="w-5 h-5 text-brand-coral" />
                      <span>ปรับแต่งค่าน้ำหนักการประเมิน (Evaluation Weight Customizer)</span>
                    </h3>
                    <p className="text-xs text-slate-500 mt-0.5">เลื่อน Slider เพื่อปรับสัดส่วน ระบบจะคำนวณคะแนนรวมและจัดอันดับผู้ชนะใหม่แบบ Real-time ทันที</p>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className={`px-3 py-1 rounded-xl text-xs font-bold ${totalWeight === 100 ? 'bg-emerald-50 text-emerald-700 border border-emerald-200' : 'bg-amber-50 text-amber-700 border border-amber-200'}`}>
                      รวม: {totalWeight}%
                    </span>
                    <button onClick={handleResetWeights} className="p-1.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100 rounded-lg text-xs font-semibold">
                      รีเซ็ต
                    </button>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  {[
                    { key: 'price_weight', label: 'ความคุ้มค่าด้านราคา', color: 'text-emerald-700', bg: 'bg-emerald-100/60', accent: 'accent-emerald-600' },
                    { key: 'credit_weight', label: 'เครดิตเทอม & การเงิน', color: 'text-brand-teal', bg: 'bg-brand-teal-light', accent: 'accent-brand-teal' },
                    { key: 'delivery_weight', label: 'ความเร็วส่งมอบ (Lead Time)', color: 'text-brand-coral', bg: 'bg-brand-coral-light', accent: 'accent-brand-coral' },
                    { key: 'warranty_weight', label: 'การรับประกัน & บริการ', color: 'text-indigo-700', bg: 'bg-indigo-100/60', accent: 'accent-indigo-600' }
                  ].map(w => (
                    <div key={w.key} className="bg-slate-50 p-4 rounded-xl border border-slate-200/60">
                      <div className="flex justify-between items-center mb-2">
                        <span className="text-xs font-bold text-slate-800">{w.label}</span>
                        <span className={`text-xs font-extrabold font-mono px-2 py-0.5 rounded ${w.bg} ${w.color}`}>{weights[w.key]}%</span>
                      </div>
                      <input 
                        type="range" min="0" max="100" step="5"
                        value={weights[w.key] || 0}
                        onChange={(e) => handleUpdateWeights(w.key, e.target.value)}
                        className={`w-full h-1.5 bg-slate-200 rounded-lg appearance-none cursor-pointer ${w.accent}`}
                      />
                    </div>
                  ))}
                </div>
              </div>

              {/* Scorecard Ranking */}
              {suppliers.length === 0 ? (
                <div className="bg-white rounded-2xl p-16 text-center text-slate-400 border border-slate-200">
                  <Icon name="trophy" className="w-12 h-12 text-slate-300 mx-auto mb-2" />
                  <p className="font-semibold text-slate-600">ยังไม่มีข้อมูลสำหรับประเมินผู้ขาย</p>
                  <p className="text-xs text-slate-400 mt-1">กรุณาอัปโหลดใบเสนอราคาในแท็บแรกก่อน</p>
                </div>
              ) : (
                <div className="space-y-4">
                  <h3 className="text-base font-bold text-slate-900 flex items-center gap-2">
                    <Icon name="trophy" className="w-5 h-5 text-amber-500" />
                    <span>ผลการจัดอันดับและคะแนนประเมินรวม (Holistic Sourcing Scorecard)</span>
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                    {vendorScores.map(sc => (
                      <div key={sc.vendor_id} className={`rounded-2xl bg-white p-5 border transition-all flex flex-col justify-between ${sc.rank === 1 ? 'border-emerald-500 ring-2 ring-emerald-500/20 shadow-md' : 'border-slate-200 shadow-sm'}`}>
                        <div>
                          <div className="flex items-center gap-2 mb-2">
                            <span className={`w-6 h-6 rounded-full flex items-center justify-center font-bold text-xs ${sc.rank === 1 ? 'bg-amber-100 text-amber-800' : 'bg-slate-100 text-slate-600'}`}>
                              #{sc.rank}
                            </span>
                            <span className="text-[11px] font-semibold text-slate-400">{sc.badge}</span>
                          </div>
                          <h4 className="text-sm font-bold text-slate-900 min-h-[38px]">{sc.vendor_name}</h4>
                          <div className="my-3 flex items-baseline gap-2">
                            <span className={`text-3xl font-extrabold font-mono ${sc.rank === 1 ? 'text-emerald-600' : 'text-slate-800'}`}>{(sc.total_score || 0).toFixed(1)}</span>
                            <span className="text-xs text-slate-400 font-semibold">/ 100 คะแนน</span>
                          </div>
                          <div className="space-y-1.5 text-xs text-slate-600">
                            <div className="flex justify-between text-[11px]"><span>ราคา ({weights.price_weight}%):</span><strong className="font-mono">{sc.price_score}</strong></div>
                            <div className="flex justify-between text-[11px]"><span>เครดิต ({weights.credit_weight}%):</span><strong className="font-mono">{sc.credit_score}</strong></div>
                            <div className="flex justify-between text-[11px]"><span>ส่งมอบ ({weights.delivery_weight}%):</span><strong className="font-mono">{sc.delivery_score}</strong></div>
                            <div className="flex justify-between text-[11px]"><span>ประกัน ({weights.warranty_weight}%):</span><strong className="font-mono">{sc.warranty_score}</strong></div>
                          </div>
                        </div>
                        <div className="mt-4 pt-3 border-t border-slate-100 text-xs flex justify-between items-center text-slate-500">
                          <span>ราคาสุทธิ:</span>
                          <strong className="text-slate-800 font-mono font-bold">฿{formatMoney(sc.grand_total)}</strong>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Commercial Matrix Table */}
                  <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden mt-6">
                    <div className="p-4 border-b border-slate-100 bg-slate-50/50">
                      <h3 className="text-sm font-bold text-slate-900">ตารางเปรียบเทียบเงื่อนไขสัญญา (Commercial Terms Matrix)</h3>
                    </div>
                    <div className="overflow-x-auto">
                      <table className="w-full text-left text-xs border-collapse">
                        <thead>
                          <tr className="bg-slate-100 text-slate-700 font-bold border-b border-slate-200 divide-x divide-slate-200">
                            <th className="p-3.5 w-60">หัวข้อเงื่อนไข (Terms & Conditions)</th>
                            {suppliers.map(sup => (
                              <th key={sup.id} className="p-3.5 min-w-[200px]">{sup.vendor_name}</th>
                            ))}
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-200 text-slate-700">
                          {commercialMatrix.map(row => (
                            <tr key={row.term_key} className="hover:bg-slate-50 divide-x divide-slate-100">
                              <td className="p-3.5 font-bold text-slate-800 bg-slate-50/50">{row.term_label}</td>
                              {suppliers.map(sup => {
                                const isWin = row.highlight_winner_vendor_id === sup.id;
                                return (
                                  <td key={sup.id} className={`p-3.5 ${isWin ? 'bg-emerald-50/70 font-semibold text-emerald-900' : ''}`}>
                                    {row.supplier_values?.[sup.id] || '-'}
                                  </td>
                                );
                              })}
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* TAB 4: DEEP INSIGHTS */}
          {activeTab === 'insights' && (
            <div className="space-y-6">
              {suppliers.length === 0 ? (
                <div className="bg-white rounded-2xl p-16 text-center text-slate-400 border border-slate-200">
                  <Icon name="lightbulb" className="w-12 h-12 text-slate-300 mx-auto mb-2" />
                  <p className="font-semibold text-slate-600">ยังไม่มีข้อมูลวิเคราะห์เชิงลึก</p>
                  <p className="text-xs text-slate-400 mt-1">กรุณาอัปโหลดใบเสนอราคาในแท็บ "1. นำเข้าเอกสาร" ก่อน</p>
                </div>
              ) : (
                <div className="space-y-6">
                  {/* 3 KPI Cards */}
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                    <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm">
                      <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block mb-1">Option 1: จัดซื้อเจ้าเดียว (Single Sourcing)</span>
                      <h4 className="text-sm font-bold text-slate-900 line-clamp-1">{analysis?.pricing_strategy?.best_single_vendor || '-'}</h4>
                      <div className="text-2xl font-extrabold font-mono text-brand-navy mt-2">
                        ฿{formatMoney(analysis?.pricing_strategy?.best_single_total)}
                      </div>
                    </div>

                    <div className="bg-white rounded-2xl p-5 border border-emerald-500/50 ring-1 ring-emerald-500/20 shadow-sm">
                      <span className="text-[11px] font-bold text-emerald-600 uppercase tracking-wider block mb-1">Option 2: แยกซื้อต่ำสุด (Split Award)</span>
                      <h4 className="text-sm font-bold text-slate-900">คัดเลือกรายไอเทม (Optimal Split)</h4>
                      <div className="text-2xl font-extrabold font-mono text-emerald-600 mt-2">
                        ฿{formatMoney(analysis?.optimal_split_total)}
                      </div>
                      <div className="text-xs text-emerald-700 mt-2 font-semibold">
                        ประหยัดงบเพิ่มได้ ฿{formatMoney(analysis?.max_potential_savings)} ({(analysis?.max_potential_savings_pct || 0).toFixed(1)}%)
                      </div>
                    </div>

                    <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm">
                      <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block mb-1">ส่วนต่างราคารวมในตลาด (Market Spread)</span>
                      <h4 className="text-sm font-bold text-slate-900">ช่องว่างราคาสูงสุด vs ต่ำสุด</h4>
                      <div className="text-2xl font-extrabold font-mono text-brand-coral mt-2">
                        {(analysis?.pricing_strategy?.package_spread_pct || 0).toFixed(1)}%
                      </div>
                      <div className="text-xs text-slate-500 mt-2">
                        ส่วนต่าง ฿{formatMoney(analysis?.pricing_strategy?.package_spread_thb)}
                      </div>
                    </div>
                  </div>

                  {/* Chart */}
                  <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm">
                    <h3 className="text-sm font-bold text-slate-900 mb-1">เปรียบเทียบงบประมาณจัดซื้อรวม (Total Sourcing Cost Comparison)</h3>
                    <p className="text-xs text-slate-500 mb-4">กราฟเปรียบเทียบยอดรวมสุทธิของผู้ขายแต่ละราย vs แยกซื้อตามราคาต่ำสุด</p>
                    <div className="h-[280px] w-full">
                      <canvas ref={chartCanvasRef}></canvas>
                    </div>
                  </div>

                  {/* Playbook & Risks */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm space-y-3">
                      <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                        <Icon name="target" className="w-4 h-4 text-brand-teal" />
                        <span>กลยุทธ์การเจรจาต่อรอง (Negotiation Playbook)</span>
                      </h3>
                      {analysis?.strategic_recommendations?.map((rec, i) => (
                        <div key={i} className="p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs">
                          <p className="font-bold text-slate-800">• {rec.title}</p>
                          <p className="text-slate-600 mt-1">{rec.detail}</p>
                        </div>
                      ))}
                    </div>

                    <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm space-y-3">
                      <h3 className="text-sm font-bold text-slate-900 flex items-center gap-2">
                        <Icon name="shield-alert" className="w-4 h-4 text-rose-500" />
                        <span>การประเมินความเสี่ยง (Risk Assessment)</span>
                      </h3>
                      {analysis?.risk_assessment?.map((rk, i) => (
                        <div key={i} className="p-3 bg-slate-50 rounded-xl border border-slate-100 text-xs">
                          <p className="font-bold text-slate-800">[{rk.severity}] {rk.risk_title}</p>
                          <p className="text-slate-600 mt-1">• มาตรการ: {rk.mitigation}</p>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* TAB 5: PPTX EXPORT */}
          {activeTab === 'pptx' && (
            <div className="space-y-6">
              <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                  <h2 className="text-base sm:text-lg font-bold text-slate-900 flex items-center gap-2">
                    <Icon name="presentation" className="w-5 h-5 text-brand-coral" />
                    <span>สร้างและดาวน์โหลดสไลด์รายงานผู้บริหาร (.pptx)</span>
                  </h2>
                  <p className="text-xs text-slate-500 mt-1">
                    ออกแบบโครงสร้างสไลด์ระดับผู้บริหารตามมาตรฐาน McKinsey/BCG Bento Grid จัด Layout เรียบร้อย ตัวหนังสือไม่ล้นขอบ
                  </p>
                </div>

                <button
                  onClick={handleExportPptx}
                  disabled={suppliers.length === 0}
                  className="flex items-center gap-2 px-5 py-3 bg-gradient-to-r from-brand-navy to-brand-teal hover:from-brand-navy-light hover:to-brand-teal text-white rounded-xl text-xs font-bold shadow-md transition-all active:scale-95 disabled:opacity-50"
                >
                  <Icon name="download" className="w-4 h-4 text-amber-300" />
                  <span>ดาวน์โหลดไฟล์สไลด์ผู้บริหาร (.pptx)</span>
                </button>
              </div>

              {suppliers.length === 0 ? (
                <div className="bg-white rounded-2xl p-16 text-center text-slate-400 border border-slate-200">
                  <Icon name="presentation" className="w-12 h-12 text-slate-300 mx-auto mb-2" />
                  <p className="font-semibold text-slate-600">ยังไม่มีข้อมูลสำหรับสร้างสไลด์ผู้บริหาร</p>
                  <p className="text-xs text-slate-400 mt-1">กรุณาอัปโหลดใบเสนอราคาในแท็บแรกก่อน</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {/* Slide Navigation */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="text-xs font-bold text-slate-700">พรีวิวสไลด์:</span>
                      {[1, 2, 3, 4, 5, 6].map(num => (
                        <button
                          key={num}
                          onClick={() => setActiveSlide(num)}
                          className={`w-7 h-7 rounded-lg text-xs font-bold transition-all ${activeSlide === num ? 'bg-brand-navy text-white' : 'bg-white border border-slate-200 text-slate-600'}`}
                        >
                          {num}
                        </button>
                      ))}
                    </div>
                    <span className="text-xs font-medium text-slate-400">สไลด์ที่ {activeSlide} จาก 6 หน้า</span>
                  </div>

                  {/* Slide Preview Frame */}
                  <div className="bg-white rounded-2xl border border-slate-200 shadow-md p-6 min-h-[340px]">
                    {activeSlide === 1 && (
                      <div className="bg-brand-navy text-white rounded-xl p-8 min-h-[300px] flex flex-col justify-between">
                        <div>
                          <span className="px-3 py-1 rounded-full bg-brand-coral text-white text-[10px] font-bold">EXECUTIVE BRIEFING</span>
                          <h2 className="text-2xl font-extrabold mt-3">รายงานผลการเปรียบเทียบใบเสนอราคา & ข้อเสนอแนะเชิงกลยุทธ์</h2>
                          <p className="text-xs text-sky-200 mt-1">AI Quotation Intelligence & Strategic Sourcing Evaluation Report</p>
                        </div>
                        <div className="bg-slate-900/80 p-3 rounded-lg text-xs text-slate-300">
                          ผู้เสนอราคา: {suppliers.map(s => (s.vendor_name || '').split('(')[0]).join(', ')}
                        </div>
                      </div>
                    )}

                    {activeSlide === 2 && (
                      <div className="space-y-4">
                        <h3 className="text-base font-bold text-slate-900 border-b pb-2">Slide 2: สรุปผลการประเมินและผู้ชนะภาพรวม (Winner & Scorecard)</h3>
                        <div className="grid grid-cols-2 gap-4 text-xs">
                          <div className="bg-emerald-50 p-4 rounded-xl border border-emerald-300">
                            <span className="px-2 py-0.5 rounded bg-emerald-600 text-white font-bold text-[10px]">WINNER #1</span>
                            <h4 className="font-bold text-sm text-slate-900 mt-2">{topVendor?.vendor_name}</h4>
                            <p className="text-2xl font-bold font-mono text-emerald-700 my-1">{topVendor?.total_score || 0} คะแนน</p>
                            <p>ราคารวม: ฿{formatMoney(topVendor?.grand_total)}</p>
                          </div>
                          <div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
                            <h4 className="font-bold text-slate-800 mb-2">ตารางอันดับ</h4>
                            {vendorScores.map(s => (
                              <div key={s.rank} className="flex justify-between py-1 border-b border-slate-200 text-[11px]">
                                <span>#{s.rank} {(s.vendor_name || '').split('(')[0]}</span>
                                <strong className="font-mono">{s.total_score} คะแนน</strong>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    )}

                    {activeSlide === 3 && (
                      <div className="space-y-4">
                        <h3 className="text-base font-bold text-slate-900 border-b pb-2">Slide 3: ตารางเปรียบเทียบราคารายไอเทม (Side-by-Side Price Matrix)</h3>
                        <div className="border border-slate-200 rounded-xl overflow-x-auto text-xs">
                          <table className="w-full text-left">
                            <thead className="bg-brand-navy text-white">
                              <tr>
                                <th className="p-2">รายการสินค้า</th>
                                <th className="p-2 text-center">จำนวน</th>
                                {suppliers.map(s => <th key={s.id} className="p-2 text-right">{(s.vendor_name || '').split('(')[0]}</th>)}
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                              {priceMatrix.map(r => (
                                <tr key={r.row_no}>
                                  <td className="p-2 font-medium">{r.standard_name}</td>
                                  <td className="p-2 text-center">{r.quantity} {r.unit}</td>
                                  {suppliers.map(s => (
                                    <td key={s.id} className="p-2 text-right font-mono">฿{r.supplier_data?.[s.id]?.unit_price ? formatMoney(r.supplier_data[s.id].unit_price) : '-'}</td>
                                  ))}
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    )}

                    {activeSlide === 4 && (
                      <div className="space-y-4">
                        <h3 className="text-base font-bold text-slate-900 border-b pb-2">Slide 4: ตารางเปรียบเทียบเงื่อนไขสัญญา & บริการ (Commercial Terms)</h3>
                        <div className="grid grid-cols-3 gap-3 text-xs">
                          {suppliers.map(sup => (
                            <div key={sup.id} className="bg-slate-50 p-3 rounded-xl border border-slate-200 space-y-1">
                              <h4 className="font-bold text-brand-navy">{(sup.vendor_name || '').split('(')[0]}</h4>
                              <p>• เครดิต: {sup.commercial_terms?.credit_term_days || 30} วัน</p>
                              <p>• ส่งมอบ: {sup.commercial_terms?.delivery_lead_days || 14} วัน</p>
                              <p>• รับประกัน: {sup.commercial_terms?.warranty_months || 12} เดือน</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {activeSlide === 5 && (
                      <div className="space-y-4">
                        <h3 className="text-base font-bold text-slate-900 border-b pb-2">Slide 5: การวิเคราะห์ความคุ้มค่าและโอกาสประหยัด (Cost Savings)</h3>
                        <div className="grid grid-cols-2 gap-4 text-xs">
                          <div className="bg-slate-50 p-4 rounded-xl border border-slate-200">
                            <span className="font-bold text-slate-700">Option 1: Single Sourcing</span>
                            <p className="text-xl font-bold font-mono text-brand-navy my-1">฿{formatMoney(analysis?.pricing_strategy?.best_single_total)}</p>
                          </div>
                          <div className="bg-emerald-50 p-4 rounded-xl border border-emerald-300">
                            <span className="font-bold text-emerald-700">Option 2: Split Award (แยกซื้อต่ำสุด)</span>
                            <p className="text-xl font-bold font-mono text-emerald-700 my-1">฿{formatMoney(analysis?.optimal_split_total)}</p>
                            <p className="text-emerald-800 font-semibold">ประหยัดเพิ่มได้ ฿{formatMoney(analysis?.max_potential_savings)}</p>
                          </div>
                        </div>
                      </div>
                    )}

                    {activeSlide === 6 && (
                      <div className="space-y-4">
                        <h3 className="text-base font-bold text-slate-900 border-b pb-2">Slide 6: กลยุทธ์การเจรจาต่อรอง & การบริหารความเสี่ยง (Strategic Playbook)</h3>
                        <div className="grid grid-cols-2 gap-4 text-xs">
                          <div className="p-3 bg-slate-50 rounded-xl space-y-1">
                            <h4 className="font-bold text-brand-teal">🎯 ข้อเสนอแนะเจรจาต่อรอง</h4>
                            {analysis?.strategic_recommendations?.slice(0, 2).map((r, i) => <p key={i}>• {r.title}</p>)}
                          </div>
                          <div className="p-3 bg-slate-50 rounded-xl space-y-1">
                            <h4 className="font-bold text-rose-600">🛡️ การบริหารความเสี่ยง</h4>
                            {analysis?.risk_assessment?.slice(0, 2).map((r, i) => <p key={i}>• [{r.severity}] {r.risk_title}</p>)}
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* TAB 6: COPILOT CHAT */}
          {activeTab === 'copilot' && (
            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden flex flex-col h-[620px]">
              <div className="p-4 border-b border-slate-100 bg-slate-50 flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-brand-navy flex items-center justify-center text-white">
                    <Icon name="bot" className="w-5 h-5" />
                  </div>
                  <div>
                    <h3 className="text-sm font-bold text-slate-900">AI Procurement Copilot</h3>
                    <p className="text-[11px] text-slate-500">ตอบคำถาม ค้นหาข้อมูลตามเอกสารใบเสนอราคา (Grounded Fact 100%)</p>
                  </div>
                </div>
                <span className="px-2.5 py-1 rounded-full bg-emerald-100 text-emerald-800 text-[10px] font-bold">
                  Zero Hallucination
                </span>
              </div>

              <div className="flex-1 p-5 overflow-y-auto space-y-4 bg-slate-50/30">
                {chatMessages.map((msg, idx) => (
                  <div key={idx} className={`flex items-start gap-3 ${msg.sender === 'user' ? 'justify-end' : 'justify-start'}`}>
                    {msg.sender === 'bot' && (
                      <div className="w-8 h-8 rounded-lg bg-brand-navy flex items-center justify-center text-white shrink-0">
                        <Icon name="bot" className="w-4 h-4" />
                      </div>
                    )}
                    <div className={`max-w-[80%] rounded-2xl px-4 py-3 text-xs leading-relaxed ${
                      msg.sender === 'user' ? 'bg-brand-navy text-white rounded-tr-none' : 'bg-white border border-slate-200 text-slate-800 rounded-tl-none'
                    }`}>
                      <div className="whitespace-pre-wrap">{msg.text}</div>
                      <div className={`text-[9px] mt-1 text-right ${msg.sender === 'user' ? 'text-slate-300' : 'text-slate-400'}`}>
                        {msg.timestamp}
                      </div>
                    </div>
                  </div>
                ))}
                {chatLoading && (
                  <div className="flex items-center gap-2 text-xs text-slate-400 p-2">
                    <div className="w-3 h-3 border-2 border-brand-teal border-t-transparent rounded-full animate-spin"></div>
                    <span>กำลังค้นหาข้อเท็จจริงในใบเสนอราคา...</span>
                  </div>
                )}
                <div ref={chatEndRef} />
              </div>

              {/* Chips */}
              <div className="px-4 py-2 bg-slate-50 border-t border-slate-100 flex items-center gap-2 overflow-x-auto">
                <span className="text-[10px] font-bold text-slate-400 shrink-0">คำถามแนะนำ:</span>
                {[
                  "เจ้าไหนเสนอราคาต่ำสุดโดยรวม?",
                  "เปรียบเทียบเครดิตเทอมของแต่ละเจ้า?",
                  "ระยะเวลารับประกันของแต่ละรายเป็นอย่างไร?",
                  "ใครได้คะแนนประเมินภาพรวมอันดับ 1?"
                ].map((q, i) => (
                  <button
                    key={i}
                    onClick={() => handleSendChat(q)}
                    disabled={chatLoading}
                    className="px-2.5 py-1 bg-white hover:bg-brand-teal hover:text-white text-slate-600 text-[11px] rounded-lg border border-slate-200 shrink-0 transition-colors"
                  >
                    {q}
                  </button>
                ))}
              </div>

              {/* Input */}
              <div className="p-3 bg-white border-t border-slate-200">
                <form onSubmit={(e) => { e.preventDefault(); handleSendChat(); }} className="flex gap-2">
                  <input 
                    type="text"
                    value={chatInput}
                    onChange={(e) => setChatInput(e.target.value)}
                    placeholder="พิมพ์คำถามเกี่ยวกับใบเสนอราคา หรือเงื่อนไขสัญญา..."
                    className="flex-1 px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-xs focus:outline-none focus:ring-2 focus:ring-brand-teal/40"
                    disabled={chatLoading}
                  />
                  <button
                    type="submit"
                    disabled={!chatInput.trim() || chatLoading}
                    className="px-4 py-2.5 bg-brand-navy hover:bg-brand-navy-light text-white rounded-xl text-xs font-bold transition-all disabled:opacity-40"
                  >
                    ส่งคำถาม
                  </button>
                </form>
              </div>
            </div>
          )}

        </main>

        {/* Supplier Modal */}
        {previewSupplier && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-sm p-4">
            <div className="bg-white rounded-2xl max-w-2xl w-full p-6 shadow-2xl border border-slate-100 max-h-[90vh] overflow-y-auto">
              <div className="flex justify-between border-b pb-3 mb-4">
                <div>
                  <h3 className="text-base font-bold text-slate-900">{previewSupplier.vendor_name}</h3>
                  <p className="text-xs text-slate-400">เลขที่: {previewSupplier.quotation_number} | วันที่: {previewSupplier.quotation_date}</p>
                </div>
                <button onClick={() => setPreviewSupplier(null)} className="text-slate-400 hover:text-slate-600">✕</button>
              </div>
              <div className="space-y-4 text-xs">
                <h4 className="font-bold text-slate-700 uppercase">รายการสินค้า</h4>
                <div className="border border-slate-200 rounded-xl overflow-hidden">
                  <table className="w-full text-left">
                    <thead className="bg-slate-50 text-slate-600 font-bold border-b">
                      <tr><th className="p-2">รายการ</th><th className="p-2 text-center">จำนวน</th><th className="p-2 text-right">ราคา/หน่วย</th><th className="p-2 text-right">ราคารวม</th></tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                      {previewSupplier.items?.map((itm, i) => (
                        <tr key={i}>
                          <td className="p-2 font-medium">{itm.standard_name || itm.raw_name}</td>
                          <td className="p-2 text-center">{itm.quantity} {itm.unit}</td>
                          <td className="p-2 text-right font-mono">฿{formatMoney(itm.unit_price)}</td>
                          <td className="p-2 text-right font-mono font-bold">฿{formatMoney(itm.total_price)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div className="grid grid-cols-2 gap-3 bg-slate-50 p-3 rounded-xl">
                  <div><span className="text-slate-400 text-[11px]">เครดิตเทอม:</span><p className="font-bold">{previewSupplier.commercial_terms?.credit_term_days || 30} วัน ({previewSupplier.commercial_terms?.payment_terms || '-'})</p></div>
                  <div><span className="text-slate-400 text-[11px]">ส่งมอบ:</span><p className="font-bold">{previewSupplier.commercial_terms?.delivery_lead_days || 14} วัน</p></div>
                  <div><span className="text-slate-400 text-[11px]">การรับประกัน:</span><p className="font-bold">{previewSupplier.commercial_terms?.warranty_months || 12} เดือน</p></div>
                  <div><span className="text-slate-400 text-[11px]">ยืนราคา:</span><p className="font-bold">{previewSupplier.commercial_terms?.validity_days || 30} วัน</p></div>
                </div>
              </div>
              <div className="mt-5 flex justify-end">
                <button onClick={() => setPreviewSupplier(null)} className="px-4 py-2 bg-slate-800 text-white rounded-xl text-xs font-bold">ปิด</button>
              </div>
            </div>
          </div>
        )}

        {/* Footer */}
        <footer className="bg-white border-t border-slate-200 py-4 text-center text-xs text-slate-400">
          <div className="max-w-7xl mx-auto px-4 flex flex-col sm:flex-row items-center justify-between gap-2">
            <span>AI Quotation Intelligence System • ระบบถอดข้อมูลใบเสนอราคาและวิเคราะห์จัดซื้ออัจฉริยะ</span>
            <span className="text-[11px] text-slate-400">Zero Hallucination & Fact-Grounded Engine</span>
          </div>
        </footer>

      </div>
    </ErrorBoundary>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
