// ── Agent: Manage Listings dashboard + My Requests ───────────────
const { Icon, Photo, FormScreen, PrimaryBtn, Segmented, fmtPrice, CATEGORIES } = window;

function statFor(l) {
  const seed = [...l.id].reduce((a, c) => a + c.charCodeAt(0), 0);
  return {
    views: 120 + (seed * 7) % 720,
    saves: 6 + (seed * 3) % 58,
    inq: 1 + seed % 11,
  };
}

function StatCard({ value, label, icon }) {
  return (
    <div style={{ flex: 1, padding: '14px 14px', borderRadius: 14, border: '1px solid var(--line)',
      background: 'var(--surface)' }}>
      <Icon name={icon} size={18} s="var(--accent)" />
      <div style={{ marginTop: 8, fontFamily: 'var(--sans)', fontSize: 22, fontWeight: 700, letterSpacing: -0.5,
        color: 'var(--ink)' }}>{value}</div>
      <div style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--muted)' }}>{label}</div>
    </div>
  );
}

function StatusBadge({ status }) {
  const map = {
    Active: ['var(--accent)', 'var(--accent-soft)'],
    Pending: ['oklch(0.55 0.12 70)', 'oklch(0.95 0.05 80)'],
    Paused: ['var(--muted)', 'oklch(0.94 0.004 95)'],
  };
  const [c, bg] = map[status] || map.Active;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 24, padding: '0 9px',
      borderRadius: 999, background: bg, fontFamily: 'var(--sans)', fontSize: 11.5, fontWeight: 600, color: c }}>
      <span style={{ width: 6, height: 6, borderRadius: 9, background: c }} />{status}</span>
  );
}

