// ── AI Search (primary search for Haven) — full-screen overlay ───
const { Icon, Photo, rankListings, filterListings, ResultRow, NoResults,
  parseQuery, chipsFromFilters, LISTINGS, NEIGHBORHOODS, PROPERTY_TYPES } = window;

const AI_EXAMPLES = [
  'Family home in Noe Valley under $1.4M with a yard',
  '2-bed rental in Hayes Valley under $4k with parking',
  'Somewhere quiet near the beach, pet friendly',
  'Modern condo to buy with a video tour and elevator',
];
const AI_FEATURES = ['Parking', 'Garden', 'Laundry', 'Pet friendly', 'Roof deck', 'Elevator', 'City views'];

function coerceFilters(o) {
  const clean = { deal: null, priceMin: null, priceMax: null, beds: 0, baths: 0, types: [], hoods: [], features: [], video: false };
  if (!o || typeof o !== 'object') return clean;
  if (o.deal === 'buy' || o.deal === 'rent') clean.deal = o.deal;
  ['priceMin', 'priceMax'].forEach(k => { if (typeof o[k] === 'number') clean[k] = o[k]; });
  ['beds', 'baths'].forEach(k => { if (typeof o[k] === 'number') clean[k] = Math.round(o[k]); });
  if (Array.isArray(o.types)) clean.types = o.types.filter(t => PROPERTY_TYPES.includes(t));
  if (Array.isArray(o.hoods)) clean.hoods = o.hoods.filter(h => NEIGHBORHOODS.includes(h));
  if (Array.isArray(o.features)) clean.features = o.features.filter(f => AI_FEATURES.includes(f));
  clean.video = !!o.video;
  return clean;
}

async function aiParse(query) {
  const local = () => {
    const f = parseQuery(query);
    const bits = chipsFromFilters(f).map(c => c.label.toLowerCase());
    const summary = bits.length ? `Searching for ${bits.join(', ')}.` : `Showing homes that best match “${query}”.`;
    return { f, summary };
  };
  if (!(window.claude && window.claude.complete)) {
    await new Promise(r => setTimeout(r, 700));
    return local();
  }
  const prompt = `You are the search assistant for "Haven", a real-estate app in San Francisco.
Convert the user's request into JSON filters. Respond with ONLY a JSON object, no prose.
Schema:
{ "deal": "buy" | "rent" | null,
  "priceMin": number | null, "priceMax": number | null,   // sale=total $, rent=$ per month
  "beds": integer, "baths": integer,
  "types": string[],   // any of: ${PROPERTY_TYPES.join(', ')}
  "hoods": string[],   // any of: ${NEIGHBORHOODS.join(', ')}
  "features": string[],// any of: ${AI_FEATURES.join(', ')}
  "video": boolean,
  "summary": string }  // one short friendly sentence describing the search
User request: "${query.replace(/"/g, "'")}"`;
  try {
    const raw = await window.claude.complete(prompt);
    const m = raw.match(/\{[\s\S]*\}/);
    const parsed = JSON.parse(m ? m[0] : raw);
    const f = coerceFilters(parsed);
    const summary = (typeof parsed.summary === 'string' && parsed.summary) || local().summary;
    return { f, summary };
  } catch (e) {
    return local();
  }
}

function ThinkingCard() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '16px 16px', borderRadius: 16,
      background: 'var(--accent-soft)', marginTop: 16 }}>
      <span style={{ width: 38, height: 38, borderRadius: 999, background: 'var(--accent)', display: 'flex',
        alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name="sparkle" size={20} s="#fff" /></span>
      <span style={{ fontFamily: 'var(--sans)', fontSize: 14.5, fontWeight: 600, color: 'var(--ink)' }}>
        Reading your request</span>
      <span style={{ display: 'flex', gap: 4, marginLeft: 2 }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{ width: 6, height: 6, borderRadius: 9, background: 'var(--accent)',
            animation: `blink 1s ${i * 0.18}s infinite ease-in-out` }} />
        ))}
      </span>
    </div>
  );
}

