// screens-user3.jsx — PropertyDetail, RequestModal, RequestsView, MessagesScreen
const { useState: u3State } = React;

/* ============ PROPERTY DETAIL ============ */
function PropertyDetail(ctx) {
  const { prop: p, saved, toggleSave, navigate, startRequest, isMobile } = ctx;
  if (!p) return null;
  const isSaved = saved.has(p.id);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <button onClick={() => navigate('browse')} style={{ alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 7, background: 'none', border: 'none', color: 'var(--ink-2)', cursor: 'pointer', fontSize: 14, fontFamily: 'var(--font-body)', padding: 0 }}>
        <Icon name="arrowLeft" size={17} /> Back to browse
      </button>

      {/* gallery */}
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '2fr 1fr', gap: 12 }}>
        <PropImage hue={p.hue} label={p.label} height={isMobile ? 240 : 380} tag={p.tag} saved={isSaved} onSave={() => toggleSave(p.id)} />
        {!isMobile && (
          <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: 12 }}>
            <PropImage hue={p.hue + 14} label="interior" height="100%" />
            <PropImage hue={p.hue - 14} label="floor plan" height="100%" />
          </div>
        )}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.6fr 1fr', gap: 26, alignItems: 'start' }}>
        {/* main */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10, flexWrap: 'wrap' }}>
              <Tag tone="brand">{p.type} · {p.sub}</Tag>
              <span style={{ color: 'var(--ink-3)', fontSize: 13, fontFamily: 'var(--font-mono)' }}>Ref {p.ref}</span>
            </div>
            <h1 style={{ fontSize: isMobile ? 26 : 32 }}>{p.title}</h1>
            <div style={{ display: 'flex', gap: 7, alignItems: 'center', color: 'var(--ink-2)', fontSize: 15, marginTop: 10 }}>
              <Icon name="pin" size={17} /> {p.city}, {p.country}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 0, border: '1px solid var(--line)', borderRadius: 'var(--r)', overflow: 'hidden', background: 'var(--surface)' }}>
            {[
              p.beds > 0 && { icon: 'bed', label: 'Bedrooms', val: p.beds },
              p.baths > 0 && { icon: 'bath', label: 'Bathrooms', val: p.baths },
              { icon: 'ruler', label: 'Area', val: `${p.area.toLocaleString()} ${p.areaUnit}` },
              { icon: 'calendar', label: 'Listed', val: p.listed },
            ].filter(Boolean).map((s, i, arr) => (
              <div key={s.label} style={{ flex: 1, padding: '16px 18px', borderRight: i < arr.length - 1 ? '1px solid var(--line)' : 'none', minWidth: 0 }}>
                <div style={{ color: 'var(--brand)', marginBottom: 8 }}><Icon name={s.icon} size={19} /></div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600 }}>{s.val}</div>
                <div style={{ color: 'var(--ink-3)', fontSize: 12.5, marginTop: 2 }}>{s.label}</div>
              </div>
            ))}
          </div>

          <div>
            <h3 style={{ fontSize: 18, marginBottom: 10 }}>About this {p.sub.toLowerCase()}</h3>
            <p style={{ color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.65, textWrap: 'pretty' }}>{p.blurb}</p>
          </div>

          <div>
            <h3 style={{ fontSize: 18, marginBottom: 12 }}>Features &amp; amenities</h3>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 10 }}>
              {p.features.map(f => (
                <div key={f} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'var(--ink)' }}>
                  <span style={{ width: 24, height: 24, borderRadius: '50%', background: 'var(--brand-soft)', color: 'var(--brand)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name="check" size={13} stroke={3} /></span>
                  {f}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* sticky cta */}
        <div style={{ position: isMobile ? 'static' : 'sticky', top: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>{p.unit ? 'Asking' : 'Guide price'}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 600, marginTop: 4 }}>
                <Money cur={p.cur} value={p.price} unit={p.unit} />
              </div>
            </div>
            <Divider />
            <Button size="lg" full icon="calendar" onClick={() => startRequest(p, 'Inspection')}>Request inspection</Button>
            <Button size="lg" full variant="soft" icon="key" onClick={() => startRequest(p, 'Lease')}>Request to {p.unit === '/night' ? 'book' : 'lease'}</Button>
            <Button size="lg" full variant="outline" icon="message" onClick={() => navigate('messages')}>Message concierge</Button>
            <button onClick={() => toggleSave(p.id)} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: 'none', border: 'none', color: isSaved ? 'var(--brand)' : 'var(--ink-2)', cursor: 'pointer', fontSize: 14, fontWeight: 600, fontFamily: 'var(--font-body)', padding: '4px' }}>
              <Icon name="heart" size={17} fill={isSaved ? 'current' : 'none'} /> {isSaved ? 'Saved to portfolio' : 'Save property'}
            </button>
          </Card>
          <Card style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface-2)' }}>
            <Avatar name="Credeo Concierge" size={42} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>Credeo Concierge</div>
              <div style={{ color: 'var(--ink-3)', fontSize: 12.5 }}>Typically replies within an hour</div>
            </div>
            <span style={{ width: 9, height: 9, borderRadius: 99, background: 'var(--ok)' }} />
          </Card>
        </div>
      </div>
    </div>
  );
}

