// ═══════════════════════════════════════════════════════════════════════
// Dyra Mobile — Admin (compact mobile admin for on-the-go operators)
// ═══════════════════════════════════════════════════════════════════════
// Mobile-first admin: optimized for the most common on-the-go operator
// tasks. Mendy is replying to inquiries from a parking lot, blocking dates
// from a shul lobby, checking arrivals during seudah. The full admin
// remains on desktop — this is the field-ops slice.
//
// Screens:
//   • Today (arrivals/departures + alerts)
//   • Reservations (list + detail)
//   • Inquiries (mobile compose + reply)
//   • Listings overview (toggle status, quick edit price)
// ═══════════════════════════════════════════════════════════════════════

const PM4 = DYRA_MOBILE_PALETTE;
const TM4 = DYRA_MOBILE_TYPE;

// ─── small admin atoms ─────────────────────────────────────────────────
function MAdminCard({ children, style, padding = 16 }) {
  return (
    <div style={{
      background: PM4.surface, border: `0.5px solid ${PM4.lineSoft}`,
      borderRadius: 14, padding, ...style,
    }}>{children}</div>
  );
}

function MAdminPill({ tone = 'neutral', children }) {
  const tones = {
    neutral: { bg: PM4.lineSoft, fg: PM4.muted },
    ok:      { bg: '#e6efe6',    fg: PM4.success },
    warn:    { bg: '#f5e6d0',    fg: '#7a5a2e' },
    err:     { bg: '#f5dad0',    fg: PM4.danger },
    accent:  { bg: PM4.accentSoft, fg: PM4.accentDark },
  };
  const t = tones[tone] || tones.neutral;
  return <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 4,
    padding: '3px 9px', borderRadius: 100,
    background: t.bg, color: t.fg,
    fontFamily: TM4.sans, fontSize: 10, fontWeight: 500,
    letterSpacing: '0.04em', textTransform: 'uppercase',
  }}>{children}</span>;
}

