// ── Post chooser + Request flow + Add-listing flow ───────────────
const { Icon, Photo, FormScreen, PrimaryBtn, Field, TextInput, OptionTiles, Segmented, ChoiceChips,
  SuccessView, CATEGORIES } = window;

// Bottom sheet: choose what to post
function PostSheet({ open, onClose, onRequest, onListing }) {
  if (!open) return null;
  const Opt = ({ icon, title, sub, onClick, tint }) => (
    <button onClick={onClick} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 14,
      padding: 16, borderRadius: 16, border: '1.5px solid var(--line)', background: 'var(--surface)',
      cursor: 'pointer', textAlign: 'left' }}>
      <span style={{ width: 48, height: 48, borderRadius: 13, flexShrink: 0, display: 'flex', alignItems: 'center',
        justifyContent: 'center', background: tint }}>
        <Icon name={icon} size={24} s="var(--accent)" /></span>
      <span style={{ flex: 1 }}>
        <span style={{ display: 'block', fontFamily: 'var(--sans)', fontSize: 16.5, fontWeight: 700,
          color: 'var(--ink)', letterSpacing: -0.2 }}>{title}</span>
        <span style={{ display: 'block', fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--muted)',
          marginTop: 2 }}>{sub}</span>
      </span>
      <Icon name="chevR" size={18} s="var(--muted)" />
    </button>
  );
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 36, display: 'flex', flexDirection: 'column',
      justifyContent: 'flex-end' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(20,20,18,0.4)',
        animation: 'fadeIn .2s ease' }} />
      <div style={{ position: 'relative', background: 'var(--bg)', borderRadius: '26px 26px 0 0',
        padding: '14px 20px calc(24px + env(safe-area-inset-bottom))', animation: 'sheetUp .28s cubic-bezier(.2,.8,.2,1)' }}>
        <div style={{ width: 38, height: 4, borderRadius: 9, background: 'var(--line)', margin: '0 auto 16px' }} />
        <div style={{ fontFamily: 'var(--sans)', fontSize: 20, fontWeight: 700, letterSpacing: -0.4,
          color: 'var(--ink)', marginBottom: 16 }}>What would you like to post?</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Opt icon="search" title="Post a request" sub="Tell agents what you're looking for"
            tint="var(--accent-soft)" onClick={onRequest} />
          <Opt icon="house" title="List a property" sub="Put your home or space on the market"
            tint="oklch(0.95 0.03 95)" onClick={onListing} />
        </div>
      </div>
    </div>
  );
}