/* ============ REQUEST MODAL (inspection / lease) ============ */
function RequestModal({ open, kind, prop, onClose, onSubmit, isMobile }) {
  const [date, setDate] = u3State('2026-06-20');
  const [slot, setSlot] = u3State('11:00');
  const [term, setTerm] = u3State('12 months');
  const [party, setParty] = u3State('2');
  const [note, setNote] = u3State('');
  if (!open || !prop) return null;
  const isInsp = kind === 'Inspection';

  const submit = () => {
    onSubmit({
      kind, propId: prop.id, date, slot: isInsp ? slot : '—', term, note,
    });
  };

  return (
    <Modal open={open} onClose={onClose} mobile={isMobile} width={540}>
      <div style={{ padding: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 22px', borderBottom: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
            <span style={{ width: 38, height: 38, borderRadius: 'var(--r-sm)', background: 'var(--brand-soft)', color: 'var(--brand)', display: 'grid', placeItems: 'center' }}><Icon name={isInsp ? 'calendar' : 'key'} size={19} /></span>
            <div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 19, fontWeight: 600 }}>{isInsp ? 'Request an inspection' : 'Request to lease'}</div>
              <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>{prop.title}</div>
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'var(--surface-2)', border: 'none', width: 34, height: 34, borderRadius: '50%', cursor: 'pointer', display: 'grid', placeItems: 'center', color: 'var(--ink-2)' }}><Icon name="x" size={18} /></button>
        </div>

        <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', gap: 12, padding: 12, background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', alignItems: 'center' }}>
            <div style={{ width: 56, height: 48, borderRadius: 'var(--r-sm)', overflow: 'hidden', flexShrink: 0 }}>
              <PropImage hue={prop.hue} label="" height={48} radius="0" />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{prop.city}, {prop.country}</div>
              <div style={{ color: 'var(--ink-3)', fontSize: 13, fontFamily: 'var(--font-mono)' }}>Ref {prop.ref}</div>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600 }}><Money cur={prop.cur} value={prop.price} unit={prop.unit} /></div>
          </div>

          {isInsp ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Field label="Preferred date" required><Input type="date" value={date} min="2026-06-16" onChange={(e) => setDate(e.target.value)} /></Field>
              <Field label="Preferred time" required>
                <Select value={slot} onChange={setSlot} options={['09:00', '10:00', '11:00', '13:00', '15:30', '17:00']} />
              </Field>
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Field label={prop.unit === '/night' ? 'Check-in date' : 'Lease start'} required><Input type="date" value={date} min="2026-06-16" onChange={(e) => setDate(e.target.value)} /></Field>
              <Field label={prop.unit === '/night' ? 'Length of stay' : 'Lease term'} required>
                <Select value={term} onChange={setTerm} options={prop.unit === '/night' ? ['3 nights', '5 nights', '1 week', '2 weeks'] : ['6 months', '12 months', '24 months', '36 months']} />
              </Field>
            </div>
          )}

          <Field label={isInsp ? 'Number attending' : 'Occupants'}>
            <Select value={party} onChange={setParty} options={['1', '2', '3', '4', '5+']} />
          </Field>

          <Field label="Notes for the concierge" hint="Anything you'd like to see or discuss during the visit.">
            <Textarea value={note} onChange={(e) => setNote(e.target.value)} placeholder={isInsp ? 'I would love to see the terrace and parking…' : 'Two professional tenants, no pets, flexible on start date…'} />
          </Field>

          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', borderTop: '1px solid var(--line)', paddingTop: 16 }}>
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button icon="send" onClick={submit}>Submit request</Button>
          </div>
        </div>
      </div>
    </Modal>
  );
}