// ═══════════════════════════════════════════════════════════════════════
// ADMIN TODAY
// ═══════════════════════════════════════════════════════════════════════
function MAdminToday({ go, openMenu }) {
  const props = window.DyraStore?.state?.properties || window.DYRA?.PROPERTIES || [];
  const today = new Date('2026-05-12');
  const arrivals = [
    { id: 'r1', guest: 'Goldberg family', propId: 'ep-4br-2ba', date: 'Today', time: '3:00 PM', guests: 6 },
  ];
  const departures = [
    { id: 'r2', guest: 'Wolfson family', propId: 'crown-510', date: 'Today', time: '11:00 AM', guests: 4 },
  ];
  const upcoming = [
    { id: 'r3', guest: 'Rosenberg family', propId: 'presidential', date: 'Tue May 14', guests: 7 },
    { id: 'r4', guest: 'Klein family', propId: 'empire-2br', date: 'Wed May 15', guests: 4 },
  ];

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PM4.bg }}>
      <MAppBar
        scrolled
        title="Today · Admin"
        leading={<MIconBtn label="Menu" onClick={openMenu}><MIco name="menu" size={22}/></MIconBtn>}
        trailing={<MIconBtn label="Notifications">
          <span style={{ position: 'relative' }}>
            <MIco name="mail" size={22}/>
            <span style={{
              position: 'absolute', top: -2, right: -2, width: 9, height: 9,
              borderRadius: 5, background: PM4.danger, border: `1.5px solid ${PM4.bg}`,
            }}/>
          </span>
        </MIconBtn>}
      />
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 16px 24px' }}>
        {/* date + greeting */}
        <div style={{ padding: '4px 4px 16px' }}>
          <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: PM4.accent }}>
            Tuesday · May 12, 2026
          </div>
          <div style={{ fontFamily: TM4.serif, fontSize: 28, color: PM4.ink, fontWeight: 500, marginTop: 6, lineHeight: 1.1 }}>
            Good morning, Mendy.
          </div>
        </div>

        {/* alert tile */}
        <div style={{
          marginBottom: 14, padding: '12px 14px', borderRadius: 12,
          background: '#fdf3e8', border: `0.5px solid #e8c89a`,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <span style={{
            width: 32, height: 32, borderRadius: 16, background: '#7a5a2e', color: '#fff',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}><MIco name="phone" size={16} color="#fff"/></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: TM4.sans, fontSize: 13, color: PM4.ink, fontWeight: 500 }}>3 unanswered inquiries</div>
            <div style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted, marginTop: 1 }}>Oldest 4h ago</div>
          </div>
          <MIco name="forward" size={16} color={PM4.muted}/>
        </div>

        {/* KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginBottom: 24 }}>
          {[
            { v: '$8,420', l: 'May revenue', tone: 'ok' },
            { v: '11/14', l: 'Nights booked', tone: null },
            { v: '92%', l: 'Occupancy', tone: 'ok' },
            { v: '$1,925', l: 'Pending', tone: 'warn' },
          ].map((k, i) => (
            <MAdminCard key={i} padding={14}>
              <div style={{ fontFamily: TM4.serif, fontSize: 22, color: PM4.ink, fontWeight: 500 }}>{k.v}</div>
              <div style={{ fontFamily: TM4.sans, fontSize: 10, color: PM4.muted, marginTop: 4, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{k.l}</div>
            </MAdminCard>
          ))}
        </div>

        {/* arrivals */}
        <div style={{ marginBottom: 20 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 4px 10px' }}>
            <h3 style={{ fontFamily: TM4.serif, fontSize: 18, color: PM4.ink, fontWeight: 500, margin: 0 }}>Arrivals today</h3>
            <span style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted }}>{arrivals.length}</span>
          </div>
          {arrivals.map(r => {
            const p = props.find(x => x.id === r.propId);
            return (
              <MAdminCard key={r.id} padding={14} style={{ marginBottom: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <MAdminPill tone="ok">▲ Arrival</MAdminPill>
                  <span style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted }}>{r.time}</span>
                </div>
                <div style={{ fontFamily: TM4.serif, fontSize: 17, color: PM4.ink, fontWeight: 500, marginTop: 8, lineHeight: 1.15 }}>
                  {r.guest}
                </div>
                <div style={{ fontFamily: TM4.sans, fontSize: 12, color: PM4.muted, marginTop: 2 }}>
                  {p?.name} · {r.guests} guests
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <button style={{ flex: 1, padding: '8px 10px', borderRadius: 8, border: `1px solid ${PM4.line}`, background: 'transparent', fontFamily: TM4.sans, fontSize: 12, color: PM4.ink, fontWeight: 500, cursor: 'pointer' }}>Send code</button>
                  <button style={{ flex: 1, padding: '8px 10px', borderRadius: 8, border: 'none', background: PM4.ink, color: PM4.bg, fontFamily: TM4.sans, fontSize: 12, fontWeight: 500, cursor: 'pointer' }}>Open booking</button>
                </div>
              </MAdminCard>
            );
          })}
        </div>

        {/* departures */}
        <div style={{ marginBottom: 20 }}>
          <h3 style={{ fontFamily: TM4.serif, fontSize: 18, color: PM4.ink, fontWeight: 500, padding: '0 4px 10px', margin: 0 }}>Departures today</h3>
          {departures.map(r => {
            const p = props.find(x => x.id === r.propId);
            return (
              <MAdminCard key={r.id} padding={14} style={{ marginBottom: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <MAdminPill tone="warn">▼ Departure</MAdminPill>
                  <span style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted }}>{r.time}</span>
                </div>
                <div style={{ fontFamily: TM4.serif, fontSize: 17, color: PM4.ink, fontWeight: 500, marginTop: 8, lineHeight: 1.15 }}>
                  {r.guest}
                </div>
                <div style={{ fontFamily: TM4.sans, fontSize: 12, color: PM4.muted, marginTop: 2 }}>
                  {p?.name} · turnover required
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <button style={{ flex: 1, padding: '8px 10px', borderRadius: 8, border: `1px solid ${PM4.line}`, background: 'transparent', fontFamily: TM4.sans, fontSize: 12, color: PM4.ink, fontWeight: 500, cursor: 'pointer' }}>Notify cleaner</button>
                  <button style={{ flex: 1, padding: '8px 10px', borderRadius: 8, border: 'none', background: PM4.ink, color: PM4.bg, fontFamily: TM4.sans, fontSize: 12, fontWeight: 500, cursor: 'pointer' }}>Mark cleaned</button>
                </div>
              </MAdminCard>
            );
          })}
        </div>

        {/* upcoming */}
        <div>
          <h3 style={{ fontFamily: TM4.serif, fontSize: 18, color: PM4.ink, fontWeight: 500, padding: '0 4px 10px', margin: 0 }}>This week</h3>
          {upcoming.map(r => {
            const p = props.find(x => x.id === r.propId);
            return (
              <button key={r.id} onClick={() => go('admin-res:' + r.id)} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', width: '100%',
                background: PM4.surface, border: `0.5px solid ${PM4.lineSoft}`,
                borderRadius: 12, marginBottom: 8, cursor: 'pointer', textAlign: 'left',
                fontFamily: 'inherit',
              }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: TM4.sans, fontSize: 14, color: PM4.ink, fontWeight: 500 }}>{r.guest}</div>
                  <div style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted, marginTop: 2 }}>
                    {r.date} · {p?.name} · {r.guests} guests
                  </div>
                </div>
                <MIco name="forward" size={16} color={PM4.muted}/>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// ADMIN RESERVATIONS
