/* global React, ReactDOM, Icon, Dashboard, Rooms, Parking, Customers, Reports, DocumentModal,
   TweaksPanel, useTweaks, TweakSection, TweakSlider, TweakToggle, TweakRadio, TweakSelect, TweakText, TweakColor, DB */
const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA, useRef: useRefA } = React;

const NAV = [
  { id: "dashboard", label: "แดชบอร์ด", icon: "dashboard" },
  { id: "rooms", label: "ห้องพัก", icon: "home" },
  { id: "parking", label: "ที่จอดรถ", icon: "parking" },
  { id: "customers", label: "ลูกค้า", icon: "users" },
  { id: "reports", label: "รายงาน", icon: "report" },
];

const PAGE_TITLES = {
  dashboard: { title: "แดชบอร์ด", sub: "สรุปภาพรวมห้องพักและที่จอดรถ" },
  rooms: { title: "จัดการห้องพัก", sub: "100 ห้อง · รายเดือน + รายวัน" },
  parking: { title: "จัดการที่จอดรถ", sub: "100 ช่อง · 4 โซน · รายเดือน + รายวัน" },
  customers: { title: "ลูกค้า", sub: "ลูกค้าห้องพักและที่จอดรถ" },
  reports: { title: "รายงานการเงิน", sub: "รายรับ-รายจ่าย ทุกบริการ" },
};