/* ============ REQUESTS (status tracking) ============ */
function RequestRow({ r, prop, expanded, onToggle }) {
  return (
    <Card pad={false} style={{ overflow: 'hidden' }}>
      <div onClick={onToggle} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 'var(--pad)', cursor: 'pointer' }}>
        <div style={{ width: 64, height: 56, borderRadius: 'var(--r-sm)', overflow: 'hidden', flexShrink: 0 }}>
          <PropImage hue={prop.hue} label="" height={56} radius="0" />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600, color: 'var(--brand-ink)' }}>
              <Icon name={r.kind === 'Inspection' ? 'calendar' : 'key'} size={14} /> {r.kind}
            </span>
            <span style={{ color: 'var(--ink-3)', fontSize: 12.5, fontFamily: 'var(--font-mono)' }}>{r.ref}</span>
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 16.5, fontWeight: 600, marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{prop.title}</div>
          <div style={{ color: 'var(--ink-2)', fontSize: 13, marginTop: 3 }}>{new Date(r.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })}{r.slot !== '—' ? ` · ${r.slot}` : ''}</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <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>
      </div>
      {expanded && (
        <div style={{ padding: '4px var(--pad) var(--pad)', borderTop: '1px solid var(--line)', animation: 'credo-fade .2s ease' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 18, paddingTop: 16 }}>
            <div style={{ background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', padding: '18px 20px' }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 16 }}>Progress</div>
              <StatusTimeline status={r.status} vertical />
            </div>
            {r.note && (
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>Your note</div>
                <p style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.55 }}>{r.note}</p>
              </div>
            )}
            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <Button variant="soft" size="sm" icon="message">Message concierge</Button>
              {r.status !== 'Completed' && <Button variant="ghost" size="sm" icon="edit">Reschedule</Button>}
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}

function RequestsView(ctx) {
  const { data, requests, navigate, userId } = ctx;
  const [tab, setTab] = u3State('All');
  const [open, setOpen] = u3State(null);
  const myReqs = requests.filter(r => r.userId === userId);
  const filtered = myReqs.filter(r => tab === 'All' || r.kind === tab.slice(0, -1));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <div>
        <h1 style={{ fontSize: 30 }}>Your requests</h1>
        <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>Track inspections and lease applications in real time</p>
      </div>
      <Segmented options={[{ value: 'All', label: 'All', count: myReqs.length }, { value: 'Inspections', label: 'Inspections', count: myReqs.filter(r => r.kind === 'Inspection').length }, { value: 'Leases', label: 'Leases', count: myReqs.filter(r => r.kind === 'Lease').length }]} value={tab} onChange={setTab} />
      {filtered.length === 0 ? (
        <Card><EmptyState icon="calendar" title="No requests yet" body="Request an inspection or lease from any property and track its progress here." action={<Button onClick={() => navigate('browse')} icon="search">Browse properties</Button>} /></Card>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
          {filtered.map(r => <RequestRow key={r.id} r={r} prop={data.PROPERTIES.find(p => p.id === r.propId)} expanded={open === r.id} onToggle={() => setOpen(open === r.id ? null : r.id)} />)}
        </div>
      )}
    </div>
  );
}

