import { useMemo, useState } from 'react'
import { BAR_MENU, DEPTS } from '../constants'
import { usePosStore } from '../store/usePosStore'
import { fmt, fmtMoney, statusPill, today } from '../utils/helpers'

export function BookingsListPage() {
  const bookings = usePosStore((s) => s.bookings)
  const viewBooking = usePosStore((s) => s.viewBooking)
  const [q, setQ] = useState('')
  const [f, setF] = useState('')
  const bookingId = (b) => b?.id || b?.bookingCode || b?.BookingCode || ''

  const list = useMemo(() => {
    const ql = q.toLowerCase()
    return bookings.filter(
      (b) =>
        (!ql ||
          (b.guestName || '').toLowerCase().includes(ql) ||
          String(bookingId(b)).toLowerCase().includes(ql) ||
          (b.room || '').includes(ql)) &&
        (!f || b.status === f)
    )
  }, [bookings, q, f])

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            All <span>Bookings</span>
          </div>
          <div className="page-sub">{list.length} booking(s)</div>
        </div>
        <div className="flex gap8">
          <input
            type="text"
            placeholder="Search name, ID, room..."
            style={{ width: 200 }}
            value={q}
            onChange={(e) => setQ(e.target.value)}
          />
          <select value={f} onChange={(e) => setF(e.target.value)} style={{ width: 130 }}>
            <option value="">All Status</option>
            <option value="confirmed">Confirmed</option>
            <option value="checked-in">Checked In</option>
            <option value="checked-out">Checked Out</option>
            <option value="cancelled">Cancelled</option>
          </select>
        </div>
      </div>
      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Booking ID</th>
                <th>Guest</th>
                <th>Room</th>
                <th>Package</th>
                <th>Check-in</th>
                <th>Check-out</th>
                <th>Pax</th>
                <th>Total (RM)</th>
                <th>Agent</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {list.length ? (
                [...list].reverse().map((b) => {
                  const id = bookingId(b)
                  return (
                  <tr
                    key={id}
                    onClick={() => viewBooking(id)}
                    style={{ cursor: 'pointer' }}
                    title="Click to view booking details"
                  >
                    <td className="mono text-teal">{id}</td>
                    <td>{b.guestName}</td>
                    <td>{b.room || '-'}</td>
                    <td>{b.packageType || '-'}</td>
                    <td>{fmt(b.checkin)}</td>
                    <td>{fmt(b.checkout)}</td>
                    <td>{(b.pax?.adult || 0) + (b.pax?.kid || 0) + (b.pax?.elderly || 0)}</td>
                    <td className="text-gold fw6">{fmtMoney(b.totalAmount)}</td>
                    <td>{b.agentCode || '-'}</td>
                    <td>
                      <span className={`pill ${statusPill(b.status)}`}>{b.status}</span>
                    </td>
                    <td>
                      <button
                        type="button"
                        className="btn btn-ghost btn-xs"
                        onClick={(e) => {
                          e.stopPropagation()
                          viewBooking(id)
                        }}
                      >
                        View
                      </button>
                    </td>
                  </tr>
                )})
              ) : (
                <tr>
                  <td colSpan={11} className="text-muted text-center" style={{ padding: 20 }}>
                    No bookings found
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function RoomMapPage() {
  const rooms = usePosStore((s) => s.rooms)
  const showRoomDetail = usePosStore((s) => s.showRoomDetail)

  const byType = useMemo(() => {
    const o = {}
    rooms.forEach((r) => {
      if (!o[r.type]) o[r.type] = []
      o[r.type].push(r)
    })
    return o
  }, [rooms])

  const labels = { available: 'Available', occupied: 'Occupied', maintenance: 'Maintenance', blocked: 'Blocked' }

  return (
    <div className="room-map-page">
      <div className="page-header">
        <div>
          <div className="page-title">
            Room <span>Map</span>
          </div>
          <div className="page-sub">Real-time room availability and status</div>
        </div>
        <div className="legend">
          <div className="legend-item">
            <div className="legend-dot" style={{ background: 'var(--green)' }} />
            Available
          </div>
          <div className="legend-item">
            <div className="legend-dot" style={{ background: 'var(--coral)' }} />
            Occupied
          </div>
          <div className="legend-item">
            <div className="legend-dot" style={{ background: 'var(--yellow)' }} />
            Maintenance
          </div>
          <div className="legend-item">
            <div className="legend-dot" style={{ background: 'var(--muted)' }} />
            Blocked
          </div>
        </div>
      </div>
      {Object.entries(byType).map(([type, rs]) => (
        <div key={type} className="mb16">
          <div className="section-label">
            {type} ({rs.filter((r) => r.status === 'available').length}/{rs.length} available)
          </div>
          <div className="room-grid">
            {rs.map((r) => (
              <button
                key={r.id}
                type="button"
                className={`room-card ${r.status}`}
                onClick={() => showRoomDetail(r.id)}
              >
                <div className="rc-num">{r.id}</div>
                <div className="rc-type">Max {r.maxPax} pax</div>
                <div className="rc-status">{labels[r.status]}</div>
                {r.currentBooking ? (
                  <div className="rc-booking-ref">{r.currentBooking}</div>
                ) : null}
              </button>
            ))}
          </div>
        </div>
      ))}
    </div>
  )
}

export function GuestsPage() {
  const bookings = usePosStore((s) => s.bookings)
  const [q, setQ] = useState('')

  const list = useMemo(() => {
    const guestMap = {}
    bookings.forEach((b) => {
      if (!guestMap[b.guestName]) {
        guestMap[b.guestName] = {
          name: b.guestName,
          nationality: b.nationality,
          ic: b.ic,
          phone: b.phone,
          email: b.email,
          bookings: 0,
          wallet: 0,
        }
      }
      guestMap[b.guestName].bookings++
    })
    const ql = q.toLowerCase()
    return Object.values(guestMap).filter((g) => !ql || g.name.toLowerCase().includes(ql))
  }, [bookings, q])

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Guest <span>Directory</span>
          </div>
        </div>
        <input
          type="text"
          placeholder="Search guest..."
          style={{ width: 200 }}
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
      </div>
      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Guest ID</th>
                <th>Name</th>
                <th>Nationality</th>
                <th>IC/Passport</th>
                <th>Phone</th>
                <th>Email</th>
                <th>Wallet (RM)</th>
                <th>Bookings</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {list.length ? (
                list.map((g, i) => (
                  <tr key={g.name}>
                    <td className="mono text-muted">G{String(i + 1).padStart(4, '0')}</td>
                    <td className="fw6">{g.name}</td>
                    <td>{g.nationality || '-'}</td>
                    <td>{g.ic || '-'}</td>
                    <td>{g.phone || '-'}</td>
                    <td>{g.email || '-'}</td>
                    <td className="text-gold">{fmtMoney(g.wallet)}</td>
                    <td>{g.bookings}</td>
                    <td>
                      <button type="button" className="btn btn-ghost btn-xs">
                        View
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={9} className="text-muted text-center" style={{ padding: 20 }}>
                    No guests found
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function DiveSchedulePage() {
  const dives = usePosStore((s) => s.dives)
  const openModal = usePosStore((s) => s.openModal)
  const cancelDive = usePosStore((s) => s.cancelDive)
  const td = today()
  const todayDives = dives.filter((d) => d.date === td)

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Dive <span>Schedule</span>
          </div>
          <div className="page-sub">Manage dive slots, boats, and instructors</div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => openModal('add-dive')}>
          + Add Dive Slot
        </button>
      </div>
      <div className="g2 mb16">
        <div className="card">
          <div className="card-title">📅 Today&apos;s Dives</div>
          {todayDives.length ? (
            todayDives.map((d) => (
              <div key={d.id} className="activity-item">
                <div className="act-icon" style={{ background: 'rgba(14,159,142,.2)' }}>🤿</div>
                <div className="act-body">
                  <div className="act-title">
                    {d.type} — {d.time}
                  </div>
                  <div className="act-sub">
                    {d.boat} · {d.instructor || 'Unassigned'} · {d.divers || 0}/{d.maxDivers} divers
                  </div>
                </div>
                <span className="pill pill-teal">{d.status || 'Scheduled'}</span>
              </div>
            ))
          ) : (
            <div className="text-muted text-center" style={{ padding: 12 }}>
              No dives today
            </div>
          )}
        </div>
        <div className="card">
          <div className="card-title">📊 Dive Stats</div>
          <div className="stats-row" style={{ gridTemplateColumns: '1fr 1fr' }}>
            <div className="stat teal">
              <div className="stat-label">Today Dives</div>
              <div className="stat-val teal">{todayDives.length}</div>
            </div>
            <div className="stat ocean">
              <div className="stat-label">Total Divers</div>
              <div className="stat-val ocean">{todayDives.reduce((s, d) => s + (d.divers || 0), 0)}</div>
            </div>
          </div>
        </div>
      </div>
      <div className="card">
        <div className="card-title">🗓 All Scheduled Dives</div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Date</th>
                <th>Time</th>
                <th>Type</th>
                <th>Boat</th>
                <th>Instructor</th>
                <th>Divers</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {dives.length ? (
                [...dives].reverse().map((d) => (
                  <tr key={d.id}>
                    <td>{fmt(d.date)}</td>
                    <td>{d.time}</td>
                    <td>{d.type}</td>
                    <td>{d.boat}</td>
                    <td>{d.instructor || '-'}</td>
                    <td>
                      {d.divers || 0}/{d.maxDivers}
                    </td>
                    <td>
                      <span className="pill pill-teal">{d.status || 'Scheduled'}</span>
                    </td>
                    <td>
                      <button type="button" className="btn btn-ghost btn-xs" onClick={() => cancelDive(d.id)}>
                        Cancel
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={8} className="text-muted text-center" style={{ padding: 16 }}>
                    No dives scheduled
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function EquipmentPage() {
  const equipment = usePosStore((s) => s.equipment)
  const openModal = usePosStore((s) => s.openModal)

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Equipment <span>Rental</span>
          </div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => openModal('add-equip')}>
          + Add Equipment
        </button>
      </div>
      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Item</th>
                <th>Category</th>
                <th>Total Units</th>
                <th>Available</th>
                <th>Rented</th>
                <th>Rate/Day (RM)</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {equipment.map((e) => (
                <tr key={e.id}>
                  <td className="fw6">{e.name}</td>
                  <td>{e.cat}</td>
                  <td>{e.total}</td>
                  <td className="text-green">{e.available}</td>
                  <td className="text-coral">{e.total - e.available}</td>
                  <td>RM {e.rate}</td>
                  <td>
                    <span className={`pill ${e.available > 0 ? 'pill-green' : 'pill-red'}`}>
                      {e.available > 0 ? 'Available' : 'All Rented'}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function InstructorsPage() {
  const instructors = usePosStore((s) => s.instructors)
  const openModal = usePosStore((s) => s.openModal)

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Instructors & <span>Dive Masters</span>
          </div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => openModal('add-instructor')}>
          + Add Staff
        </button>
      </div>
      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Name</th>
                <th>Role</th>
                <th>Cert Level</th>
                <th>Dives This Month</th>
                <th>Commission (RM)</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {instructors.map((i) => (
                <tr key={i.id}>
                  <td className="fw6">{i.name}</td>
                  <td>{i.role}</td>
                  <td>{i.cert}</td>
                  <td>{i.dives}</td>
                  <td className="text-gold">{fmtMoney(i.dives * i.commission)}</td>
                  <td>
                    <span className={`pill ${i.status === 'Active' ? 'pill-green' : 'pill-gray'}`}>{i.status}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function BarPOSPage() {
  const barCat = usePosStore((s) => s.barCat)
  const barCart = usePosStore((s) => s.barCart)
  const barRoomCharge = usePosStore((s) => s.barRoomCharge)
  const bookings = usePosStore((s) => s.bookings)
  const setBarCat = usePosStore((s) => s.setBarCat)
  const setBarRoomCharge = usePosStore((s) => s.setBarRoomCharge)
  const addBarCartItem = usePosStore((s) => s.addBarCartItem)
  const removeBarCartItem = usePosStore((s) => s.removeBarCartItem)
  const clearBarCart = usePosStore((s) => s.clearBarCart)
  const processBarSale = usePosStore((s) => s.processBarSale)
  const barSales = usePosStore((s) => s.barSales)

  const sub = barCart.reduce((s, i) => s + i.price * i.qty, 0)
  const tax = sub * 0.06

  const showBarReport = () => {
    const t = today()
    const today_sales = barSales.filter((s) => s.date === t)
    const total = today_sales.reduce((s, x) => s + x.total, 0)
    alert(`📊 Today's Bar Report\nTransactions: ${today_sales.length}\nTotal Revenue: ${fmtMoney(total)}`)
  }

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Sunset Bar <span>POS</span>
          </div>
          <div className="page-sub">Point of sale & inventory management</div>
        </div>
        <button type="button" className="btn btn-ghost btn-sm" onClick={showBarReport}>
          📊 Daily Report
        </button>
      </div>
      <div className="pos-grid">
        <div className="pos-items">
          <div className="pos-cat-tabs">
            {Object.keys(BAR_MENU).map((c) => (
              <button
                key={c}
                type="button"
                className={`cat-tab${c === barCat ? ' active' : ''}`}
                onClick={() => setBarCat(c)}
              >
                {c}
              </button>
            ))}
          </div>
          <div className="item-grid">
            {(BAR_MENU[barCat] || []).map((item) => (
              <button
                key={item.name}
                type="button"
                className="item-btn"
                onClick={() => addBarCartItem(item)}
              >
                <div style={{ fontSize: '1.8rem' }}>{item.emoji}</div>
                <div className="item-name">{item.name}</div>
                <div className="item-price">RM {item.price.toFixed(2)}</div>
              </button>
            ))}
          </div>
        </div>
        <div className="pos-cart">
          <div style={{ padding: 14, borderBottom: '1px solid var(--border)' }}>
            <div className="card-title" style={{ margin: 0 }}>
              🧾 Current Order
            </div>
            <div className="fgroup mt8">
              <label className="lbl">Charge To Room (optional)</label>
              <select value={barRoomCharge} onChange={(e) => setBarRoomCharge(e.target.value)}>
                <option value="">— Walk-in —</option>
                {bookings
                  .filter((b) => b.status === 'checked-in')
                  .map((b) => (
                    <option key={b.id} value={b.id}>
                      Room {b.room} - {b.guestName}
                    </option>
                  ))}
              </select>
            </div>
          </div>
          <div className="cart-list">
            {barCart.length ? (
              barCart.map((i) => (
                <div key={i.name} className="cart-item">
                  <div>
                    <div className="cart-item-name">
                      {i.emoji} {i.name}
                    </div>
                    <div className="text-muted" style={{ fontSize: '0.7rem' }}>
                      RM {i.price.toFixed(2)} each
                    </div>
                  </div>
                  <div className="cart-item-qty">
                    <button type="button" className="qty-btn" onClick={() => removeBarCartItem(i.name)}>
                      −
                    </button>
                    <span>{i.qty}</span>
                    <button type="button" className="qty-btn" onClick={() => addBarCartItem(i)}>
                      +
                    </button>
                  </div>
                  <div className="text-gold fw6">RM {(i.price * i.qty).toFixed(2)}</div>
                </div>
              ))
            ) : (
              <div className="text-muted text-center" style={{ padding: 20, fontSize: '0.8rem' }}>
                Cart is empty
              </div>
            )}
          </div>
          <div className="cart-footer">
            <div className="cart-total-row">
              <span>Subtotal</span>
              <span>{fmtMoney(sub)}</span>
            </div>
            <div className="cart-total-row">
              <span>Tax (6%)</span>
              <span>{fmtMoney(tax)}</span>
            </div>
            <div className="cart-total-row big">
              <span>TOTAL</span>
              <span>{fmtMoney(sub + tax)}</span>
            </div>
            <div className="mt8 flex gap8">
              <button type="button" className="btn btn-ghost btn-sm w100" onClick={() => clearBarCart()}>
                🗑 Clear
              </button>
              <button type="button" className="btn btn-success w100" onClick={() => processBarSale()}>
                ✅ Charge
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}

export function TransportPage() {
  const trips = usePosStore((s) => s.trips)
  const openModal = usePosStore((s) => s.openModal)

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Transport & <span>Shuttle</span>
          </div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => openModal('add-trip')}>
          + Schedule Trip
        </button>
      </div>
      <div className="card mb16">
        <div className="card-title">🚌 Scheduled Trips</div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Date</th>
                <th>Route</th>
                <th>Time</th>
                <th>Capacity</th>
                <th>Booked</th>
                <th>Available</th>
                <th>Manifest</th>
              </tr>
            </thead>
            <tbody>
              {trips.length ? (
                trips.map((t) => (
                  <tr key={t.id}>
                    <td>{fmt(t.date)}</td>
                    <td>{t.route}</td>
                    <td>{t.time}</td>
                    <td>{t.capacity}</td>
                    <td>{t.booked}</td>
                    <td className="text-green">{t.capacity - t.booked}</td>
                    <td>
                      <button
                        type="button"
                        className="btn btn-ghost btn-xs"
                        onClick={() =>
                          alert(
                            `📋 Manifest: ${t.route}\n${fmt(t.date)} ${t.time}\nBooked: ${t.booked}/${t.capacity}`
                          )
                        }
                      >
                        📋 Manifest
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="text-muted text-center" style={{ padding: 16 }}>
                    No trips scheduled
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function EventsPage() {
  const events = usePosStore((s) => s.events)
  const openModal = usePosStore((s) => s.openModal)
  const payEventBalance = usePosStore((s) => s.payEventBalance)

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Events & <span>Groups</span>
          </div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => openModal('add-event')}>
          + Create Event
        </button>
      </div>
      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Event ID</th>
                <th>Name</th>
                <th>Date</th>
                <th>Pax</th>
                <th>Total (RM)</th>
                <th>Deposit (RM)</th>
                <th>Balance (RM)</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {events.length ? (
                events.map((e) => (
                  <tr key={e.id}>
                    <td className="mono text-teal">{e.id}</td>
                    <td className="fw6">{e.name}</td>
                    <td>{fmt(e.date)}</td>
                    <td>{e.pax}</td>
                    <td>{fmtMoney(e.total)}</td>
                    <td className="text-green">{fmtMoney(e.deposit)}</td>
                    <td className="text-coral">{fmtMoney(e.total - e.deposit)}</td>
                    <td>
                      <span className="pill pill-blue">{e.status || 'Active'}</span>
                    </td>
                    <td>
                      <button type="button" className="btn btn-ghost btn-xs" onClick={() => payEventBalance(e.id)}>
                        Pay Balance
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={9} className="text-muted text-center" style={{ padding: 16 }}>
                    No events
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function WalletPage() {
  const bookings = usePosStore((s) => s.bookings)

  const list = useMemo(() => {
    const guestMap = {}
    bookings.forEach((b) => {
      if (!guestMap[b.guestName]) guestMap[b.guestName] = { name: b.guestName, wallet: 0 }
    })
    return Object.values(guestMap)
  }, [bookings])

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Guest <span>Wallet</span>
          </div>
          <div className="page-sub">Store credits, refunds and island spending</div>
        </div>
      </div>
      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Guest</th>
                <th>Balance (RM)</th>
                <th>Last Topped Up</th>
                <th>Expires</th>
                <th>Transactions</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {list.length ? (
                list.map((g) => (
                  <tr key={g.name}>
                    <td className="fw6">{g.name}</td>
                    <td className="text-gold">{fmtMoney(g.wallet)}</td>
                    <td>-</td>
                    <td>Never</td>
                    <td>0</td>
                    <td>
                      <button
                        type="button"
                        className="btn btn-ghost btn-xs"
                        onClick={() => {
                          const amt = prompt(`Top up wallet for ${g.name} (RM):`)
                          if (amt) alert(`Topped up RM${amt} for ${g.name}`)
                        }}
                      >
                        + Top Up
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} className="text-muted text-center" style={{ padding: 16 }}>
                    No wallet records
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function AgentsPage() {
  const agents = usePosStore((s) => s.agents)
  const openModal = usePosStore((s) => s.openModal)
  const deactivateAgent = usePosStore((s) => s.deactivateAgent)

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Agent <span>Management</span>
          </div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => openModal('add-agent')}>
          + Add Agent
        </button>
      </div>
      <div className="card">
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Agent ID</th>
                <th>Name</th>
                <th>Code</th>
                <th>Commission</th>
                <th>Bookings</th>
                <th>Total Earned (RM)</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {agents.length ? (
                agents.map((a) => (
                  <tr key={a.id}>
                    <td className="mono text-teal">{a.id}</td>
                    <td className="fw6">{a.name}</td>
                    <td>
                      <span className="pill pill-purple">{a.code}</span>
                    </td>
                    <td>
                      {a.rate}
                      {a.type === 'percent' ? '%' : ' RM fixed'}
                    </td>
                    <td>{a.bookings}</td>
                    <td className="text-gold">{fmtMoney(a.earned)}</td>
                    <td>
                      <span className={`pill ${a.status === 'Active' ? 'pill-green' : 'pill-gray'}`}>{a.status}</span>
                    </td>
                    <td>
                      <button type="button" className="btn btn-ghost btn-xs" onClick={() => deactivateAgent(a.id)}>
                        Deactivate
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={8} className="text-muted text-center" style={{ padding: 16 }}>
                    No agents
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function CommissionPage() {
  const bookings = usePosStore((s) => s.bookings)

  const totalGuests = bookings
    .filter((b) => b.status !== 'cancelled')
    .reduce((s, b) => s + (b.pax?.adult || 0) + (b.pax?.kid || 0) + (b.pax?.elderly || 0), 0)
  const perDept = DEPTS.length ? (totalGuests * 10) / DEPTS.length : 0

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Commission <span>Distribution</span>
          </div>
          <div className="page-sub">RM10 per guest — distributed across departments</div>
        </div>
      </div>
      <div className="stats-row" id="comm-stats">
        <div className="stat gold">
          <div className="stat-label">Total Guests</div>
          <div className="stat-val gold">{totalGuests}</div>
        </div>
        <div className="stat teal">
          <div className="stat-label">Rate/Guest</div>
          <div className="stat-val teal">RM 10</div>
        </div>
        <div className="stat green">
          <div className="stat-label">Total Pool</div>
          <div className="stat-val green">{fmtMoney(totalGuests * 10)}</div>
        </div>
        <div className="stat ocean">
          <div className="stat-label">Departments</div>
          <div className="stat-val ocean">{DEPTS.length}</div>
        </div>
      </div>
      <div className="card">
        <div className="card-title">💰 Department Breakdown</div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Department</th>
                <th>Guests</th>
                <th>Rate (RM)</th>
                <th>This Month (RM)</th>
                <th>YTD (RM)</th>
              </tr>
            </thead>
            <tbody>
              {DEPTS.map((d) => (
                <tr key={d}>
                  <td className="fw6">{d}</td>
                  <td>{totalGuests}</td>
                  <td>RM 10</td>
                  <td className="text-gold">{fmtMoney(perDept)}</td>
                  <td className="text-green">{fmtMoney(perDept * 12)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}

export function ReportsPage() {
  const transactions = usePosStore((s) => s.transactions)
  const bookings = usePosStore((s) => s.bookings)
  const rooms = usePosStore((s) => s.rooms)
  const [period, setPeriod] = useState('month')

  const totalRev = transactions.reduce((s, t) => s + t.amount, 0)
  const totalBk = bookings.length
  const occ = rooms.length ? Math.round((rooms.filter((r) => r.status === 'occupied').length / rooms.length) * 100) : 0
  const avgNights = bookings.length
    ? bookings.reduce((s, b) => s + (b.nights || 0), 0) / bookings.length
    : 0

  const cats = { Booking: 0, Bar: 0, Event: 0, Checkout: 0, Other: 0 }
  transactions.forEach((t) => {
    cats[t.category] = (cats[t.category] || 0) + t.amount
  })

  const pkgCount = {}
  bookings.forEach((b) => {
    if (b.packageType) pkgCount[b.packageType] = (pkgCount[b.packageType] || 0) + 1
  })

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">
            Reports & <span>Analytics</span>
          </div>
        </div>
        <div className="flex gap8">
          <select value={period} onChange={(e) => setPeriod(e.target.value)} style={{ width: 130 }}>
            <option value="today">Today</option>
            <option value="week">This Week</option>
            <option value="month">This Month</option>
            <option value="year">This Year</option>
          </select>
          <button type="button" className="btn btn-ghost btn-sm">
            📥 Export
          </button>
        </div>
      </div>
      <div className="stats-row">
        <div className="stat gold">
          <div className="stat-label">Total Revenue</div>
          <div className="stat-val gold">{fmtMoney(totalRev)}</div>
          <div className="stat-sub">{period}</div>
        </div>
        <div className="stat teal">
          <div className="stat-label">Total Bookings</div>
          <div className="stat-val teal">{totalBk}</div>
        </div>
        <div className="stat ocean">
          <div className="stat-label">Occupancy Rate</div>
          <div className="stat-val ocean">{occ}%</div>
        </div>
        <div className="stat green">
          <div className="stat-label">Avg Stay</div>
          <div className="stat-val green">{avgNights.toFixed(1)} nts</div>
        </div>
      </div>
      <div className="g2 mb16">
        <div className="card">
          <div className="card-title">📊 Revenue by Category</div>
          {Object.entries(cats).filter(([, v]) => v > 0).length ? (
            Object.entries(cats)
              .filter(([, v]) => v > 0)
              .map(([k, v]) => (
                <div key={k} className="mb8">
                  <div className="flex jb mb8" style={{ fontSize: '0.8rem' }}>
                    <span>{k}</span>
                    <span className="fw6">{fmtMoney(v)}</span>
                  </div>
                  <div className="progress-bar">
                    <div
                      className="progress-fill"
                      style={{ width: `${totalRev ? Math.round((v / totalRev) * 100) : 0}%` }}
                    />
                  </div>
                </div>
              ))
          ) : (
            <div className="text-muted">No data</div>
          )}
        </div>
        <div className="card">
          <div className="card-title">🏆 Top Packages</div>
          {Object.keys(pkgCount).length ? (
            Object.entries(pkgCount)
              .sort((a, b) => b[1] - a[1])
              .map(([k, v]) => (
                <div key={k} className="flex jb mb8" style={{ fontSize: '0.82rem' }}>
                  <span>{k}</span>
                  <span className="pill pill-teal">{v} bookings</span>
                </div>
              ))
          ) : (
            <div className="text-muted">No data</div>
          )}
        </div>
      </div>
      <div className="card">
        <div className="card-title">📋 All Transactions</div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>Date</th>
                <th>Booking ID</th>
                <th>Guest</th>
                <th>Category</th>
                <th>Amount (RM)</th>
                <th>Method</th>
              </tr>
            </thead>
            <tbody>
              {transactions.length ? (
                [...transactions].reverse().map((t) => (
                  <tr key={t.id}>
                    <td>{fmt(t.date)}</td>
                    <td className="mono text-muted">{t.bookingId || '-'}</td>
                    <td>{t.guestName || '-'}</td>
                    <td>
                      <span className="pill pill-blue">{t.category}</span>
                    </td>
                    <td className="text-gold fw6">{fmtMoney(t.amount)}</td>
                    <td>{t.method || '-'}</td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} className="text-muted text-center" style={{ padding: 16 }}>
                    No transactions
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}
