/* global React, Icon, Modal, Pill, StatusPill, Field, formatBaht, formatDateTH, DATA, DB */
const { useState: useStateR, useMemo: useMemoR } = React;

function Rooms({ rooms, setRooms, onOpenInvoice, onOpenReceipt }) {
  const [tab, setTab] = useStateR("all");
  const [view, setView] = useStateR("floor");
  const [query, setQuery] = useStateR("");
  const [active, setActive] = useStateR(null); // selected room for detail
  const [adding, setAdding] = useStateR(false);
  const [newRoom, setNewRoom] = useStateR({ no: "", floor: "", type: "monthly", size: "ห้องมาตรฐาน 22 ตร.ม.", rent: "", waterRate: "25", electricRate: "8", deposit: "" });
  const [meterFor, setMeterFor] = useStateR(null);
  const [editPriceFor, setEditPriceFor] = useStateR(null);
  const [promo, setPromo] = useStateR(false);

  const filtered = useMemoR(() => {
    return rooms.filter(r => {
      if (tab === "monthly" && r.type !== "monthly") return false;
      if (tab === "daily" && r.type !== "daily") return false;
      if (tab === "vacant" && r.status !== "vacant") return false;
      if (tab === "overdue" && r.status !== "overdue") return false;
      if (query && !(r.no.includes(query) || (r.customer && r.customer.name.includes(query)))) return false;
      return true;
    });
  }, [rooms, tab, query]);

  const byFloor = useMemoR(() => {
    const out = {};
    filtered.forEach(r => { (out[r.floor] = out[r.floor] || []).push(r); });
    Object.keys(out).forEach(f => {
      out[f].sort((a, b) => a.no.localeCompare(b.no, undefined, { numeric: true, sensitivity: "base" }));
    });
    return out;
  }, [filtered]);

  const counts = useMemoR(() => ({
    all: rooms.length,
    monthly: rooms.filter(r => r.type === "monthly").length,
    daily: rooms.filter(r => r.type === "daily").length,
    vacant: rooms.filter(r => r.status === "vacant").length,
    overdue: rooms.filter(r => r.status === "overdue").length,
  }), [rooms]);

  const updateRoom = (no, patch) => {
    // optimistic UI update
    setRooms(rs => rs.map(r => r.no === no ? { ...r, ...patch } : r));
    if (active && active.no === no) setActive(a => ({ ...a, ...patch }));
    // persist to DB — detect check-in vs regular update
    const currentRoom = rooms.find(r => r.no === no);
    if (patch.customer && !currentRoom?.customer) {
      // new check-in: update room status + create customer + tenant
      DB.updateRoom(no, { status: patch.status }).catch(console.error);
      DB.checkIn(no, patch.customer).catch(console.error);
    } else {
      DB.updateRoom(no, patch).catch(console.error);
    }
  };

  const deleteRoom = (no) => {
    if (!confirm(`ต้องการลบห้อง ${no}?`)) return;
    setRooms(rs => rs.filter(r => r.no !== no));
    setActive(null);
    DB.deleteRoom(no).catch(console.error);
  };

  const saveNewRoom = () => {
    const { no, floor, type, size, rent, waterRate, electricRate } = newRoom;
    if (!no.trim()) { alert("กรุณากรอกเลขห้อง"); return; }
    if (!floor.trim()) { alert("กรุณากรอกชั้น"); return; }
    if (!rent.trim()) { alert("กรุณากรอกค่าเช่า"); return; }
    if (rooms.some(r => r.no === no.trim())) { alert(`ห้อง ${no.trim()} มีอยู่แล้ว`); return; }
    const floorNum = parseInt(floor) || 1;
    const rentNum = parseFloat(rent) || 0;
    const room = {
      no: no.trim(), floor: floorNum, type, size: size || "ห้องมาตรฐาน 22 ตร.ม.",
      rent: rentNum, status: "vacant", customer: null,
      waterRate: parseFloat(waterRate) || 25,
      electricRate: parseFloat(electricRate) || 8,
      extras: [],
      prevMeter: { water: 0, electric: 0 },
      currMeter: { water: 0, electric: 0 },
    };
    setRooms(rs => [...rs, room].sort((a, b) => a.no.localeCompare(b.no, undefined, { numeric: true })));
    setNewRoom({ no: "", floor: "", type: "monthly", size: "ห้องมาตรฐาน 22 ตร.ม.", rent: "", waterRate: "25", electricRate: "8", deposit: "" });
    setAdding(false);
    DB.addRoom(room).catch(console.error);
  };

  return (
    <div className="grid" style={{ gap: 18 }}>
      <div className="row" style={{ flexWrap: "wrap", gap: 12 }}>
        <div className="tabs">
          <button className={"tab " + (tab === "all" ? "active" : "")} onClick={() => setTab("all")}>ทั้งหมด <span style={{opacity:0.6, marginLeft: 4}}>{counts.all}</span></button>
          <button className={"tab " + (tab === "monthly" ? "active" : "")} onClick={() => setTab("monthly")}>รายเดือน <span style={{opacity:0.6, marginLeft: 4}}>{counts.monthly}</span></button>
          <button className={"tab " + (tab === "daily" ? "active" : "")} onClick={() => setTab("daily")}>รายวัน <span style={{opacity:0.6, marginLeft: 4}}>{counts.daily}</span></button>
          <button className={"tab " + (tab === "vacant" ? "active" : "")} onClick={() => setTab("vacant")}>ว่าง <span style={{opacity:0.6, marginLeft: 4}}>{counts.vacant}</span></button>
          <button className={"tab " + (tab === "overdue" ? "active" : "")} onClick={() => setTab("overdue")}>ค้างชำระ <span style={{opacity:0.6, marginLeft: 4}}>{counts.overdue}</span></button>
        </div>
        <div className="topbar-search" style={{ position: "relative" }}>
          <input className="input" style={{ width: 240, paddingLeft: 36 }} placeholder="ค้นหาเลขห้อง / ชื่อผู้เช่า" value={query} onChange={e => setQuery(e.target.value)} />
          <Icon name="search" style={{ position: "absolute", left: 10, top: 10, color: "var(--ink-3)" }} />
        </div>
        <div className="spacer" style={{ flex: 1 }} />
        <div className="tabs">
          <button className={"tab " + (view === "floor" ? "active" : "")} onClick={() => setView("floor")}>ผังห้อง</button>
          <button className={"tab " + (view === "list" ? "active" : "")} onClick={() => setView("list")}>ตาราง</button>
        </div>
        <button className="btn" onClick={() => setPromo(true)}><Icon name="tag" size={16}/> โปรโมชั่น</button>
        <button className="btn primary" onClick={() => setAdding(true)}><Icon name="plus" size={16}/> เพิ่มห้อง</button>
      </div>

      <div className="card">
        <div className="card-head">
          <h3>ผังห้องพัก</h3>
          <div className="spacer" />
          <div className="legend">
            <span className="item"><span className="swatch" style={{ background: "var(--ok-soft)", borderColor: "var(--ok)" }}/> มีผู้เช่า</span>
            <span className="item"><span className="swatch" style={{ background: "var(--info-soft)", borderColor: "var(--accent)" }}/> รายวัน</span>
            <span className="item"><span className="swatch" style={{ background: "var(--surface)" }}/> ว่าง</span>
            <span className="item"><span className="swatch" style={{ background: "var(--danger-soft)", borderColor: "var(--danger)" }}/> ค้างชำระ</span>
            <span className="item"><span className="swatch" style={{ background: "var(--warn-soft)", borderColor: "var(--warn)" }}/> ทำความสะอาด</span>
          </div>
        </div>

        {view === "floor" ? (
          <div className="grid" style={{ gap: 22 }}>
            {Object.keys(byFloor).sort().map(f => (
              <div key={f}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                  <div style={{ fontWeight: 600 }}>ชั้น {f}</div>
                  <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
                  <span className="pill">{byFloor[f].length} ห้อง</span>
                </div>
                <div className="floor">
                  {byFloor[f].map(r => (
                    <button className="room-cell" data-status={r.status} key={r.no} onClick={() => setActive(r)}>
                      <span className="status-dot" />
                      <span className="floor-tag">{r.type === "monthly" ? "รายเดือน" : "รายวัน"}</span>
                      <span className="no">{r.no}</span>
                      <span className="who">{r.customer ? r.customer.name : "ห้องว่าง"}</span>
                    </button>
                  ))}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="table-wrap" style={{ border: "1px solid var(--line)" }}>
            <table className="table">
              <thead><tr>
                <th>ห้อง</th><th>ประเภท</th><th>สถานะ</th><th>ผู้เช่า</th><th>โทรศัพท์</th><th className="num">ค่าเช่า</th><th></th>
              </tr></thead>
              <tbody>
                {filtered.map(r => (
                  <tr key={r.no} onClick={() => setActive(r)} style={{ cursor: "pointer" }}>
                    <td><strong>{r.no}</strong> <span style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>· ชั้น {r.floor}</span></td>
                    <td>{r.type === "monthly" ? "รายเดือน" : "รายวัน"}</td>
                    <td><StatusPill status={r.status}/></td>
                    <td>{r.customer ? r.customer.name : "—"}</td>
                    <td>{r.customer ? r.customer.phone : "—"}</td>
                    <td className="num">{formatBaht(r.rent)}{r.type === "daily" && "/คืน"}</td>
                    <td><Icon name="more"/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Room detail modal */}
      <Modal open={!!active} onClose={() => setActive(null)} size="xl"
             title={active ? `ห้อง ${active.no} · ชั้น ${active.floor} · ${active.type === "monthly" ? "รายเดือน" : "รายวัน"}` : ""}>
        {active && (
          <RoomDetail room={active}
                      onUpdate={(p) => updateRoom(active.no, p)}
                      onDelete={() => deleteRoom(active.no)}
                      onMeter={() => setMeterFor(active)}
                      onEditPrice={() => setEditPriceFor(active)}
                      onInvoice={() => onOpenInvoice(active)}
                      onReceipt={() => onOpenReceipt(active)} />
        )}
      </Modal>

      {/* Add room modal */}
      <Modal open={adding} onClose={() => setAdding(false)} title="เพิ่มห้องพักใหม่"
             footer={<>
               <button className="btn" onClick={() => setAdding(false)}>ยกเลิก</button>
               <button className="btn primary" onClick={saveNewRoom}><Icon name="check" size={16}/> บันทึก</button>
             </>}>
        <div className="grid cols-2" style={{ gap: 14 }}>
          <Field label="เลขห้อง"><input className="input" placeholder="เช่น 601" value={newRoom.no} onChange={e => setNewRoom(r => ({ ...r, no: e.target.value }))}/></Field>
          <Field label="ชั้น"><input className="input" placeholder="6" value={newRoom.floor} onChange={e => setNewRoom(r => ({ ...r, floor: e.target.value }))}/></Field>
          <Field label="ประเภท">
            <select className="select" value={newRoom.type} onChange={e => setNewRoom(r => ({ ...r, type: e.target.value }))}>
              <option value="monthly">รายเดือน</option>
              <option value="daily">รายวัน</option>
            </select>
          </Field>
          <Field label="ขนาด"><input className="input" value={newRoom.size} onChange={e => setNewRoom(r => ({ ...r, size: e.target.value }))}/></Field>
          <Field label="ค่าเช่า (บาท)"><input className="input num" placeholder="4500" value={newRoom.rent} onChange={e => setNewRoom(r => ({ ...r, rent: e.target.value }))}/></Field>
          <Field label="ค่าน้ำต่อหน่วย"><input className="input num" value={newRoom.waterRate} onChange={e => setNewRoom(r => ({ ...r, waterRate: e.target.value }))}/></Field>
          <Field label="ค่าไฟต่อหน่วย"><input className="input num" value={newRoom.electricRate} onChange={e => setNewRoom(r => ({ ...r, electricRate: e.target.value }))}/></Field>
          <Field label="ค่ามัดจำ (รายเดือน)"><input className="input num" placeholder="9000" value={newRoom.deposit} onChange={e => setNewRoom(r => ({ ...r, deposit: e.target.value }))}/></Field>
        </div>
      </Modal>

      {/* Meter modal */}
      <Modal open={!!meterFor} onClose={() => setMeterFor(null)} size="lg"
             title={meterFor ? `จดมิเตอร์ — ห้อง ${meterFor.no}` : ""}>
        {meterFor && (
          <MeterModal
            room={meterFor}
            onSave={(patch, printInvoice) => { updateRoom(meterFor.no, patch); setMeterFor(null); if (printInvoice) onOpenInvoice({ ...meterFor, ...patch }); }}
            onCancel={() => setMeterFor(null)}
          />
        )}
      </Modal>

      {/* Edit Price */}
      <Modal open={!!editPriceFor} onClose={() => setEditPriceFor(null)}
             title={editPriceFor ? `ตั้งค่าราคาห้อง ${editPriceFor.no}` : ""}>
        {editPriceFor && (
          <EditPriceModal
            room={editPriceFor}
            onSave={(patch) => { updateRoom(editPriceFor.no, patch); setEditPriceFor(null); }}
            onCancel={() => setEditPriceFor(null)}
          />
        )}
      </Modal>

      {/* Promotions */}
      <Modal open={promo} onClose={() => setPromo(false)} size="lg" title="โปรโมชั่นห้องพักรายวัน">
        <div className="grid" style={{ gap: 10 }}>
          {DATA.promotions.filter(p => p.type === "daily-week").map(p => (
            <div key={p.id} className="card" style={{ padding: 14 }}>
              <div className="row" style={{ alignItems: "flex-start" }}>
                <div style={{ flex: 1 }}>
                  <div className="row" style={{ gap: 8 }}>
                    <strong>{p.name}</strong>
                    <Pill tone="info">−{p.value}%</Pill>
                  </div>
                  <div style={{ color: "var(--ink-3)", marginTop: 4 }}>{p.desc}</div>
                </div>
                <button className="btn sm"><Icon name="edit" size={14}/></button>
                <button className="btn ghost sm"><Icon name="trash" size={14}/></button>
              </div>
            </div>
          ))}
          <button className="btn"><Icon name="plus" size={16}/> เพิ่มโปรโมชั่น</button>
        </div>
      </Modal>
    </div>
  );
}

function RoomDetail({ room, onUpdate, onDelete, onMeter, onEditPrice, onInvoice, onReceipt }) {
  const [editCust, setEditCust] = useStateR(false);
  const [checkIn, setCheckIn] = useStateR(false);
  const usedWater = (room.currMeter?.water || 0) - (room.prevMeter?.water || 0);
  const usedElec = (room.currMeter?.electric || 0) - (room.prevMeter?.electric || 0);
  const waterCost = usedWater * room.waterRate;
  const elecCost = usedElec * room.electricRate;
  const extraSum = (room.extras || []).reduce((s, x) => s + Number(x.amount || 0), 0);
  const total = room.rent + waterCost + elecCost + extraSum;

  return (
    <div className="grid" style={{ gap: 18, gridTemplateColumns: "1fr 320px" }}>
      <div className="grid" style={{ gap: 14 }}>
        <div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
          <StatusPill status={room.status}/>
          <Pill>{room.size}</Pill>
          <Pill>{room.type === "monthly" ? `${formatBaht(room.rent)} / เดือน` : `${formatBaht(room.rent)} / คืน`}</Pill>
        </div>

        {room.customer ? (
          <div className="card" style={{ background: "var(--surface-2)" }}>
            <div className="card-head"><h3>ข้อมูลผู้เช่า</h3><div className="spacer"/>
              <button className="btn sm" onClick={() => setEditCust(true)}><Icon name="edit" size={14}/> แก้ไข</button>
            </div>
            <div className="grid cols-2" style={{ gap: 10 }}>
              <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>ชื่อ</div><div style={{ fontWeight: 600 }}>{room.customer.name}</div></div>
              <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>โทรศัพท์</div><div className="num">{room.customer.phone}</div></div>
              <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>เข้าพักตั้งแต่</div><div>{formatDateTH(room.customer.since)}</div></div>
              {room.customer.checkoutPlan && <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>กำหนดออก</div><div>{formatDateTH(room.customer.checkoutPlan)}</div></div>}
              {room.customer.deposit > 0 && <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>เงินมัดจำ</div><div className="num">{formatBaht(room.customer.deposit)}</div></div>}
              <div><div style={{ color: "var(--ink-3)", fontSize: "0.8rem" }}>รหัสลูกค้า</div><div className="num">{room.customer.id}</div></div>
            </div>
          </div>
        ) : (
          <div className="card" style={{ borderStyle: "dashed", textAlign: "center", padding: 30 }}>
            <div style={{ color: "var(--ink-3)" }}>ห้องนี้ว่าง · พร้อมเข้าพัก</div>
            <button className="btn primary" style={{ marginTop: 12 }} onClick={() => setCheckIn(true)}><Icon name="plus" size={16}/> เช็คอินผู้เช่า</button>
          </div>
        )}

        {room.type === "monthly" && (
          <div className="card">
            <div className="card-head">
              <h3>มิเตอร์เดือนนี้</h3>
              <div className="spacer"/>
              <button className="btn sm primary" onClick={onMeter}><Icon name="camera" size={14}/> จดมิเตอร์</button>
            </div>
            <div className="grid cols-2" style={{ gap: 14 }}>
              <div style={{ padding: 12, background: "var(--info-soft)", borderRadius: 10 }}>
                <div className="row"><Icon name="drop" size={16}/><span style={{ fontWeight: 600 }}>น้ำประปา</span></div>
                <div className="num" style={{ fontSize: "1.4rem", fontWeight: 600, marginTop: 8 }}>{usedWater} หน่วย</div>
                <div style={{ color: "var(--ink-3)", fontSize: "0.85rem" }}>{room.prevMeter.water} → {room.currMeter.water} · {formatBaht(waterCost)}</div>
              </div>
              <div style={{ padding: 12, background: "var(--warn-soft)", borderRadius: 10 }}>
                <div className="row"><Icon name="bolt" size={16}/><span style={{ fontWeight: 600 }}>ไฟฟ้า</span></div>
                <div className="num" style={{ fontSize: "1.4rem", fontWeight: 600, marginTop: 8 }}>{usedElec} หน่วย</div>
                <div style={{ color: "var(--ink-3)", fontSize: "0.85rem" }}>{room.prevMeter.electric} → {room.currMeter.electric} · {formatBaht(elecCost)}</div>
              </div>
            </div>
            <div style={{ marginTop: 14, padding: 12, borderTop: "1px dashed var(--line)" }}>
              <div className="row" style={{ justifyContent: "space-between" }}>
                <span>ค่าเช่าห้อง</span><span className="num" style={{ fontWeight: 600 }}>{formatBaht(room.rent)}</span>
              </div>
              <div className="row" style={{ justifyContent: "space-between", marginTop: 4 }}>
                <span>ค่าน้ำ + ไฟ</span><span className="num">{formatBaht(waterCost + elecCost)}</span>
              </div>
              {(room.extras || []).map((x, i) => (
                <div key={i} className="row" style={{ justifyContent: "space-between", marginTop: 4 }}>
                  <span>{x.name || "ค่าใช้จ่ายอื่นๆ"}</span><span className="num">{formatBaht(x.amount)}</span>
                </div>
              ))}
              <div className="row" style={{ justifyContent: "space-between", marginTop: 8, paddingTop: 8, borderTop: "1px solid var(--line)" }}>
                <strong>รวมที่ต้องชำระ</strong><strong className="num" style={{ color: "var(--accent)" }}>{formatBaht(total)}</strong>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="grid" style={{ gap: 12, alignContent: "start" }}>
        <button className="btn primary lg" onClick={room.type === "monthly" ? onInvoice : onReceipt}>
          <Icon name="printer" size={16}/> {room.type === "monthly" ? "พิมพ์ใบแจ้งหนี้" : "พิมพ์ใบเสร็จ"}
        </button>
        <button className="btn" onClick={onEditPrice}><Icon name="money" size={16}/> ตั้งค่าราคา/ค่าใช้จ่าย</button>
        <button className="btn"><Icon name="qr" size={16}/> สร้าง QR ชำระเงิน</button>
        <button className="btn"><Icon name="phone" size={16}/> ติดต่อผู้เช่า</button>
        <div style={{ height: 8 }} />
        <button className="btn danger" onClick={onDelete}><Icon name="trash" size={16}/> ลบห้อง</button>
      </div>

      {/* Edit customer modal */}
      <Modal open={editCust} onClose={() => setEditCust(false)} title="แก้ไขข้อมูลผู้เช่า">
        {editCust && room.customer && (
          <EditCustomerModal
            customer={room.customer}
            onSave={(c) => { onUpdate({ customer: c }); setEditCust(false); }}
            onCancel={() => setEditCust(false)}
          />
        )}
      </Modal>

      {/* Check-in modal */}
      <Modal open={checkIn} onClose={() => setCheckIn(false)} title={`เช็คอินผู้เช่า — ห้อง ${room.no}`}>
        {checkIn && (
          <CheckInModal
            room={room}
            onSave={(patch) => { onUpdate(patch); setCheckIn(false); }}
            onCancel={() => setCheckIn(false)}
          />
        )}
      </Modal>
    </div>
  );
}

function CheckInModal({ room, onSave, onCancel }) {
  const today = new Date().toISOString().slice(0, 10);
  const [name, setName] = useStateR("");
  const [phone, setPhone] = useStateR("");
  const [since, setSince] = useStateR(today);
  const [deposit, setDeposit] = useStateR(room.type === "monthly" ? String(room.rent * 2) : "0");
  const [checkoutPlan, setCheckoutPlan] = useStateR("");
  const [idCard, setIdCard] = useStateR("");

  const save = () => {
    if (!name.trim()) { alert("กรุณากรอกชื่อ-นามสกุล"); return; }
    if (!phone.trim()) { alert("กรุณากรอกเบอร์โทรศัพท์"); return; }
    if (!since) { alert("กรุณาเลือกวันที่เข้าพัก"); return; }
    const newId = `C${Date.now().toString().slice(-6)}`;
    const customer = {
      id: newId,
      name: name.trim(),
      phone: phone.trim(),
      since,
      deposit: parseFloat(deposit) || 0,
      checkoutPlan: checkoutPlan || null,
      idCard: idCard.trim() || null,
    };
    const newStatus = room.type === "daily" ? "daily" : "occupied";
    onSave({ customer, status: newStatus });
  };

  return (
    <div className="grid" style={{ gap: 14 }}>
      <div className="grid cols-2" style={{ gap: 14 }}>
        <Field label="ชื่อ-นามสกุล *">
          <input className="input" placeholder="สมชาย ใจดี" value={name} onChange={e => setName(e.target.value)} autoFocus/>
        </Field>
        <Field label="โทรศัพท์ *">
          <input className="input num" placeholder="08x-xxx-xxxx" value={phone} onChange={e => setPhone(e.target.value)}/>
        </Field>
        <Field label="วันที่เข้าพัก *">
          <input className="input" type="date" value={since} onChange={e => setSince(e.target.value)}/>
        </Field>
        <Field label="เลขบัตรประชาชน">
          <input className="input num" placeholder="x-xxxx-xxxxx-xx-x" value={idCard} onChange={e => setIdCard(e.target.value)}/>
        </Field>
        <Field label="เงินมัดจำ (บาท)">
          <input className="input num" value={deposit} onChange={e => setDeposit(e.target.value)}/>
        </Field>
        {room.type === "daily" && (
          <Field label="กำหนดออก">
            <input className="input" type="date" value={checkoutPlan} onChange={e => setCheckoutPlan(e.target.value)}/>
          </Field>
        )}
      </div>
      <div style={{ padding: "10px 14px", background: "var(--surface-2)", borderRadius: 10, fontSize: "0.88rem", color: "var(--ink-2)" }}>
        ห้อง {room.no} · {room.type === "monthly" ? "รายเดือน" : "รายวัน"} · {formatBaht(room.rent)}{room.type === "daily" ? "/คืน" : "/เดือน"}
      </div>
      <div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
        <button className="btn" onClick={onCancel}>ยกเลิก</button>
        <button className="btn primary" onClick={save}><Icon name="check" size={16}/> เช็คอิน</button>
      </div>
    </div>
  );
}

function EditCustomerModal({ customer, onSave, onCancel }) {
  const [name, setName] = useStateR(customer.name || "");
  const [phone, setPhone] = useStateR(customer.phone || "");
  const [since, setSince] = useStateR(customer.since || "");
  const [deposit, setDeposit] = useStateR(customer.deposit || 0);
  const [checkoutPlan, setCheckoutPlan] = useStateR(customer.checkoutPlan || "");

  return (
    <div className="grid" style={{ gap: 14 }}>
      <div className="grid cols-2" style={{ gap: 14 }}>
        <Field label="ชื่อ-นามสกุล">
          <input className="input" value={name} onChange={e => setName(e.target.value)}/>
        </Field>
        <Field label="โทรศัพท์">
          <input className="input num" value={phone} onChange={e => setPhone(e.target.value)}/>
        </Field>
        <Field label="วันที่เข้าพัก">
          <input className="input" type="date" value={since} onChange={e => setSince(e.target.value)}/>
        </Field>
        <Field label="เงินมัดจำ (บาท)">
          <input className="input num" value={deposit} onChange={e => setDeposit(+e.target.value)}/>
        </Field>
        <Field label="กำหนดออก (ถ้ามี)">
          <input className="input" type="date" value={checkoutPlan} onChange={e => setCheckoutPlan(e.target.value)}/>
        </Field>
        <Field label="รหัสลูกค้า">
          <input className="input" value={customer.id} readOnly style={{ opacity: 0.6 }}/>
        </Field>
      </div>
      <div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
        <button className="btn" onClick={onCancel}>ยกเลิก</button>
        <button className="btn primary" onClick={() => onSave({ ...customer, name, phone, since, deposit, checkoutPlan: checkoutPlan || null })}>
          <Icon name="check" size={16}/> บันทึก
        </button>
      </div>
    </div>
  );
}

function MeterModal({ room, onSave, onCancel }) {
  const [w, setW] = useStateR(room.currMeter.water);
  const [e, setE] = useStateR(room.currMeter.electric);
  const [waterPhoto, setWaterPhoto] = useStateR(false);
  const [elecPhoto, setElecPhoto] = useStateR(false);
  const [extras, setExtras] = useStateR(room.extras && room.extras.length ? room.extras : []);

  const usedW = w - room.prevMeter.water;
  const usedE = e - room.prevMeter.electric;
  const wCost = usedW * room.waterRate;
  const eCost = usedE * room.electricRate;
  const extraSum = extras.reduce((s,x) => s + Number(x.amount || 0), 0);
  const total = room.rent + wCost + eCost + extraSum;

  return (
    <div className="grid" style={{ gap: 16 }}>
      <div className="grid cols-2" style={{ gap: 14 }}>
        <div className="card" style={{ padding: 14 }}>
          <div className="row" style={{ marginBottom: 8 }}><Icon name="drop" size={18}/><strong>น้ำประปา</strong></div>
          <div className="grid cols-2" style={{ gap: 8 }}>
            <Field label="ครั้งก่อน"><input className="input num" value={room.prevMeter.water} readOnly/></Field>
            <Field label="ครั้งนี้"><input className="input num" value={w} onChange={ev => setW(+ev.target.value)}/></Field>
          </div>
          <div className="row" style={{ justifyContent: "space-between", marginTop: 8, fontSize: "0.9rem" }}>
            <span style={{ color: "var(--ink-3)" }}>ใช้ไป {usedW} หน่วย × {formatBaht(room.waterRate)}</span>
            <strong className="num">{formatBaht(wCost)}</strong>
          </div>
          <div className={"meter-photo " + (waterPhoto ? "has-img" : "")} style={{ marginTop: 10 }} onClick={() => setWaterPhoto(!waterPhoto)}>
            {waterPhoto ? "✓ บันทึกรูปมิเตอร์น้ำแล้ว — IMG_WATER.jpg" : "+ แตะเพื่อถ่ายรูปมิเตอร์น้ำ"}
          </div>
        </div>
        <div className="card" style={{ padding: 14 }}>
          <div className="row" style={{ marginBottom: 8 }}><Icon name="bolt" size={18}/><strong>ไฟฟ้า</strong></div>
          <div className="grid cols-2" style={{ gap: 8 }}>
            <Field label="ครั้งก่อน"><input className="input num" value={room.prevMeter.electric} readOnly/></Field>
            <Field label="ครั้งนี้"><input className="input num" value={e} onChange={ev => setE(+ev.target.value)}/></Field>
          </div>
          <div className="row" style={{ justifyContent: "space-between", marginTop: 8, fontSize: "0.9rem" }}>
            <span style={{ color: "var(--ink-3)" }}>ใช้ไป {usedE} หน่วย × {formatBaht(room.electricRate)}</span>
            <strong className="num">{formatBaht(eCost)}</strong>
          </div>
          <div className={"meter-photo " + (elecPhoto ? "has-img" : "")} style={{ marginTop: 10 }} onClick={() => setElecPhoto(!elecPhoto)}>
            {elecPhoto ? "✓ บันทึกรูปมิเตอร์ไฟแล้ว — IMG_ELEC.jpg" : "+ แตะเพื่อถ่ายรูปมิเตอร์ไฟ"}
          </div>
        </div>
      </div>

      <div className="card" style={{ padding: 14 }}>
        <div className="row"><strong>ค่าใช้จ่ายอื่นๆ</strong><div className="spacer"/>
          <button className="btn sm" onClick={() => setExtras([...extras, { name: "", amount: 0 }])}><Icon name="plus" size={14}/> เพิ่ม</button>
        </div>
        <div className="grid" style={{ gap: 8, marginTop: 10 }}>
          {extras.map((x, i) => (
            <div key={i} className="row">
              <input className="input" placeholder="ชื่อค่าใช้จ่าย" value={x.name} onChange={ev => setExtras(extras.map((y, j) => i === j ? {...y, name: ev.target.value} : y))}/>
              <input className="input num" style={{ width: 120 }} value={x.amount} onChange={ev => setExtras(extras.map((y, j) => i === j ? {...y, amount: +ev.target.value} : y))}/>
              <button className="btn ghost sm" onClick={() => setExtras(extras.filter((_, j) => i !== j))}><Icon name="trash" size={14}/></button>
            </div>
          ))}
        </div>
      </div>

      <div style={{ padding: 16, background: "var(--info-soft)", borderRadius: 12 }}>
        <div className="row" style={{ justifyContent: "space-between" }}><span>ค่าเช่าห้อง</span><span className="num">{formatBaht(room.rent)}</span></div>
        <div className="row" style={{ justifyContent: "space-between", marginTop: 4 }}><span>ค่าน้ำ</span><span className="num">{formatBaht(wCost)}</span></div>
        <div className="row" style={{ justifyContent: "space-between", marginTop: 4 }}><span>ค่าไฟ</span><span className="num">{formatBaht(eCost)}</span></div>
        {extras.map((x, i) => (
          <div key={i} className="row" style={{ justifyContent: "space-between", marginTop: 4 }}>
            <span>{x.name || "ค่าใช้จ่ายอื่นๆ"}</span><span className="num">{formatBaht(x.amount)}</span>
          </div>
        ))}
        <div className="row" style={{ justifyContent: "space-between", marginTop: 10, paddingTop: 10, borderTop: "1px solid color-mix(in oklab, var(--accent) 30%, transparent)" }}>
          <strong style={{ fontSize: "1.05rem" }}>รวมที่ต้องชำระ</strong>
          <strong className="num" style={{ fontSize: "1.3rem", color: "var(--accent-strong)" }}>{formatBaht(total)}</strong>
        </div>
      </div>
      <div className="row" style={{ justifyContent: "flex-end", gap: 8 }}>
        <button className="btn" onClick={onCancel}>ยกเลิก</button>
        <button className="btn" onClick={() => onSave({ currMeter: { water: w, electric: e }, extras }, false)}>
          <Icon name="check" size={16}/> บันทึก
        </button>
        <button className="btn primary" onClick={() => onSave({ currMeter: { water: w, electric: e }, extras }, true)}>
          <Icon name="printer" size={16}/> พิมพ์ใบแจ้งหนี้
        </button>
      </div>
    </div>
  );
}

function EditPriceModal({ room, onSave, onCancel }) {
  const [rent, setRent] = useStateR(room.rent);
  const [size, setSize] = useStateR(room.size);
  const [waterRate, setWaterRate] = useStateR(room.waterRate);
  const [electricRate, setElectricRate] = useStateR(room.electricRate);
  const [extras, setExtras] = useStateR(room.extras || []);

  const handleSave = () => {
    onSave({ rent: Number(rent), size, waterRate: Number(waterRate), electricRate: Number(electricRate), extras });
  };

  return (
    <div className="grid" style={{ gap: 14 }}>
      <div className="grid cols-2" style={{ gap: 14 }}>
        <Field label="ค่าเช่าห้อง / เดือน"><input className="input num" value={rent} onChange={e => setRent(e.target.value)}/></Field>
        <Field label="ขนาด"><input className="input" value={size} onChange={e => setSize(e.target.value)}/></Field>
        <Field label="ค่าน้ำต่อหน่วย (บาท)"><input className="input num" value={waterRate} onChange={e => setWaterRate(e.target.value)}/></Field>
        <Field label="ค่าไฟต่อหน่วย (บาท)"><input className="input num" value={electricRate} onChange={e => setElectricRate(e.target.value)}/></Field>
      </div>
      <div>
        <div style={{ fontWeight: 600, marginBottom: 8 }}>ค่าใช้จ่ายอื่นๆ ประจำเดือน</div>
        <div className="grid" style={{ gap: 8 }}>
          {extras.map((x, i) => (
            <div key={i} className="row" style={{ gap: 8 }}>
              <input className="input" placeholder="ชื่อค่าใช้จ่าย" value={x.name}
                onChange={e => setExtras(extras.map((y, j) => i === j ? { ...y, name: e.target.value } : y))}/>
              <input className="input num" style={{ width: 120 }} value={x.amount}
                onChange={e => setExtras(extras.map((y, j) => i === j ? { ...y, amount: +e.target.value } : y))}/>
              <button className="btn ghost sm" onClick={() => setExtras(extras.filter((_, j) => i !== j))}>
                <Icon name="trash" size={16}/>
              </button>
            </div>
          ))}
          <button className="btn sm" style={{ alignSelf: "flex-start" }}
            onClick={() => setExtras([...extras, { name: "", amount: 0 }])}>
            <Icon name="plus" size={14}/> เพิ่มรายการ
          </button>
        </div>
      </div>
      <div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 4 }}>
        <button className="btn" onClick={onCancel}>ยกเลิก</button>
        <button className="btn primary" onClick={handleSave}><Icon name="check" size={16}/> บันทึก</button>
      </div>
    </div>
  );
}

window.Rooms = Rooms;