function AISearchScreen({ onClose, onOpenDetail, saved, onToggleSave }) {
  const [q, setQ] = React.useState('');
  const [phase, setPhase] = React.useState('idle'); // idle | thinking | results
  const [filters, setFilters] = React.useState(null);
  const [summary, setSummary] = React.useState('');

  const run = async (text) => {
    const v = (text != null ? text : q).trim();
    if (!v) return;
    setQ(v); setPhase('thinking');
    const { f, summary } = await aiParse(v);
    setFilters(f); setSummary(summary); setPhase('results');
  };

  const removeChip = (key) => {
    const nf = { ...filters };
    if (key === 'deal') nf.deal = null;
    else if (key === 'beds') nf.beds = 0;
    else if (key === 'baths') nf.baths = 0;
    else if (key === 'priceMax') nf.priceMax = null;
    else if (key === 'priceMin') nf.priceMin = null;
    else if (key === 'video') nf.video = false;
    else if (key.startsWith('type:')) nf.types = nf.types.filter(t => t !== key.slice(5));
    else if (key.startsWith('hood:')) nf.hoods = nf.hoods.filter(h => h !== key.slice(5));
    else if (key.startsWith('feat:')) nf.features = nf.features.filter(x => x !== key.slice(5));
    setFilters(nf);
  };

  let ranked = [], closest = false;
  if (filters) {
    const hard = { deal: filters.deal, priceMin: filters.priceMin, priceMax: filters.priceMax,
      beds: filters.beds, baths: filters.baths, types: filters.types, hoods: filters.hoods, video: filters.video };
    let base = filterListings(LISTINGS, hard);
    if (base.length === 0) { base = LISTINGS; closest = true; }
    ranked = rankListings(base, filters);
  }
  const chips = filters ? chipsFromFilters(filters) : [];

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 34, background: 'var(--bg)', display: 'flex',
      flexDirection: 'column', animation: 'slideIn .26s cubic-bezier(.2,.8,.2,1)' }}>
      {/* header */}
      <div style={{ paddingTop: 50, padding: '50px 18px 12px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <span style={{ width: 30, height: 30, borderRadius: 9, background: 'var(--accent)', display: 'flex',
              alignItems: 'center', justifyContent: 'center' }}><Icon name="sparkle" size={18} s="#fff" /></span>
            <span style={{ fontFamily: 'var(--sans)', fontSize: 20, fontWeight: 700, letterSpacing: -0.4,
              color: 'var(--ink)' }}>Haven AI</span>
          </div>
          <button onClick={onClose} style={{ width: 38, height: 38, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: 'oklch(0.94 0.004 95)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="close" size={20} s="var(--ink)" sw={2} /></button>
        </div>
        {/* input */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minHeight: 54, padding: '8px 8px 8px 16px',
          borderRadius: 16, border: '1.5px solid var(--ink)', background: 'var(--surface)' }}>
          <Icon name="search" size={20} s="var(--ink)" />
          <input value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') run(); }}
            placeholder="Describe your ideal home…" autoFocus
            style={{ flex: 1, border: 'none', outline: 'none', background: 'none', fontFamily: 'var(--sans)',
              fontSize: 15, color: 'var(--ink)', minWidth: 0 }} />
          <button onClick={() => run()} style={{ width: 38, height: 38, borderRadius: 999, border: 'none',
            cursor: 'pointer', flexShrink: 0, background: 'var(--accent)', display: 'flex', alignItems: 'center',
            justifyContent: 'center' }}><Icon name="arrowUp" size={20} s="#fff" sw={2.4} /></button>
        </div>
      </div>

      {/* body */}
      <div className="no-scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '0 18px 24px' }}>
        {phase === 'idle' && (
          <div style={{ paddingTop: 8 }}>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 13.5, fontWeight: 600, color: 'var(--muted)',
              margin: '4px 0 10px' }}>Ask in your own words</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {AI_EXAMPLES.map(ex => (
                <button key={ex} onClick={() => run(ex)} style={{ display: 'flex', alignItems: 'center', gap: 11,
                  padding: '13px 15px', borderRadius: 14, border: '1px solid var(--line)', background: 'var(--surface)',
                  cursor: 'pointer', textAlign: 'left' }}>
                  <Icon name="sparkle" size={18} s="var(--accent)" />
                  <span style={{ flex: 1, fontFamily: 'var(--sans)', fontSize: 14.5, color: 'var(--ink)', fontWeight: 500 }}>{ex}</span>
                  <Icon name="arrowUp" size={16} s="var(--muted)" style={{ transform: 'rotate(45deg)' }} />
                </button>
              ))}
            </div>
          </div>
        )}

        {phase === 'thinking' && <ThinkingCard />}

        {phase === 'results' && filters && (
          <>
            {/* AI summary */}
            <div style={{ display: 'flex', gap: 10, padding: '14px 14px', borderRadius: 16, background: 'var(--accent-soft)',
              margin: '14px 0 4px' }}>
              <Icon name="sparkle" size={18} s="var(--accent)" style={{ flexShrink: 0, marginTop: 1 }} />
              <span style={{ fontFamily: 'var(--sans)', fontSize: 14, color: 'var(--ink)', lineHeight: 1.5 }}>{summary}</span>
            </div>
            {/* chips */}
            {chips.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, padding: '12px 0 4px' }}>
                {chips.map(c => (
                  <button key={c.key} onClick={() => removeChip(c.key)} style={{ display: 'inline-flex', alignItems: 'center',
                    gap: 5, height: 32, padding: '0 7px 0 12px', borderRadius: 999, border: 'none', cursor: 'pointer',
                    background: 'var(--accent)', color: '#fff', fontFamily: 'var(--sans)', fontSize: 13, fontWeight: 600 }}>
                    {c.label}<span style={{ width: 18, height: 18, borderRadius: 999, background: 'rgba(255,255,255,0.25)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Icon name="close" size={11} s="#fff" sw={2.6} /></span></button>
                ))}
              </div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0 4px' }}>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 14.5, fontWeight: 700, color: 'var(--ink)' }}>
                {ranked.length} {ranked.length === 1 ? 'home' : 'homes'}</span>
              <span style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--muted)' }}>
                {closest ? 'Closest matches' : 'Best match first'}</span>
            </div>
            {ranked.length === 0 ? <NoResults /> : ranked.map(({ l, pct, reasons }) => (
              <ResultRow key={l.id} l={l} match={pct} reasons={reasons} onClick={() => onOpenDetail(l.id)} />
            ))}
          </>
        )}
      </div>
    </div>
  );
}

window.AISearchScreen = AISearchScreen;