function ManageRow({ l, onOpen, onAction }) {
  const s = statFor(l);
  const Stat = ({ icon, n }) => (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
      <Icon name={icon} size={15} s="var(--muted)" sw={1.7} />
      <span style={{ fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{n}</span></span>
  );
  const Action = ({ icon, label, onClick, danger }) => (
    <button onClick={onClick} style={{ flex: 1, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      gap: 6, height: 38, border: 'none', cursor: 'pointer', background: 'transparent', fontFamily: 'var(--sans)',
      fontSize: 13, fontWeight: 600, color: danger ? 'var(--muted)' : 'var(--ink)' }}>
      <Icon name={icon} size={16} s={danger ? 'var(--muted)' : 'var(--ink)'} sw={1.8} />{label}</button>
  );
  return (
    <div style={{ borderRadius: 16, border: '1px solid var(--line)', background: 'var(--surface)', overflow: 'hidden' }}>
      <div onClick={() => onOpen(l.id)} style={{ display: 'flex', gap: 13, padding: 12, cursor: 'pointer' }}>
        <div style={{ position: 'relative', width: 92, height: 92, borderRadius: 12, overflow: 'hidden', flexShrink: 0 }}>
          <Photo hue={l.hue} label={false} />
          {l.video && <span style={{ position: 'absolute', bottom: 6, left: 6, width: 22, height: 22, borderRadius: 999,
            background: 'rgba(20,20,18,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="play" size={10} s="#fff" fill="#fff" /></span>}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 18, fontWeight: 700, letterSpacing: -0.4,
              color: 'var(--ink)' }}>{fmtPrice(l)}</span>
            <StatusBadge status={l.status || 'Active'} />
          </div>
          <div style={{ marginTop: 3, fontFamily: 'var(--sans)', fontSize: 13.5, fontWeight: 500, color: 'var(--ink)',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{l.address}</div>
          <div style={{ marginTop: 1, fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--muted)' }}>{l.hood}</div>
          <div style={{ marginTop: 9, display: 'flex', gap: 14 }}>
            <Stat icon="eye" n={s.views} /><Stat icon="heart" n={s.saves} /><Stat icon="msg" n={s.inq} />
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', borderTop: '1px solid var(--line)' }}>
        <Action icon="edit" label="Edit" onClick={() => onAction('edit', l)} />
        <div style={{ width: 1, background: 'var(--line)' }} />
        <Action icon="sparkle" label="Promote" onClick={() => onAction('promote', l)} />
        <div style={{ width: 1, background: 'var(--line)' }} />
        <Action icon="pause" label="Pause" onClick={() => onAction('pause', l)} danger />
      </div>
    </div>
  );
}

function ManageListings({ listings, onBack, onOpen, onNew }) {
  const [tab, setTab] = React.useState('active');
  // demo statuses
  const withStatus = listings.map((l, i) => ({ ...l, status: l.status || (i % 5 === 3 ? 'Pending' : 'Active') }));
  const shown = tab === 'all' ? withStatus : withStatus.filter(l => (l.status || 'Active').toLowerCase() === tab);
  const totalViews = withStatus.reduce((a, l) => a + statFor(l).views, 0);
  const totalInq = withStatus.reduce((a, l) => a + statFor(l).inq, 0);

  return (
    <FormScreen title="Manage listings" onBack={onBack} action="+ New" onAction={onNew}
      footer={<PrimaryBtn icon="plus" onClick={onNew}>New listing</PrimaryBtn>}>
      <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
        <StatCard value={withStatus.filter(l => l.status === 'Active').length} label="Active" icon="chart" />
        <StatCard value={totalViews.toLocaleString()} label="Views · 30d" icon="eye" />
        <StatCard value={totalInq} label="Inquiries" icon="msg" />
      </div>

      <div style={{ marginTop: 18 }}>
        <Segmented options={[['active', 'Active'], ['pending', 'Pending'], ['all', 'All']]} value={tab} onChange={setTab} />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 18 }}>
        {shown.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 20px', fontFamily: 'var(--sans)', fontSize: 14,
            color: 'var(--muted)' }}>No {tab} listings.</div>
        ) : shown.map(l => <ManageRow key={l.id} l={l} onOpen={onOpen} onAction={() => {}} />)}
      </div>
      <div style={{ height: 8 }} />
    </FormScreen>
  );
}

// ── My Requests ──────────────────────────────────────────────────
function RequestCard({ r }) {
  const cat = CATEGORIES.find(c => c.id === r.cat) || { label: 'Property', icon: 'house' };
  return (
    <div style={{ borderRadius: 16, border: '1px solid var(--line)', background: 'var(--surface)', padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 12 }}>
        <span style={{ width: 40, height: 40, borderRadius: 11, flexShrink: 0, display: 'flex', alignItems: 'center',
          justifyContent: 'center', background: 'var(--accent-soft)' }}>
          <Icon name={cat.icon} size={21} s="var(--accent)" /></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 15.5, fontWeight: 700, color: 'var(--ink)',
            letterSpacing: -0.2 }}>{r.deal === 'rent' ? 'Renting' : 'Buying'} · {cat.label}</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--muted)' }}>{r.created}</div>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 24, padding: '0 9px',
          borderRadius: 999, background: 'var(--accent-soft)', fontFamily: 'var(--sans)', fontSize: 11.5,
          fontWeight: 600, color: 'var(--accent)' }}>
          <span style={{ width: 6, height: 6, borderRadius: 9, background: 'var(--accent)' }} />{r.status}</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 8px', marginBottom: 12 }}>
        {[['Area', r.area], ['Budget', r.budget], r.beds ? ['Beds · baths', `${r.beds} · ${r.baths}`] : null,
          ['Move-in', r.when]].filter(Boolean).map(([k, v]) => (
          <div key={k}>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 9.5, letterSpacing: 0.5, textTransform: 'uppercase',
              color: 'var(--muted)' }}>{k}</div>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginTop: 2 }}>{v}</div>
          </div>
        ))}
      </div>

      {r.note && <p style={{ margin: '0 0 12px', fontFamily: 'var(--sans)', fontSize: 13.5, lineHeight: 1.5,
        color: 'var(--muted)', textWrap: 'pretty' }}>{r.note}</p>}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 12,
        borderTop: '1px solid var(--line)' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--sans)', fontSize: 13.5,
          fontWeight: 600, color: 'var(--ink)' }}>
          <Icon name="sparkle" size={16} s="var(--accent)" />{r.matches} {r.matches === 1 ? 'match' : 'matches'}</span>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={{ height: 36, padding: '0 14px', borderRadius: 999, border: '1.5px solid var(--line)',
            background: 'var(--surface)', cursor: 'pointer', fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600,
            color: 'var(--ink)' }}>Edit</button>
          <button style={{ height: 36, padding: '0 14px', borderRadius: 999, border: 'none', background: 'var(--ink)',
            color: 'var(--bg)', cursor: 'pointer', fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600 }}>
            View matches</button>
        </div>
      </div>
    </div>
  );
}

function MyRequests({ requests, onBack, onNew }) {
  return (
    <FormScreen title="My requests" onBack={onBack} action="+ New" onAction={onNew}
      footer={<PrimaryBtn icon="plus" onClick={onNew}>Post a request</PrimaryBtn>}>
      {requests.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '70px 40px' }}>
          <div style={{ width: 64, height: 64, borderRadius: 999, background: 'var(--accent-soft)', display: 'flex',
            alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
            <Icon name="search" size={28} s="var(--accent)" /></div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>No requests yet</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--muted)', marginTop: 4, maxWidth: 250,
            marginInline: 'auto' }}>Tell agents what you're after and let the right homes come to you.</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginTop: 16 }}>
          {requests.map(r => <RequestCard key={r.id} r={r} />)}
        </div>
      )}
      <div style={{ height: 8 }} />
    </FormScreen>
  );
}

Object.assign(window, { ManageListings, MyRequests });
