// screens-user2.jsx — Dashboard, Browse, Saved
const { useState: u2State, useMemo: u2Memo } = React;

function SectionHead({ title, sub, action }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 16 }}>
      <div>
        <h2 style={{ fontSize: 21 }}>{title}</h2>
        {sub && <p style={{ color: 'var(--ink-2)', fontSize: 13.5, marginTop: 4 }}>{sub}</p>}
      </div>
      {action}
    </div>
  );
}

function StatCard({ icon, label, value, foot, accent }) {
  return (
    <Card style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ width: 38, height: 38, borderRadius: 'var(--r-sm)', display: 'grid', placeItems: 'center', background: accent ? 'var(--brand)' : 'var(--brand-soft)', color: accent ? '#fff' : 'var(--brand)' }}>
          <Icon name={icon} size={19} />
        </span>
        {foot && <span style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 600 }}>{foot}</span>}
      </div>
      <div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 600, lineHeight: 1 }}>{value}</div>
        <div style={{ color: 'var(--ink-2)', fontSize: 13, marginTop: 6 }}>{label}</div>
      </div>
    </Card>
  );
}

/* ============ DASHBOARD ============ */
function UserDashboard(ctx) {
  const { data, user, saved, toggleSave, openProp, requests, navigate, userId, fresh } = ctx;
  const myReqs = requests.filter(r => r.userId === userId);
  const savedProps = data.PROPERTIES.filter(p => saved.has(p.id));
  const nextInspection = myReqs.find(r => r.kind === 'Inspection' && ['Approved', 'Scheduled'].includes(r.status)) || myReqs.find(r => r.kind === 'Inspection');
  const nextProp = nextInspection && data.PROPERTIES.find(p => p.id === nextInspection.propId);
  const recommended = data.PROPERTIES.filter(p => !saved.has(p.id)).slice(0, 3);
  const hour = 14;
  const greet = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 30 }}>
      {/* greeting */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, color: 'var(--brand)', fontSize: 13, fontWeight: 600 }}>
            <Icon name="shield" size={15} /> Verified member
          </div>
          <h1 style={{ fontSize: 32 }}>{greet}, {user.name.split(' ')[0]}.</h1>
          <p style={{ color: 'var(--ink-2)', fontSize: 15 }}>Here's what's moving across your properties today.</p>
        </div>
        <Button size="lg" icon="search" onClick={() => navigate('browse')}>Browse properties</Button>
      </div>

      {/* stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 'var(--gap)' }}>
        <StatCard icon="heart" label="Saved properties" value={savedProps.length} foot="Portfolio" />
        <StatCard icon="calendar" label="Active requests" value={myReqs.filter(r => r.status !== 'Completed').length} foot="In progress" accent />
        <StatCard icon="message" label="Unread messages" value={fresh ? 0 : 1} foot="Concierge" />
        <StatCard icon="checkCircle" label="Next inspection" value={nextInspection ? new Date(nextInspection.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' }) : '—'} foot={nextInspection ? nextInspection.slot : ''} />
      </div>

      {/* next inspection — hero */}
      {nextInspection && nextProp && (
        <Card pad={false} style={{ overflow: 'hidden' }}>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', gap: 0, flexWrap: 'wrap' }}>
              <div style={{ flex: '1 1 320px' }}>
                <div style={{ padding: 'calc(var(--pad) + 6px)', display: 'flex', flexDirection: 'column', gap: 16 }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
                    <span style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Your next inspection</span>
                    <StatusPill status={nextInspection.status} />
                  </div>
                  <div>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600 }}>{nextProp.title}</div>
                    <div style={{ display: 'flex', gap: 16, color: 'var(--ink-2)', fontSize: 13.5, marginTop: 8, flexWrap: 'wrap' }}>
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="pin" size={15} /> {nextProp.city}, {nextProp.country}</span>
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="calendar" size={15} /> {new Date(nextInspection.date).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'long' })}</span>
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="clock" size={15} /> {nextInspection.slot}</span>
                    </div>
                  </div>
                  <div style={{ background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', padding: '16px 18px', border: '1px solid var(--line)' }}>
                    <StatusTimeline status={nextInspection.status} />
                  </div>
                  <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                    <Button variant="soft" icon="list" onClick={() => navigate('requests')}>Track request</Button>
                    <Button variant="ghost" icon="message" onClick={() => navigate('messages')}>Message concierge</Button>
                  </div>
                </div>
              </div>
              <div style={{ flex: '1 1 240px', minWidth: 200 }}>
                <PropImage hue={nextProp.hue} label={nextProp.label} height="100%" radius="0" />
              </div>
            </div>
          </div>
        </Card>
      )}

      {/* saved */}
      <div>
        <SectionHead title="Saved properties" sub={savedProps.length ? `${savedProps.length} in your portfolio` : 'Nothing saved yet'} action={savedProps.length > 0 && <Button variant="ghost" size="sm" iconRight="arrowRight" onClick={() => navigate('saved')}>View all</Button>} />
        {savedProps.length === 0 ? (
          <Card><EmptyState icon="heart" title="No saved properties" body="Tap the heart on any listing to keep it here for easy access." action={<Button size="sm" onClick={() => navigate('browse')}>Browse now</Button>} /></Card>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(248px, 1fr))', gap: 'var(--gap)' }}>
            {savedProps.slice(0, 3).map(p => <PropertyCard key={p.id} p={p} saved onSave={() => toggleSave(p.id)} onOpen={() => openProp(p)} compact />)}
          </div>
        )}
      </div>

      {/* recommended */}
      <div>
        <SectionHead title="Recommended for you" sub="Based on your saved residences and recent inspections" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(248px, 1fr))', gap: 'var(--gap)' }}>
          {recommended.map(p => <PropertyCard key={p.id} p={p} saved={saved.has(p.id)} onSave={() => toggleSave(p.id)} onOpen={() => openProp(p)} compact />)}
        </div>
      </div>
    </div>
  );
}