/* ============ MESSAGES ============ */
function MessagesScreen(ctx) {
  const { isMobile, fresh } = ctx;
  const [thread, setThread] = u3State(fresh ? [] : window.CREDO.THREAD);
  const [draft, setDraft] = u3State('');
  const send = () => {
    if (!draft.trim()) return;
    setThread([...thread, { from: 'user', name: 'You', text: draft, time: 'Now' }]);
    setDraft('');
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 22, height: '100%' }}>
      <div>
        <h1 style={{ fontSize: 30 }}>Messages</h1>
        <p style={{ color: 'var(--ink-2)', fontSize: 15, marginTop: 8 }}>Your conversation with the Credeo concierge</p>
      </div>
      <Card pad={false} style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', flex: 1, minHeight: 420 }}>
        {/* thread header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
          <Avatar name="Credeo Concierge" size={42} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 600, fontSize: 15 }}>Credeo Concierge</div>
            <div style={{ color: 'var(--ok)', fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 7, height: 7, borderRadius: 99, background: 'var(--ok)' }} /> {fresh ? 'Online' : 'Online · Ashby Lofts 14B'}</div>
          </div>
          <Button variant="ghost" size="sm" icon="phone">Call</Button>
        </div>
        {/* messages */}
        <div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 14, background: 'var(--surface-2)' }}>
          {thread.length > 0 && <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-3)', margin: '4px 0' }}>Monday, 15 June 2026</div>}
          {thread.length === 0 && <EmptyState icon="message" title="No messages yet" body="Your concierge will reach out here once you make a request. You can also start the conversation below." />}
          {thread.map((m, i) => {
            const mine = m.from === 'user';
            return (
              <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: mine ? 'flex-end' : 'flex-start', gap: 4 }}>
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: 9, flexDirection: mine ? 'row-reverse' : 'row', maxWidth: '82%' }}>
                  {!mine && <Avatar name="Credeo Concierge" size={30} />}
                  <div style={{
                    padding: '11px 15px', borderRadius: 16, fontSize: 14, lineHeight: 1.5,
                    background: mine ? 'var(--brand)' : 'var(--surface)', color: mine ? '#fff' : 'var(--ink)',
                    borderBottomRightRadius: mine ? 4 : 16, borderBottomLeftRadius: mine ? 16 : 4,
                    border: mine ? 'none' : '1px solid var(--line)', boxShadow: 'var(--shadow-sm)',
                  }}>
                    {m.text}
                    {m.meta === 'inspection-approved' && (
                      <div style={{ marginTop: 10, padding: '10px 12px', background: 'rgba(255,255,255,.16)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 9, fontSize: 13 }}>
                        <Icon name="checkCircle" size={17} /> Inspection INS-2041 approved
                      </div>
                    )}
                  </div>
                </div>
                <span style={{ fontSize: 11, color: 'var(--ink-3)', padding: mine ? '0 4px' : '0 39px' }}>{m.time}</span>
              </div>
            );
          })}
        </div>
        {/* composer */}
        <div style={{ display: 'flex', gap: 10, padding: 14, borderTop: '1px solid var(--line)', alignItems: 'center' }}>
          <Input value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} placeholder="Write a message…" style={{ borderRadius: 99 }} />
          <Button icon="send" onClick={send} style={{ borderRadius: 99, width: 46, padding: 0, flexShrink: 0 }} />
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { PropertyDetail, RequestModal, RequestsView, MessagesScreen });