// ── Request flow ─────────────────────────────────────────────────
function RequestForm({ onClose, onCreate }) {
  const [deal, setDeal] = React.useState('buy');
  const [cat, setCat] = React.useState('home');
  const [area, setArea] = React.useState('');
  const [bMin, setBMin] = React.useState('');
  const [bMax, setBMax] = React.useState('');
  const [beds, setBeds] = React.useState('any');
  const [baths, setBaths] = React.useState('any');
  const [when, setWhen] = React.useState('flex');
  const [size, setSize] = React.useState('');
  const [note, setNote] = React.useState('');
  const [done, setDone] = React.useState(false);

  const category = CATEGORIES.find(c => c.id === cat);
  const residential = category && category.residential;
  const valid = area.trim().length > 1;

  if (done) return (
    <SuccessView title="Request posted" doneLabel="View my requests" onDone={onClose}
      sub="Matching agents will reach out with homes that fit. Track replies under My requests." />
  );

  const bedOpts = [['any', 'Any'], ['1', '1+'], ['2', '2+'], ['3', '3+'], ['4', '4+']];

  return (
    <FormScreen title="Post a request" onBack={onClose}
      footer={<PrimaryBtn disabled={!valid} icon="sparkle" onClick={() => { onCreate && onCreate({ deal, cat, area, bMin, bMax }); setDone(true); }}>
        Post request</PrimaryBtn>}>
      <Field label="I want to">
        <Segmented options={[['buy', 'Buy'], ['rent', 'Rent']]} value={deal} onChange={setDeal} />
      </Field>
      <Field label="Property type">
        <OptionTiles options={CATEGORIES} value={cat} onChange={setCat} cols={2} />
      </Field>
      <Field label="Preferred area" hint="Add one or more neighborhoods, or a city.">
        <TextInput value={area} onChange={setArea} placeholder="e.g. Noe Valley, Mission" />
      </Field>
      <Field label={deal === 'rent' ? 'Monthly budget' : 'Budget'}>
        <div style={{ display: 'flex', gap: 10 }}>
          <div style={{ flex: 1, minWidth: 0 }}><TextInput value={bMin} onChange={setBMin} placeholder="Min" prefix="$" type="number" /></div>
          <div style={{ flex: 1, minWidth: 0 }}><TextInput value={bMax} onChange={setBMax} placeholder="Max" prefix="$" type="number" /></div>
        </div>
      </Field>
      {residential ? (
        <>
          <Field label="Bedrooms"><ChoiceChips options={bedOpts.slice(0, 5)} value={beds} onChange={setBeds} /></Field>
          <Field label="Bathrooms"><ChoiceChips options={bedOpts.slice(0, 4)} value={baths} onChange={setBaths} /></Field>
        </>
      ) : (
        <Field label="Approx. size" optional><TextInput value={size} onChange={setSize} placeholder="e.g. 800–1,200 sqft" /></Field>
      )}
      <Field label="Timeframe">
        <ChoiceChips options={[['asap', 'ASAP'], ['3mo', '1–3 months'], ['flex', 'Flexible']]} value={when} onChange={setWhen} />
      </Field>
      <Field label="Anything else?" optional>
        <TextInput value={note} onChange={setNote} placeholder="Must-haves, deal-breakers, style…" multiline />
      </Field>
      <div style={{ height: 8 }} />
    </FormScreen>
  );
}

// ── Add-listing flow ─────────────────────────────────────────────
const FEATURE_BANK = ['Parking', 'Garden / yard', 'In-unit laundry', 'Pet friendly', 'Renovated',
  'Elevator', 'Roof deck', 'Air conditioning', 'Storage', 'Doorman'];

function PhotoAdder({ count, setCount }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} style={{ position: 'relative', aspectRatio: '1', borderRadius: 12, overflow: 'hidden' }}>
          <Photo hue={40 + i * 30} i={i} label={false} />
          {i === 0 && <span style={{ position: 'absolute', bottom: 6, left: 6, fontFamily: 'var(--mono)',
            fontSize: 9, color: '#fff', background: 'rgba(20,20,18,0.6)', padding: '2px 6px', borderRadius: 5 }}>COVER</span>}
        </div>
      ))}
      <button onClick={() => setCount(c => c + 1)} style={{ aspectRatio: '1', borderRadius: 12, cursor: 'pointer',
        border: '1.5px dashed var(--line)', background: 'var(--surface)', display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 5 }}>
        <Icon name="camera" size={22} s="var(--muted)" />
        <span style={{ fontFamily: 'var(--sans)', fontSize: 11, fontWeight: 600, color: 'var(--muted)' }}>Add</span>
      </button>
    </div>
  );
}

