const { useState, useEffect } = React;
const { 
  Scan, History, Settings, Mail, FileSpreadsheet, 
  Sparkles, Database, Check, ShieldCheck 
} = window.lucide;

const OCRScanner = window.OCRScanner;
const ScanHistory = window.ScanHistory;
const EmailLogsPanel = window.EmailLogsPanel;
const SettingsPanel = window.SettingsPanel;

function App() {
  const [activeTab, setActiveTab] = useState('scan');
  const [records, setRecords] = useState([]);
  const [settings, setSettings] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchHistory();
    fetchSettings();
  }, []);

  const fetchHistory = async () => {
    try {
      const res = await fetch('api.php?action=history');
      if (res.ok) {
        const text = await res.text();
        try {
          const data = JSON.parse(text);
          setRecords(data);
        } catch (jsonErr) {
          console.error('Expected JSON from /api/history but got HTML/text:', text.substring(0, 100));
        }
      }
    } catch (e) {
      console.error('Failed to fetch history:', e);
    } finally {
      setLoading(false);
    }
  };

  const fetchSettings = async () => {
    try {
      const res = await fetch('api/settings');
      if (res.ok) {
        const text = await res.text();
        try {
          const data = JSON.parse(text);
          setSettings(data);
        } catch (jsonErr) {
          console.error('Expected JSON from /api/settings but got HTML/text:', text.substring(0, 100));
        }
      }
    } catch (e) {
      console.error('Failed to fetch settings:', e);
    }
  };

  const handleScanComplete = (newRecords) => {
    const recordsArray = Array.isArray(newRecords) ? newRecords : [newRecords];
    setRecords(prev => [...recordsArray, ...prev]);
    fetchHistory(); // Sync fully
  };

  const handleRecordDeleted = () => {
    fetchHistory();
  };

  const handleRecordSyncUpdated = () => {
    fetchHistory();
  };

  return (
    <div className="flex h-screen w-full bg-slate-50 font-sans text-slate-900 overflow-hidden">
      {/* Sidebar navigation on the left */}
      <aside className="w-64 bg-white border-r border-slate-200 flex flex-col shrink-0">
        <div className="p-6 border-b border-slate-200">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-blue-600 rounded flex items-center justify-center text-white font-bold shadow-sm shadow-blue-200">
              <FileSpreadsheet className="w-4.5 h-4.5" />
            </div>
            <div>
              <h1 className="font-bold text-base tracking-tight leading-none text-slate-950">SheetOCR</h1>
              <span className="text-[10px] text-slate-400 font-bold tracking-wider uppercase">eCom AI Portal</span>
            </div>
          </div>
        </div>

        {/* Navigation links */}
        <nav className="flex-1 p-4 space-y-1">
          <div className="px-3 py-2 text-[10px] font-black text-slate-400 uppercase tracking-widest">Main Menu</div>
          
          <button
            onClick={() => setActiveTab('scan')}
            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-md text-xs font-bold transition-all outline-none ${
              activeTab === 'scan'
                ? 'bg-blue-50 text-blue-700'
                : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
            }`}
          >
            <Scan className="w-4.5 h-4.5 shrink-0" />
            สแกนเอกสาร AI
          </button>

          <button
            onClick={() => setActiveTab('history')}
            className={`w-full flex items-center justify-between px-3 py-2.5 rounded-md text-xs font-bold transition-all outline-none ${
              activeTab === 'history'
                ? 'bg-blue-50 text-blue-700'
                : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
            }`}
          >
            <div className="flex items-center gap-3">
              <History className="w-4.5 h-4.5 shrink-0" />
              ประวัติการสแกน
            </div>
            {records.length > 0 && (
              <span className="bg-slate-100 text-slate-700 text-[10px] font-bold px-2 py-0.5 rounded-full border border-slate-200/50">
                {records.length}
              </span>
            )}
          </button>

          <button
            onClick={() => setActiveTab('emails')}
            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-md text-xs font-bold transition-all outline-none ${
              activeTab === 'emails'
                ? 'bg-blue-50 text-blue-700'
                : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
            }`}
          >
            <Mail className="w-4.5 h-4.5 shrink-0" />
            จดหมายแจ้งเตือน
          </button>

          <button
            onClick={() => setActiveTab('settings')}
            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-md text-xs font-bold transition-all outline-none ${
              activeTab === 'settings'
                ? 'bg-blue-50 text-blue-700'
                : 'text-slate-600 hover:bg-slate-100 hover:text-slate-900'
            }`}
          >
            <Settings className="w-4.5 h-4.5 shrink-0" />
            ตั้งค่าระบบ
          </button>
        </nav>

        {/* Bottom card containing sheets status */}
        <div className="p-4 border-t border-slate-200">
          <div className="bg-slate-900 rounded-lg p-4 text-white">
            <p className="text-[10px] text-slate-400 mb-1 font-bold uppercase tracking-wider">Google Sheets Status</p>
            <div className="flex items-center gap-2">
              <span className={`w-2 h-2 rounded-full animate-pulse ${settings?.sheetsEnabled ? 'bg-emerald-500' : 'bg-amber-400'}`}></span>
              <span className="text-xs font-bold">{settings?.sheetsEnabled ? 'เชื่อมต่อแล้ว' : 'ปิดการใช้งาน'}</span>
            </div>
          </div>
        </div>
      </aside>

      {/* Main content frame on the right */}
      <main className="flex-1 flex flex-col overflow-hidden">
        {/* Upper sticky header */}
        <header className="h-16 bg-white border-b border-slate-200 flex items-center justify-between px-8 shrink-0">
          <div className="flex items-center gap-4">
            <h2 className="text-sm font-black text-slate-900 uppercase tracking-wide">
              {activeTab === 'scan' && 'ระบบ OCR อัจฉริยะ (AI-Powered Scanner)'}
              {activeTab === 'history' && 'คลังข้อมูลประวัติออเดอร์ (Audit logs)'}
              {activeTab === 'emails' && 'จดหมายแจ้งเตือน (Notifications Outbox)'}
              {activeTab === 'settings' && 'การตั้งค่าเซิร์ฟเวอร์ (Configurations)'}
            </h2>
            <span className="bg-blue-100 text-blue-700 text-[10px] px-2.5 py-0.5 rounded-full font-black uppercase tracking-wider">
              Premium v2.4
            </span>
          </div>

          <div className="flex items-center gap-6">
            <div className="text-right hidden sm:block">
              <p className="text-[10px] text-slate-400 font-bold uppercase tracking-wider">แจ้งเตือนอีเมล</p>
              <p className="text-xs font-bold text-slate-700">{settings?.emailEnabled ? settings.targetEmail : 'ปิดใช้งาน'}</p>
            </div>
            <div className="w-8 h-8 rounded-full bg-slate-100 border border-slate-200 flex items-center justify-center text-slate-600 font-bold text-xs shadow-inner">
              TH
            </div>
          </div>
        </header>

        {/* Scrollable Main Area */}
        <div className="flex-1 overflow-y-auto p-8 max-w-7xl w-full mx-auto scrollbar-thin">
          {/* Welcome Banner Banner */}
          {activeTab === 'scan' && (
            <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6 mb-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
              <div className="space-y-1">
                <h2 className="text-lg font-black text-slate-900 flex items-center gap-2">
                  ยินดีต้อนรับสู่ระบบสแกนใบปะหน้าอัจฉริยะ 
                  <Sparkles className="w-5 h-5 text-indigo-500 fill-indigo-100" />
                </h2>
                <p className="text-xs text-slate-500 max-w-2xl leading-relaxed">
                  อัปโหลดไฟล์เอกสาร PDF หรือรูปภาพของคุณเข้าสู่ระบบเพื่อสกัดแยกรายละเอียดสินค้า ราคา และค่ายขนส่ง Lazada, Shopee และ TikTok Shop ออกมารายแถวอย่างอัจฉริยะด้วย AI อัจฉริยะของ Gemini พร้อมส่งตรงเข้า Google Sheet ทันที!
                </p>
              </div>

              <div className="flex items-center gap-2 shrink-0 bg-emerald-50 px-4 py-2 rounded-lg border border-emerald-100">
                <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span className="text-[10px] font-bold text-emerald-800 uppercase tracking-wider">AI SYSTEM ONLINE</span>
              </div>
            </div>
          )}

          {/* Sub Panels router with animation */}
          <div>
            <div className={`animate-fade-in ${activeTab === 'scan' ? 'block' : 'hidden'}`}>
              <OCRScanner onScanComplete={handleScanComplete} />
            </div>

            <div className={`animate-fade-in ${activeTab === 'history' ? 'block' : 'hidden'}`}>
              <ScanHistory 
                records={records} 
                onRecordDeleted={handleRecordDeleted}
                onRecordSyncUpdated={handleRecordSyncUpdated}
              />
            </div>

            <div className={`animate-fade-in ${activeTab === 'emails' ? 'block' : 'hidden'}`}>
              <EmailLogsPanel />
            </div>

            <div className={`animate-fade-in ${activeTab === 'settings' ? 'block' : 'hidden'}`}>
              <SettingsPanel onSettingsSaved={fetchHistory} />
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

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