/* ============ BROWSE ============ */
function BrowseScreen(ctx) {
  const { data, saved, toggleSave, openProp } = ctx;
  const [q, setQ] = u2State('');
  const [type, setType] = u2State('All');
  const [sort, setSort] = u2State('featured');

  const types = ['All', 'Residential', 'Commercial', 'Land', 'Short-let', 'Development'];
  const list = u2Memo(() => {
    let l = data.PROPERTIES.filter(p =>
      (type === 'All' || p.type === type) &&
      (q === '' || (p.title + p.city + p.country + p.type).toLowerCase().includes(q.toLowerCase()))
    );
    if (sort === 'price-asc') l = [...l].sort((a, b) => a.price - b.price);
    if (sort === 'price-desc') l = [...l].sort((a, b) => b.price - a.price);
    return l;
  }, [q, type, sort, data]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <h1 style={{ fontSize: 30 }}>Browse properties</h1>
        <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>{list.length} listings across the UK &amp; Europe</p>
      </div>

      {/* filter bar */}
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ position: 'relative', flex: '1 1 260px', minWidth: 200 }}>
          <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 city, type or name…" style={{ paddingLeft: 40 }} />
        </div>
        <Select value={sort} onChange={setSort} options={[{ value: 'featured', label: 'Featured first' }, { value: 'price-asc', label: 'Price: low to high' }, { value: 'price-desc', label: 'Price: high to low' }]} style={{ width: 'auto', minWidth: 180 }} />
      </div>
      <div style={{ overflowX: 'auto', paddingBottom: 2 }}>
        <Segmented options={types} value={type} onChange={setType} />
      </div>

      {list.length === 0 ? (
        <Card><EmptyState icon="search" title="No matches" body="Try a different type or clear your search." /></Card>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(268px, 1fr))', gap: 'var(--gap)' }}>
          {list.map(p => <PropertyCard key={p.id} p={p} saved={saved.has(p.id)} onSave={() => toggleSave(p.id)} onOpen={() => openProp(p)} />)}
        </div>
      )}
    </div>
  );
}

/* ============ SAVED ============ */
function SavedScreen(ctx) {
  const { data, saved, toggleSave, openProp, navigate } = ctx;
  const savedProps = data.PROPERTIES.filter(p => saved.has(p.id));
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <h1 style={{ fontSize: 30 }}>Saved properties</h1>
        <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>{savedProps.length} residences in your portfolio</p>
      </div>
      {savedProps.length === 0 ? (
        <Card><EmptyState icon="heart" title="Your portfolio is empty" body="Save listings from Browse to compare them here and request inspections." action={<Button onClick={() => navigate('browse')} icon="search">Browse properties</Button>} /></Card>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(268px, 1fr))', gap: 'var(--gap)' }}>
          {savedProps.map(p => <PropertyCard key={p.id} p={p} saved onSave={() => toggleSave(p.id)} onOpen={() => openProp(p)} />)}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { SectionHead, StatCard, UserDashboard, BrowseScreen, SavedScreen });