function ListingForm({ onClose, onCreate }) {
  const [deal, setDeal] = React.useState('buy');
  const [cat, setCat] = React.useState('home');
  const [addr, setAddr] = React.useState('');
  const [hood, setHood] = React.useState('');
  const [price, setPrice] = React.useState('');
  const [beds, setBeds] = React.useState('3');
  const [baths, setBaths] = React.useState('2');
  const [sqft, setSqft] = React.useState('');
  const [photos, setPhotos] = React.useState(3);
  const [reel, setReel] = React.useState(true);
  const [feats, setFeats] = React.useState(['Parking']);
  const [desc, setDesc] = React.useState('');
  const [done, setDone] = React.useState(false);

  const category = CATEGORIES.find(c => c.id === cat);
  const residential = category && category.residential;
  const valid = addr.trim().length > 2 && price.trim().length > 0;
  const toggleFeat = (f) => setFeats(p => p.includes(f) ? p.filter(x => x !== f) : [...p, f]);

  if (done) return (
    <SuccessView title="Listing published" doneLabel="Manage listings" onDone={onClose}
      sub="Your listing is live and now appears in search, map and reels. Track its performance in Manage listings." />
  );

  const SmallNum = ({ label, value, onChange }) => (
    <div style={{ flex: 1 }}>
      <div style={{ fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600, color: 'var(--muted)', marginBottom: 7 }}>{label}</div>
      <TextInput value={value} onChange={onChange} placeholder="0" type="number" />
    </div>
  );

  return (
    <FormScreen title="List a property" onBack={onClose}
      footer={<PrimaryBtn disabled={!valid} icon="check" onClick={() => { onCreate && onCreate({ deal, cat, addr, hood, price: +price, beds: +beds, baths: +baths, sqft: +sqft, reel, feats }); setDone(true); }}>
        Publish listing</PrimaryBtn>}>
      <Field label="Listing type">
        <Segmented options={[['buy', 'For sale'], ['rent', 'For rent']]} value={deal} onChange={setDeal} />
      </Field>
      <Field label="Property type">
        <OptionTiles options={CATEGORIES} value={cat} onChange={setCat} cols={2} />
      </Field>
      <Field label="Photos" hint="The first photo is your cover.">
        <PhotoAdder count={photos} setCount={setPhotos} />
      </Field>
      <Field label="Add a video reel" hint="Listings with a walkthrough reel get more views.">
        <button onClick={() => setReel(r => !r)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12,
          padding: 14, borderRadius: 13, cursor: 'pointer', textAlign: 'left',
          border: reel ? '1.5px solid var(--ink)' : '1.5px solid var(--line)',
          background: reel ? 'var(--ink)' : 'var(--surface)' }}>
          <Icon name="play" size={22} s={reel ? 'var(--bg)' : 'var(--accent)'} fill={reel ? 'var(--bg)' : 'none'} />
          <span style={{ flex: 1, fontFamily: 'var(--sans)', fontSize: 14.5, fontWeight: 600,
            color: reel ? 'var(--bg)' : 'var(--ink)' }}>{reel ? 'Reel added — record a 30s walkthrough' : 'Tap to add a walkthrough reel'}</span>
          {reel && <Icon name="check" size={18} s="var(--bg)" sw={2.4} />}
        </button>
      </Field>
      <Field label="Address"><TextInput value={addr} onChange={setAddr} placeholder="e.g. 418 Fair Oaks St" /></Field>
      <Field label="Neighborhood"><TextInput value={hood} onChange={setHood} placeholder="e.g. Noe Valley" /></Field>
      <Field label={deal === 'rent' ? 'Monthly rent' : 'Price'}>
        <TextInput value={price} onChange={setPrice} placeholder={deal === 'rent' ? '4,200' : '1,295,000'} prefix="$" type="number" />
      </Field>
      {residential && (
        <Field label="Beds · baths · size">
          <div style={{ display: 'flex', gap: 10 }}>
            <SmallNum label="Beds" value={beds} onChange={setBeds} />
            <SmallNum label="Baths" value={baths} onChange={setBaths} />
            <SmallNum label="Sqft" value={sqft} onChange={setSqft} />
          </div>
        </Field>
      )}
      <Field label="Features" optional>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {FEATURE_BANK.map(f => {
            const on = feats.includes(f);
            return (
              <button key={f} onClick={() => toggleFeat(f)} style={{ height: 40, padding: '0 14px', borderRadius: 999,
                cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: 'var(--sans)',
                fontSize: 13.5, fontWeight: 500, border: on ? '1.5px solid var(--ink)' : '1.5px solid var(--line)',
                background: on ? 'var(--ink)' : 'var(--surface)', color: on ? 'var(--bg)' : 'var(--ink)' }}>
                {on && <Icon name="check" size={14} s="var(--bg)" sw={2.4} />}{f}</button>
            );
          })}
        </div>
      </Field>
      <Field label="Description" optional>
        <TextInput value={desc} onChange={setDesc} placeholder="Describe what makes this place special…" multiline />
      </Field>
      <div style={{ height: 8 }} />
    </FormScreen>
  );
}

Object.assign(window, { PostSheet, RequestForm, ListingForm });