function App() {
  const [page, setPage] = useStateA("dashboard");
  const [doc, setDoc] = useStateA(null);
  const [t, setTweak] = useTweaks(window.__TWEAK_DEFAULTS);
  const [rooms, setRooms] = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [loadError, setLoadError] = useStateA(null);
  const defaultBrand = window.__TWEAK_DEFAULTS?.brand || "ParkingHome";
  const [thermalHeader, setThermalHeader] = useStateA([defaultBrand, "ใบเสร็จรับเงิน / RECEIPT"]);
  const [thermalFooter, setThermalFooter] = useStateA(["ขอบคุณที่ใช้บริการ", "โทร 02-123-4567"]);
  const [invoiceHeaderLines, setInvoiceHeaderLines] = useStateA(["ที่อยู่กิจการ · โทร 02-123-4567", "เลขที่ผู้เสียภาษี 0-0000-00000-00-0"]);
  const [invoiceFooterLines, setInvoiceFooterLines] = useStateA(["ขอบคุณที่ใช้บริการ"]);
  const settingsLoaded = useRefA(false);

  // โหลดข้อมูลจาก Supabase ตอนเปิดแอป
  useEffectA(() => {
    async function init() {
      try {
        const [loadedRooms, settings] = await Promise.all([
          DB.loadRooms(),
          DB.loadSettings(),
        ]);
        setRooms(loadedRooms);
        if (settings.thermal_header) setThermalHeader(settings.thermal_header);
        if (settings.thermal_footer) setThermalFooter(settings.thermal_footer);
        if (settings.invoice_header) setInvoiceHeaderLines(settings.invoice_header);
        if (settings.invoice_footer) setInvoiceFooterLines(settings.invoice_footer);
        settingsLoaded.current = true;
      } catch (err) {
        console.error("DB load error:", err);
        setLoadError(err.message || "เชื่อมต่อฐานข้อมูลไม่ได้");
      } finally {
        setLoading(false);
      }
    }
    init();
  }, []);

  // บันทึก settings อัตโนมัติเมื่อเปลี่ยน (หลังโหลดครั้งแรกแล้ว)
  useEffectA(() => {
    if (!settingsLoaded.current) return;
    DB.saveSetting("thermal_header", thermalHeader).catch(console.error);
  }, [thermalHeader]);
  useEffectA(() => {
    if (!settingsLoaded.current) return;
    DB.saveSetting("thermal_footer", thermalFooter).catch(console.error);
  }, [thermalFooter]);
  useEffectA(() => {
    if (!settingsLoaded.current) return;
    DB.saveSetting("invoice_header", invoiceHeaderLines).catch(console.error);
  }, [invoiceHeaderLines]);
  useEffectA(() => {
    if (!settingsLoaded.current) return;
    DB.saveSetting("invoice_footer", invoiceFooterLines).catch(console.error);
  }, [invoiceFooterLines]);

  // apply tweaks to CSS vars + theme
  useEffectA(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
    document.documentElement.style.setProperty("--font-scale", String(t.fontScale));
    document.documentElement.dataset.theme = t.theme;
    document.documentElement.dataset.warmth = t.warmth;
    document.documentElement.dataset.density = t.density;
  }, [t.accent, t.theme, t.fontScale, t.warmth, t.density]);

  const pt = PAGE_TITLES[page];

  const overdueCount = useMemoA(() => {
    return rooms.filter(r => r.status === "overdue").length
      + window.DATA.parking.filter(p => p.status === "overdue").length;
  }, [rooms]);

  const openInvoice = (room) => setDoc({ kind: "invoice", data: room });
  const openReceipt = (data) => setDoc({ kind: "receipt", data });

  if (loading) return (
    <div style={{ display: "grid", placeItems: "center", height: "100vh", gap: 16 }}>
      <div style={{ textAlign: "center" }}>
        <div style={{ fontSize: "2rem", marginBottom: 12 }}>⏳</div>
        <div style={{ fontWeight: 600, fontSize: "1.1rem" }}>กำลังโหลดข้อมูล...</div>
        <div style={{ color: "var(--ink-3)", marginTop: 6, fontSize: "0.9rem" }}>กำลังเชื่อมต่อฐานข้อมูล</div>
      </div>
    </div>
  );

  if (loadError) return (
    <div style={{ display: "grid", placeItems: "center", height: "100vh", gap: 16 }}>
      <div style={{ textAlign: "center", maxWidth: 420 }}>
        <div style={{ fontSize: "2rem", marginBottom: 12 }}>❌</div>
        <div style={{ fontWeight: 600, fontSize: "1.1rem", color: "var(--danger)" }}>เชื่อมต่อฐานข้อมูลไม่ได้</div>
        <div style={{ color: "var(--ink-3)", marginTop: 8, fontSize: "0.9rem", lineHeight: 1.6 }}>{loadError}</div>
        <div style={{ marginTop: 14, padding: "10px 14px", background: "var(--surface-2)", borderRadius: 10, fontSize: "0.85rem", textAlign: "left" }}>
          <b>แก้ไข:</b> เปิดไฟล์ <code>config.js</code> แล้วใส่ค่า SUPABASE_URL และ SUPABASE_ANON_KEY ที่ถูกต้อง
        </div>
        <button className="btn primary" style={{ marginTop: 14 }} onClick={() => window.location.reload()}>ลองใหม่</button>
      </div>
    </div>
  );

  return (
    <div className="app">
      <aside className="sidebar">
        <div className="brand">
          <div className="logo">{t.brand[0]}</div>
          <div>
            <div className="name">{t.brand}</div>
            <div className="sub">{t.tagline}</div>
          </div>
        </div>
        <div className="nav-section">เมนูหลัก</div>
        {NAV.map(n => (
          <a key={n.id} className={"nav-item " + (page === n.id ? "active" : "")} onClick={(e) => { e.preventDefault(); setPage(n.id); }} href={"#" + n.id}>
            <Icon name={n.icon}/>
            <span className="label">{n.label}</span>
            {n.id === "rooms" && overdueCount > 0 && <span className="badge">{overdueCount}</span>}
          </a>
        ))}
        <div style={{ flex: 1 }}/>
        <div className="nav-section">บัญชีผู้ใช้</div>
        <div className="nav-item">
          <div style={{ width: 28, height: 28, borderRadius: "50%", background: "var(--accent)", color: "#fff", display: "grid", placeItems: "center", fontWeight: 600, fontSize: "0.85rem" }}>คม</div>
          <div>
            <div style={{ fontSize: "0.88rem", fontWeight: 600 }}>คุณมานพ</div>
            <div style={{ fontSize: "0.75rem", color: "var(--ink-3)" }}>ผู้ดูแลระบบ</div>
          </div>
        </div>
      </aside>

      <main className="main">
        <div className="topbar">
          <div>
            <h1>{pt.title}</h1>
            <div className="sub">{pt.sub}</div>
          </div>
          <div className="spacer"/>
          <div className="search no-print">
            <Icon name="search" size={16}/>
            <input placeholder="ค้นหาห้อง · ลูกค้า · ทะเบียน..."/>
          </div>
          <button className="iconbtn" title="แจ้งเตือน" onClick={() => setPage("dashboard")}>
            <Icon name="bell"/>
            {overdueCount > 0 && <span style={{ position: "absolute", marginTop: -22, marginLeft: 14, background: "var(--danger)", color: "white", borderRadius: 999, fontSize: "0.65rem", padding: "1px 5px", fontWeight: 600 }}>{overdueCount}</span>}
          </button>
          <button className="iconbtn" title="โหมดมืด" onClick={() => setTweak("theme", t.theme === "light" ? "dark" : "light")}>
            <Icon name={t.theme === "light" ? "moon" : "sun"}/>
          </button>
        </div>

        <div className="content" key={page}>
          {page === "dashboard" && <Dashboard goto={setPage}/>}
          {page === "rooms" && <Rooms rooms={rooms} setRooms={setRooms} onOpenInvoice={openInvoice} onOpenReceipt={openReceipt}/>}
          {page === "parking" && <Parking onOpenReceipt={openReceipt}/>}
          {page === "customers" && <Customers rooms={rooms}/>}
          {page === "reports" && <Reports/>}
        </div>
      </main>

      <DocumentModal doc={doc} onClose={() => setDoc(null)}
        thermalHeader={thermalHeader} setThermalHeader={setThermalHeader}
        thermalFooter={thermalFooter} setThermalFooter={setThermalFooter}
        invoiceHeaderLines={invoiceHeaderLines} setInvoiceHeaderLines={setInvoiceHeaderLines}
        invoiceFooterLines={invoiceFooterLines} setInvoiceFooterLines={setInvoiceFooterLines}/>

      <TweaksPanel title="Tweaks">
        <TweakSection title="แบรนด์">
          <TweakText label="ชื่อโครงการ" value={t.brand} onChange={(v) => setTweak("brand", v)} />
          <TweakText label="คำโปรย" value={t.tagline} onChange={(v) => setTweak("tagline", v)} />
        </TweakSection>
        <TweakSection title="ธีมและสี">
          <TweakColor
            label="สีหลัก"
            value={t.accent}
            options={["#2563eb", "#0ea5a4", "#ea580c", "#7c3aed", "#16804a", "#be123c", "#0f172a"]}
            onChange={(v) => setTweak("accent", v)}
          />
          <TweakRadio
            label="โหมด"
            value={t.theme}
            options={[{ value: "light", label: "สว่าง" }, { value: "dark", label: "มืด" }]}
            onChange={(v) => setTweak("theme", v)}
          />
          <TweakRadio
            label="โทน"
            value={t.warmth}
            options={[{ value: "warm", label: "อบอุ่น" }, { value: "neutral", label: "เป็นกลาง" }]}
            onChange={(v) => setTweak("warmth", v)}
          />
        </TweakSection>
        <TweakSection title="ความหนาแน่นข้อมูล">
          <TweakRadio
            label="ระยะห่าง"
            value={t.density}
            options={[{ value: "comfortable", label: "ปกติ" }, { value: "compact", label: "แน่น" }]}
            onChange={(v) => setTweak("density", v)}
          />
          <TweakSlider
            label="ขนาดตัวอักษร"
            value={t.fontScale} min={0.85} max={1.2} step={0.05}
            onChange={(v) => setTweak("fontScale", v)}
            format={(v) => `${Math.round(v * 100)}%`}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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