// ═══════════════════════════════════════════════════════════════════════
function MAdminReservations({ go, openMenu }) {
  const [filter, setFilter] = React.useState('all');
  const props = window.DyraStore?.state?.properties || window.DYRA?.PROPERTIES || [];
  const list = [
    { id: 'DYR-26-0844', guest: 'Goldberg family', propId: 'ep-4br-2ba', dates: 'May 8 → 11', total: 1925, status: 'arriving', source: 'mobile' },
    { id: 'DYR-26-0837', guest: 'Wolfson family', propId: 'crown-510', dates: 'May 9 → 12', total: 1535, status: 'departing', source: 'site' },
    { id: 'DYR-26-0822', guest: 'Rosenberg family', propId: 'presidential', dates: 'May 14 → 18', total: 5380, status: 'paid', source: 'site' },
    { id: 'DYR-26-0815', guest: 'Klein family', propId: 'empire-2br', dates: 'May 15 → 17', total: 525, status: 'deposit', source: 'mobile' },
    { id: 'DYR-26-0809', guest: 'Berkowitz', propId: 'crown-468-5br', dates: 'May 22 → 25', total: 2100, status: 'pending', source: 'phone' },
  ];
  const filtered = filter === 'all' ? list : list.filter(r => r.status === filter);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PM4.bg }}>
      <MAppBar scrolled title="Reservations" leading={<MIconBtn onClick={openMenu} label="Menu"><MIco name="menu" size={22}/></MIconBtn>}
        trailing={<MIconBtn label="Add"><MIco name="plus" size={22}/></MIconBtn>}/>
      {/* search */}
      <div style={{ padding: '12px 16px 8px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '10px 14px', background: PM4.surface,
          border: `0.5px solid ${PM4.line}`, borderRadius: 12,
        }}>
          <MIco name="search" size={18} color={PM4.muted}/>
          <input placeholder="Search guests, IDs…" style={{
            flex: 1, border: 'none', background: 'transparent', outline: 'none',
            fontFamily: TM4.sans, fontSize: 14, color: PM4.ink,
          }}/>
        </div>
      </div>

      {/* chips */}
      <div style={{ display: 'flex', gap: 6, padding: '4px 16px 12px', overflowX: 'auto' }}>
        {[
          { id: 'all', label: 'All', n: list.length },
          { id: 'arriving', label: 'Arriving', n: 1 },
          { id: 'departing', label: 'Departing', n: 1 },
          { id: 'pending', label: 'Pending', n: 1 },
          { id: 'paid', label: 'Paid', n: 1 },
        ].map(c => (
          <button key={c.id} onClick={() => setFilter(c.id)} style={{
            padding: '7px 12px', borderRadius: 100,
            background: filter === c.id ? PM4.ink : PM4.surface,
            color: filter === c.id ? PM4.bg : PM4.ink,
            border: filter === c.id ? 'none' : `0.5px solid ${PM4.line}`,
            fontFamily: TM4.sans, fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap',
            cursor: 'pointer',
          }}>{c.label} <span style={{ opacity: 0.6, marginLeft: 4 }}>{c.n}</span></button>
        ))}
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 16px 24px' }}>
        {filtered.map(r => {
          const p = props.find(x => x.id === r.propId);
          const tones = { arriving: 'ok', departing: 'warn', paid: 'ok', deposit: 'accent', pending: 'warn' };
          return (
            <button key={r.id} onClick={() => go('admin-res:' + r.id)} style={{
              width: '100%', textAlign: 'left',
              background: PM4.surface, border: `0.5px solid ${PM4.lineSoft}`,
              borderRadius: 12, padding: 14, marginBottom: 8,
              cursor: 'pointer', fontFamily: 'inherit',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ fontFamily: TM4.sans, fontSize: 9, color: PM4.muted, letterSpacing: '0.18em', textTransform: 'uppercase' }}>{r.id}</span>
                <MAdminPill tone={tones[r.status]}>{r.status}</MAdminPill>
              </div>
              <div style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 6, lineHeight: 1.2 }}>{r.guest}</div>
              <div style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted, marginTop: 2 }}>{p?.name}</div>
              <div style={{
                display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
                marginTop: 10, paddingTop: 10, borderTop: `0.5px solid ${PM4.lineSoft}`,
              }}>
                <span style={{ fontFamily: TM4.sans, fontSize: 12, color: PM4.muted }}>{r.dates}</span>
                <span style={{ fontFamily: TM4.sans, fontSize: 13, color: PM4.ink, fontWeight: 500 }}>${r.total}</span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// ADMIN RESERVATION DETAIL
