// screens-admin.jsx — Admin engagement dashboard, requests review, users, messages
const { useState: aState } = React;

function KpiCard({ icon, label, value, delta, deltaUp = true }) {
  return (
    <Card style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ color: 'var(--ink-3)', fontSize: 13, fontWeight: 600 }}>{label}</span>
        <span style={{ color: 'var(--brand)' }}><Icon name={icon} size={18} /></span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 600, lineHeight: 1 }}>{value}</div>
        {delta && (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 12.5, fontWeight: 600, color: deltaUp ? 'var(--ok)' : 'var(--danger)' }}>
            <Icon name="trending" size={13} /> {delta}
          </span>
        )}
      </div>
    </Card>
  );
}

/* ============ ADMIN DASHBOARD ============ */
function AdminDashboard(ctx) {
  const { data, requests, navigate, advanceRequest } = ctx;
  const open = requests.filter(r => ['Pending', 'In review'].includes(r.status));
  const bars = [42, 58, 49, 71, 63, 88, 76];
  const days = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
  const maxBar = Math.max(...bars);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 26 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontSize: 30 }}>Engagement overview</h1>
          <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>Monday, 15 June 2026 · all regions</p>
        </div>
        <Segmented options={['7 days', '30 days', 'Quarter']} value="7 days" onChange={() => {}} size="sm" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', gap: 'var(--gap)' }}>
        <KpiCard icon="users" label="Total members" value={data.USERS.length} delta="+2 this week" />
        <KpiCard icon="shield" label="Verified" value={data.USERS.filter(u => u.verified).length} delta="71%" />
        <KpiCard icon="calendar" label="Open requests" value={open.length} delta="needs action" deltaUp={false} />
        <KpiCard icon="heart" label="Saves this week" value={22} delta="+18%" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.5fr) minmax(0,1fr)', gap: 'var(--gap)' }} className="admin-cols">
        {/* left */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
          {/* requests needing action */}
          <Card pad={false} style={{ overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: 'var(--pad)', borderBottom: '1px solid var(--line)' }}>
              <h3 style={{ fontSize: 17 }}>Requests needing action</h3>
              <Button variant="ghost" size="sm" iconRight="arrowRight" onClick={() => navigate('requests')}>Open queue</Button>
            </div>
            <div>
              {open.length === 0 ? (
                <EmptyState icon="checkCircle" title="All clear" body="No requests are waiting on you right now." />
              ) : open.map((r, i) => {
                const p = data.PROPERTIES.find(x => x.id === r.propId);
                return (
                  <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: 'var(--pad)', borderTop: i ? '1px solid var(--line)' : 'none' }}>
                    <Avatar name={r.user} size={38} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600 }}>{r.user}</div>
                      <div style={{ color: 'var(--ink-2)', fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                        {r.kind} · {p.title}
                      </div>
                    </div>
                    <StatusPill status={r.status} size="sm" />
                    <Button variant="soft" size="sm" onClick={() => advanceRequest(r.id, 'Approved')}>Approve</Button>
                  </div>
                );
              })}
            </div>
          </Card>

          {/* activity feed */}
          <Card pad={false}>
            <div style={{ padding: 'var(--pad)', borderBottom: '1px solid var(--line)' }}><h3 style={{ fontSize: 17 }}>Recent activity</h3></div>
            <div style={{ padding: '6px var(--pad) var(--pad)' }}>
              {data.ACTIVITY.map((a, i) => {
                const iconMap = { Lease: 'key', Inspection: 'calendar', Save: 'heart', Message: 'message', Verify: 'shield' };
                return (
                  <div key={i} style={{ display: 'flex', gap: 13, padding: '12px 0', borderBottom: i < data.ACTIVITY.length - 1 ? '1px solid var(--line)' : 'none', alignItems: 'center' }}>
                    <span style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--brand-soft)', color: 'var(--brand)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={iconMap[a.kind]} size={16} /></span>
                    <div style={{ flex: 1, fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.45 }}>
                      <strong style={{ color: 'var(--ink)' }}>{a.who}</strong> {a.act} {a.obj && <strong style={{ color: 'var(--ink)' }}>{a.obj}</strong>}
                    </div>
                    <span style={{ color: 'var(--ink-3)', fontSize: 12, whiteSpace: 'nowrap' }}>{a.time}</span>
                  </div>
                );
              })}
            </div>
          </Card>
        </div>

        {/* right */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
          {/* engagement chart */}
          <Card style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div>
              <h3 style={{ fontSize: 17 }}>Engagement this week</h3>
              <p style={{ color: 'var(--ink-3)', fontSize: 13, marginTop: 4 }}>Daily active members</p>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 130 }}>
              {bars.map((b, i) => (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, height: '100%', justifyContent: 'flex-end' }}>
                  <div style={{ width: '100%', height: `${(b / maxBar) * 100}%`, background: i === bars.length - 2 ? 'var(--brand)' : 'var(--brand-soft)', borderRadius: 'var(--r-sm)', transition: 'height .4s ease', minHeight: 4 }} title={`${b}`} />
                  <span style={{ fontSize: 11.5, color: 'var(--ink-3)', fontWeight: 600 }}>{days[i]}</span>
                </div>
              ))}
            </div>
          </Card>

          {/* request breakdown */}
          <Card style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <h3 style={{ fontSize: 17 }}>Requests by type</h3>
            {[
              { label: 'Inspections', n: requests.filter(r => r.kind === 'Inspection').length, c: 'var(--brand)' },
              { label: 'Lease / lettings', n: requests.filter(r => r.kind === 'Lease').length, c: 'var(--accent)' },
            ].map(row => {
              const total = requests.length || 1;
              return (
                <div key={row.label} style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}>
                    <span style={{ color: 'var(--ink-2)' }}>{row.label}</span>
                    <strong>{row.n}</strong>
                  </div>
                  <div style={{ height: 8, background: 'var(--surface-3)', borderRadius: 99, overflow: 'hidden' }}>
                    <div style={{ width: `${(row.n / total) * 100}%`, height: '100%', background: row.c, borderRadius: 99 }} />
                  </div>
                </div>
              );
            })}
          </Card>

          {/* new members */}
          <Card pad={false}>
            <div style={{ padding: 'var(--pad)', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h3 style={{ fontSize: 17 }}>New members</h3>
              <Button variant="ghost" size="sm" onClick={() => navigate('users')}>All</Button>
            </div>
            <div style={{ padding: '4px var(--pad) var(--pad)' }}>
              {data.USERS.slice(-3).reverse().map((u, i) => (
                <div key={u.id} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 0', borderBottom: i < 2 ? '1px solid var(--line)' : 'none' }}>
                  <Avatar name={u.name} size={36} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{u.name}</div>
                    <div style={{ color: 'var(--ink-3)', fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.email}</div>
                  </div>
                  {u.verified ? <Tag tone="brand"><Icon name="check" size={11} stroke={3} /> Verified</Tag> : <Tag>Pending</Tag>}
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

/* ============ ADMIN REQUESTS QUEUE (review side of hero flow) ============ */
function AdminRequests(ctx) {
  const { data, requests, advanceRequest, toast } = ctx;
  const [tab, setTab] = aState('All');
  const [openId, setOpenId] = aState(null);
  const tabs = ['All', 'Pending', 'In review', 'Approved', 'Scheduled', 'Completed'];
  const filtered = requests.filter(r => tab === 'All' || r.status === tab);

  const actionsFor = (r) => {
    switch (r.status) {
      case 'Pending': return [['In review', 'Move to review', 'soft'], ['Approved', 'Approve', 'primary'], ['Declined', 'Decline', 'danger']];
      case 'In review': return [['Approved', 'Approve', 'primary'], ['Declined', 'Decline', 'danger']];
      case 'Approved': return [['Scheduled', 'Schedule visit', 'primary']];
      case 'Scheduled': return [['Completed', 'Mark complete', 'primary']];
      default: return [];
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <h1 style={{ fontSize: 30 }}>Request queue</h1>
        <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>Review and progress inspection &amp; lease requests</p>
      </div>
      <div style={{ overflowX: 'auto', paddingBottom: 2 }}>
        <Segmented size="sm" options={tabs.map(t => ({ value: t, label: t, count: t === 'All' ? requests.length : requests.filter(r => r.status === t).length }))} value={tab} onChange={setTab} />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
        {filtered.length === 0 ? <Card><EmptyState icon="inbox" title="Nothing here" body="No requests with this status." /></Card> :
          filtered.map(r => {
            const p = data.PROPERTIES.find(x => x.id === r.propId);
            const expanded = openId === r.id;
            return (
              <Card key={r.id} pad={false} style={{ overflow: 'hidden' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 'var(--pad)', cursor: 'pointer', flexWrap: 'wrap' }} onClick={() => setOpenId(expanded ? null : r.id)}>
                  <Avatar name={r.user} size={42} />
                  <div style={{ flex: '1 1 200px', minWidth: 0 }}>
                    <div style={{ display: 'flex', gap: 9, alignItems: 'center', flexWrap: 'wrap' }}>
                      <span style={{ fontSize: 14.5, fontWeight: 600 }}>{r.user}</span>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--brand-ink)', fontWeight: 600 }}><Icon name={r.kind === 'Inspection' ? 'calendar' : 'key'} size={13} />{r.kind}</span>
                      <span style={{ color: 'var(--ink-3)', fontSize: 12, fontFamily: 'var(--font-mono)' }}>{r.ref}</span>
                    </div>
                    <div style={{ color: 'var(--ink-2)', fontSize: 13, marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.title} · {new Date(r.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}{r.slot !== '—' ? `, ${r.slot}` : ''}</div>
                  </div>
                  <StatusPill status={r.status} />
                  <span style={{ color: 'var(--ink-3)', transition: 'transform .2s', transform: expanded ? 'rotate(180deg)' : 'none' }}><Icon name="chevronDown" size={18} /></span>
                </div>
                {expanded && (
                  <div style={{ padding: '0 var(--pad) var(--pad)', borderTop: '1px solid var(--line)', animation: 'credo-fade .2s ease' }}>
                    <div style={{ paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))', gap: 12 }}>
                        {[['Property', p.title], ['Location', `${p.city}, ${p.country}`], ['Requested', new Date(r.created).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })], ['Preferred', `${new Date(r.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}${r.slot !== '—' ? ` · ${r.slot}` : ''}`]].map(([k, v]) => (
                          <div key={k}><div style={{ fontSize: 11.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>{k}</div><div style={{ fontSize: 14, marginTop: 4, fontWeight: 500 }}>{v}</div></div>
                        ))}
                      </div>
                      {r.note && <div style={{ background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', padding: '12px 15px', fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.5 }}><span style={{ color: 'var(--ink-3)', fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 }}>Note from {r.user.split(' ')[0]}</span>{r.note}</div>}
                      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                        <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>Progress</span>
                        <div style={{ flex: 1 }}><StatusTimeline status={r.status} /></div>
                      </div>
                      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', borderTop: '1px solid var(--line)', paddingTop: 16 }}>
                        {actionsFor(r).map(([st, label, variant]) => (
                          <Button key={st} size="sm" variant={variant} onClick={() => { advanceRequest(r.id, st); toast(`${r.ref} → ${st}`); }}>{label}</Button>
                        ))}
                        <Button size="sm" variant="ghost" icon="message">Message {r.user.split(' ')[0]}</Button>
                        {actionsFor(r).length === 0 && <span style={{ fontSize: 13, color: 'var(--ink-3)', alignSelf: 'center' }}>This request is complete.</span>}
                      </div>
                    </div>
                  </div>
                )}
              </Card>
            );
          })}
      </div>
    </div>
  );
}

/* ============ ADMIN USERS ============ */
function AdminUsers(ctx) {
  const { data } = ctx;
  const [q, setQ] = aState('');
  const users = data.USERS.filter(u => (u.name + u.email).toLowerCase().includes(q.toLowerCase()));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <h1 style={{ fontSize: 30 }}>Members</h1>
        <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>{data.USERS.length} registered · {data.USERS.filter(u => u.verified).length} verified</p>
      </div>
      <div style={{ position: 'relative', maxWidth: 340 }}>
        <span style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)' }}><Icon name="search" size={17} /></span>
        <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search members…" style={{ paddingLeft: 40 }} />
      </div>
      <Card pad={false} style={{ overflow: 'hidden' }}>
        <div className="user-table-head" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 90px 90px 100px', gap: 12, padding: '12px var(--pad)', borderBottom: '1px solid var(--line)', fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
          <span>Member</span><span>Joined</span><span>Saved</span><span>Requests</span><span>Status</span>
        </div>
        {users.map((u, i) => (
          <div key={u.id} className="user-table-row" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 90px 90px 100px', gap: 12, padding: 'var(--pad)', borderTop: i ? '1px solid var(--line)' : 'none', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
              <Avatar name={u.name} size={38} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}>{u.name} {u.verified && <span style={{ color: 'var(--brand)' }} title="Verified"><Icon name="shield" size={14} /></span>}</div>
                <div style={{ color: 'var(--ink-3)', fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.email}</div>
              </div>
            </div>
            <span style={{ fontSize: 13.5, color: 'var(--ink-2)' }}>{new Date(u.joined).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' })}</span>
            <span style={{ fontSize: 14, fontWeight: 600 }}>{u.saved}</span>
            <span style={{ fontSize: 14, fontWeight: 600 }}>{u.requests}</span>
            <span>{u.status === 'Active' ? <Tag tone="brand">Active</Tag> : <Tag>Pending</Tag>}</span>
          </div>
        ))}
      </Card>
    </div>
  );
}

/* ============ ADMIN MESSAGES ============ */
function AdminMessages(ctx) {
  const { data } = ctx;
  const convos = [
    { name: 'Eleanor Whitmore', last: 'Perfect, please confirm. Is the terrace…', time: '10:02', unread: false, prop: 'Ashby Lofts 14B' },
    { name: 'James Okonkwo', last: 'Querying A3 hospitality consent for the…', time: '09:14', unread: true, prop: 'Keizersgracht Retail' },
    { name: 'Priya Nadkarni', last: 'Could we see the meeting suites on the…', time: 'Yesterday', unread: true, prop: 'Northgate Suite' },
    { name: 'Sofia Almeida', last: 'Thank you — the roof terrace was lovely.', time: 'Fri', unread: false, prop: 'Le Marais' },
  ];
  const [active, setActive] = aState(0);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22, height: '100%' }}>
      <div>
        <h1 style={{ fontSize: 30 }}>Conversations</h1>
        <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>Member messages routed to the concierge desk</p>
      </div>
      <Card pad={false} style={{ display: 'flex', overflow: 'hidden', flex: 1, minHeight: 460 }}>
        <div className="convo-list" style={{ width: 300, borderRight: '1px solid var(--line)', overflowY: 'auto', flexShrink: 0 }}>
          {convos.map((c, i) => (
            <div key={i} onClick={() => setActive(i)} style={{ display: 'flex', gap: 11, padding: '14px var(--pad)', borderBottom: '1px solid var(--line)', cursor: 'pointer', background: active === i ? 'var(--surface-2)' : 'transparent', borderLeft: active === i ? '3px solid var(--brand)' : '3px solid transparent' }}>
              <Avatar name={c.name} size={40} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 6 }}>
                  <span style={{ fontSize: 14, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.name}</span>
                  <span style={{ fontSize: 11.5, color: 'var(--ink-3)', flexShrink: 0 }}>{c.time}</span>
                </div>
                <div style={{ color: 'var(--ink-2)', fontSize: 12.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginTop: 2 }}>{c.last}</div>
              </div>
              {c.unread && <span style={{ width: 8, height: 8, borderRadius: 99, background: 'var(--brand)', flexShrink: 0, marginTop: 6 }} />}
            </div>
          ))}
        </div>
        <div className="convo-thread" style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 11 }}>
            <Avatar name={convos[active].name} size={40} />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 15 }}>{convos[active].name}</div>
              <div style={{ color: 'var(--ink-3)', fontSize: 12.5 }}>Re: {convos[active].prop}</div>
            </div>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 14, background: 'var(--surface-2)' }}>
            {window.CREDO.THREAD.map((m, i) => {
              const admin = m.from === 'admin';
              return (
                <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: admin ? 'flex-end' : 'flex-start' }}>
                  <div style={{ maxWidth: '78%', padding: '11px 15px', borderRadius: 16, fontSize: 14, lineHeight: 1.5, background: admin ? 'var(--brand)' : 'var(--surface)', color: admin ? '#fff' : 'var(--ink)', border: admin ? 'none' : '1px solid var(--line)', borderBottomRightRadius: admin ? 4 : 16, borderBottomLeftRadius: admin ? 16 : 4 }}>{m.text}</div>
                  <span style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>{m.time}</span>
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: 10, padding: 14, borderTop: '1px solid var(--line)', alignItems: 'center' }}>
            <Input placeholder="Reply as concierge…" style={{ borderRadius: 99 }} />
            <Button icon="send" style={{ borderRadius: 99, width: 46, padding: 0, flexShrink: 0 }} />
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { AdminDashboard, AdminRequests, AdminUsers, AdminMessages });