// ═══════════════════════════════════════════════════════════════════════
function MAdminResDetail({ resId, go }) {
  const props = window.DyraStore?.state?.properties || window.DYRA?.PROPERTIES || [];
  const p = props.find(x => x.id === 'ep-4br-2ba') || props[0];
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PM4.bg }}>
      <MAppBar scrolled title={resId || 'DYR-26-0844'} leading={<MIconBtn onClick={() => go('admin-reservations')} label="Back"><MIco name="back" size={22}/></MIconBtn>}/>
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 16px 24px' }}>
        <MAdminCard padding={16}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <MAdminPill tone="ok">Confirmed</MAdminPill>
            <MAdminPill tone="accent">Mobile</MAdminPill>
          </div>
          <div style={{ fontFamily: TM4.serif, fontSize: 22, color: PM4.ink, fontWeight: 500, marginTop: 10, lineHeight: 1.15 }}>Goldberg family</div>
          <div style={{ fontFamily: TM4.sans, fontSize: 12, color: PM4.muted, marginTop: 4 }}>{p.name}</div>
          <div style={{ marginTop: 16, padding: '12px 0 0', borderTop: `0.5px solid ${PM4.lineSoft}`, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <div style={{ fontFamily: TM4.sans, fontSize: 10, color: PM4.muted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Check-in</div>
              <div style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 2 }}>May 8</div>
            </div>
            <div>
              <div style={{ fontFamily: TM4.sans, fontSize: 10, color: PM4.muted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Check-out</div>
              <div style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 2 }}>May 11</div>
            </div>
            <div>
              <div style={{ fontFamily: TM4.sans, fontSize: 10, color: PM4.muted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Guests</div>
              <div style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 2 }}>4 + 2</div>
            </div>
            <div>
              <div style={{ fontFamily: TM4.sans, fontSize: 10, color: PM4.muted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Total</div>
              <div style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 2 }}>$1,925</div>
            </div>
          </div>
        </MAdminCard>

        <h3 style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 24, marginBottom: 8 }}>Contact</h3>
        <MAdminCard padding={0}>
          {[
            ['Phone', '+1 (845) 555-0184', 'phone'],
            ['Email', 'goldberg@example.com', 'mail'],
            ['WhatsApp', '+1 (845) 555-0184', 'whatsapp'],
          ].map((row, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '14px 16px', borderBottom: i < 2 ? `0.5px solid ${PM4.lineSoft}` : 'none',
            }}>
              <span style={{ color: PM4.accent }}><MIco name={row[2]} size={18}/></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted }}>{row[0]}</div>
                <div style={{ fontFamily: TM4.sans, fontSize: 14, color: PM4.ink, marginTop: 1 }}>{row[1]}</div>
              </div>
              <MIco name="forward" size={16} color={PM4.muted}/>
            </div>
          ))}
        </MAdminCard>

        <h3 style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 24, marginBottom: 8 }}>Kosher prefs</h3>
        <MAdminCard padding={14}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {['Cholov Yisroel', 'Glatt / Chalak', 'Pas Yisroel'].map(t => (
              <span key={t} style={{
                padding: '5px 10px', borderRadius: 100, background: PM4.card,
                fontFamily: TM4.sans, fontSize: 11, color: PM4.ink,
                border: `0.5px solid ${PM4.line}`,
              }}>{t}</span>
            ))}
          </div>
          <p style={{ fontFamily: TM4.sans, fontSize: 12, color: PM4.muted, marginTop: 12, lineHeight: 1.5, fontStyle: 'italic' }}>
            "Coming in for our daughter's sheva brachos, late Friday arrival around 2:30pm please."
          </p>
        </MAdminCard>

        <h3 style={{ fontFamily: TM4.serif, fontSize: 16, color: PM4.ink, fontWeight: 500, marginTop: 24, marginBottom: 8 }}>Quick actions</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {['Send check-in code', 'Modify dates', 'Refund deposit', 'Cancel reservation'].map((l, i) => (
            <button key={i} style={{
              padding: '14px 16px', borderRadius: 12,
              background: PM4.surface, border: `0.5px solid ${PM4.line}`,
              fontFamily: TM4.sans, fontSize: 14,
              color: l.startsWith('Cancel') ? PM4.danger : PM4.ink,
              textAlign: 'left',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              cursor: 'pointer',
            }}>
              <span>{l}</span>
              <MIco name="forward" size={16} color={PM4.muted}/>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// ADMIN INQUIRIES
// ═══════════════════════════════════════════════════════════════════════
function MAdminInquiries({ go, openMenu }) {
  const [open, setOpen] = React.useState(null);
  const store = window.DyraStore && window.DyraStore.useStore ? window.DyraStore.useStore() : (window.DyraStore?.state || { inquiries: [] });
  const sourceLabel = (s) => ({
    'list-your-home': 'List your home',
    'contact-form':   'Site form',
    'listing-inquiry':'Listing inquiry',
    'email':          'Email',
    'whatsapp':       'WhatsApp',
    'phone':          'Phone',
  }[s] || (s ? s : 'Site form'));
  const relTime = (iso) => {
    if (!iso) return '';
    const d = new Date(iso); if (isNaN(d.getTime())) return '';
    const diff = Date.now() - d.getTime();
    const mins = Math.round(diff / 60000);
    if (mins < 1) return 'just now';
    if (mins < 60) return mins + 'm ago';
    const hrs = Math.round(mins / 60);
    if (hrs < 24) return hrs + 'h ago';
    const days = Math.round(hrs / 24);
    if (days < 7) return days + 'd ago';
    return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  };
  const inquiries = (store.inquiries || []).map((i) => ({
    id: i.id,
    name: i.name || 'Anonymous',
    from: sourceLabel(i.source),
    time: relTime(i.receivedAt),
    preview: ((i.notes || i.body || '').replace(/\s+/g, ' ').slice(0, 90)) + ((i.notes || i.body || '').length > 90 ? '…' : ''),
    status: i.status === 'new' ? 'new' : 'replied',
    body: i.notes || i.body || '',
  }));
  if (open) {
    const i = inquiries.find(x => x.id === open);
    if (!i) { setOpen(null); return null; }
    return <MAdminInquiryDetail inquiry={i} onBack={() => setOpen(null)}/>;
  }
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PM4.bg }}>
      <MAppBar scrolled title="Inquiries" leading={<MIconBtn onClick={openMenu} label="Menu"><MIco name="menu" size={22}/></MIconBtn>}/>
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 16px 24px' }}>
        {inquiries.length === 0 && (
          <div style={{ padding: 32, textAlign: 'center', color: PM4.muted, fontFamily: TM4.sans, fontSize: 13 }}>
            No inquiries at this time.
          </div>
        )}
        {inquiries.map(i => (
          <button key={i.id} onClick={() => setOpen(i.id)} style={{
            width: '100%', textAlign: 'left',
            background: PM4.surface, border: `0.5px solid ${PM4.lineSoft}`,
            borderRadius: 12, padding: 14, marginBottom: 8,
            cursor: 'pointer', fontFamily: 'inherit',
            position: 'relative',
          }}>
            {i.status === 'new' && (
              <span style={{ position: 'absolute', top: 14, right: 14, width: 8, height: 8, borderRadius: 4, background: PM4.accent }}/>
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 18, background: PM4.accentSoft,
                color: PM4.accentDark,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: TM4.serif, fontSize: 14, fontWeight: 600,
              }}>{(i.name && i.name[0]) || '?'}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: TM4.sans, fontSize: 14, color: PM4.ink, fontWeight: 500 }}>{i.name}</div>
                <div style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted, marginTop: 1 }}>{i.from} · {i.time}</div>
              </div>
            </div>
            <div style={{ fontFamily: TM4.sans, fontSize: 13, color: PM4.inkSoft, marginTop: 8, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
              {i.preview}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function MAdminInquiryDetail({ inquiry, onBack }) {
  const [reply, setReply] = React.useState('');
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PM4.bg }}>
      <MAppBar scrolled title={inquiry.name} leading={<MIconBtn onClick={onBack} label="Back"><MIco name="back" size={22}/></MIconBtn>}/>
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 16px 16px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 0 12px' }}>
          <MAdminPill tone="accent">{inquiry.from}</MAdminPill>
          <span style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted }}>{inquiry.time}</span>
        </div>
        <MAdminCard>
          <p style={{ fontFamily: TM4.sans, fontSize: 14, lineHeight: 1.55, color: PM4.ink, margin: 0, whiteSpace: 'pre-line' }}>
            {inquiry.body}
          </p>
        </MAdminCard>

        <h3 style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 24, marginBottom: 8 }}>Quick replies</h3>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {[
            'Available, sending link',
            'Sorry, booked',
            'Need more info',
            'Pesach kashering yes',
          ].map(t => (
            <button key={t} onClick={() => setReply(t === 'Pesach kashering yes' ? "Yes — we kasher the kitchen for Pesach as a turnkey add-on. The 1.5 baths suite is the right fit at 8 people. I'll send dates + total in the next message." : t)} style={{
              padding: '8px 12px', borderRadius: 100,
              background: PM4.card, border: `0.5px solid ${PM4.line}`,
              fontFamily: TM4.sans, fontSize: 12, color: PM4.ink, cursor: 'pointer',
            }}>{t}</button>
          ))}
        </div>
      </div>

      <div style={{ padding: '8px 12px 16px', borderTop: `0.5px solid ${PM4.line}`, background: PM4.bg, display: 'flex', alignItems: 'flex-end', gap: 8 }}>
        <textarea
          value={reply}
          onChange={(e) => setReply(e.target.value)}
          placeholder="Write a reply…"
          rows={2}
          style={{
            flex: 1, padding: 12, borderRadius: 18,
            border: `1px solid ${PM4.line}`, background: PM4.surface,
            fontFamily: TM4.sans, fontSize: 14, color: PM4.ink,
            resize: 'none', outline: 'none', boxSizing: 'border-box',
          }}/>
        <button style={{
          width: 44, height: 44, borderRadius: 22, border: 'none',
          background: PM4.accent, color: '#fff', cursor: 'pointer', flexShrink: 0,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/>
          </svg>
        </button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════
// ADMIN LISTINGS
// ═══════════════════════════════════════════════════════════════════════
function MAdminListings({ go, openMenu }) {
  const props = window.DyraStore?.state?.properties || window.DYRA?.PROPERTIES || [];
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: PM4.bg }}>
      <MAppBar scrolled title="Listings" leading={<MIconBtn onClick={openMenu} label="Menu"><MIco name="menu" size={22}/></MIconBtn>}
        trailing={<MIconBtn label="Add"><MIco name="plus" size={22}/></MIconBtn>}/>
      <div style={{ flex: 1, overflow: 'auto', padding: '8px 16px 24px' }}>
        <div style={{ fontFamily: TM4.sans, fontSize: 12, color: PM4.muted, padding: '4px 4px 12px' }}>{props.length} active homes</div>
        {props.map(p => (
          <MAdminCard key={p.id} padding={0} style={{ marginBottom: 10 }}>
            <div style={{ display: 'flex', gap: 12, padding: 12, alignItems: 'center' }}>
              <MPhoto property={p} idx={0} style={{ width: 72, height: 72, borderRadius: 8, flexShrink: 0 }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: TM4.serif, fontSize: 14, color: PM4.ink, fontWeight: 500, lineHeight: 1.2 }}>{p.name}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
                  <MAdminPill tone="ok">Active</MAdminPill>
                  <span style={{ fontFamily: TM4.sans, fontSize: 11, color: PM4.muted }}>${p.priceFrom}/n</span>
                </div>
              </div>
              <MIco name="forward" size={18} color={PM4.muted}/>
            </div>
            <div style={{
              display: 'flex', borderTop: `0.5px solid ${PM4.lineSoft}`,
            }}>
              <button style={{ flex: 1, padding: '10px 0', background: 'transparent', border: 'none', borderRight: `0.5px solid ${PM4.lineSoft}`, fontFamily: TM4.sans, fontSize: 11, color: PM4.ink, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4 }}>
                <MIco name="calendar" size={13}/> Block dates
              </button>
              <button style={{ flex: 1, padding: '10px 0', background: 'transparent', border: 'none', borderRight: `0.5px solid ${PM4.lineSoft}`, fontFamily: TM4.sans, fontSize: 11, color: PM4.ink, cursor: 'pointer' }}>
                Edit price
              </button>
              <button style={{ flex: 1, padding: '10px 0', background: 'transparent', border: 'none', fontFamily: TM4.sans, fontSize: 11, color: PM4.ink, cursor: 'pointer' }}>
                View
              </button>
            </div>
          </MAdminCard>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { MAdminToday, MAdminReservations, MAdminResDetail, MAdminInquiries, MAdminListings });
