// Skrrs portal — Search results. Responsive.
const { PropertyCard: SPCard, Button: SButton, Select: SSelect, Tag: STag, Checkbox: SCheck, Badge: SBg } = window.SkrrsDesignSystem_6013e8;

const TYPE_TABS = [
  { key:'all', label:'すべて' },
  { key:'office', label:'オフィス' },
  { key:'retail', label:'店舗' },
  { key:'rnd', label:'教室' },
  { key:'industrial', label:'倉庫' },
  { key:'datacenter', label:'工場' },
];
const FEATURE_FILTERS = ['仲介手数料0円','居抜き・セットアップ','NEW物件','駐車場あり','24時間利用可','電力増設可'];

function SearchScreen({ initialType = 'all', saved, onToggleSave, onOpen, onNav }) {
  const D = window.SKRRS_DATA;
  const { isMobile, isTablet } = window.useViewport();
  const [type, setType] = React.useState(initialType);
  const [feat, setFeat] = React.useState({});
  const [sort, setSort] = React.useState('new');
  const [showFilters, setShowFilters] = React.useState(false);
  React.useEffect(()=>{ setType(initialType); }, [initialType]);

  const list = D.properties.filter(p => type === 'all' || p.type === type);
  const cols = isMobile ? 2 : isTablet ? 2 : 3;

  const FilterPanel = (
    <div style={{ background:'var(--surface)', border:'1px solid var(--border-subtle)',
      borderRadius:'var(--r-md)', padding:'var(--sp-5)', display:'flex', flexDirection:'column', gap:'var(--sp-5)' }}>
      <span style={{ font:'700 var(--t-sm)/1 var(--font-display)', color:'var(--text-strong)' }}>絞り込み条件</span>
      <SSelect label="エリア" placeholder="都道府県を選択" options={D.areas} />
      <SSelect label="沿線・駅" placeholder="沿線を選択" options={['JR山手線','東京メトロ丸ノ内線','東急東横線']} />
      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
        <span style={{ font:'var(--fw-medium) var(--t-sm)/1.3 var(--font-body)', color:'var(--text-strong)' }}>賃料（坪単価）</span>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <SSelect placeholder="下限" options={['¥5,000','¥10,000','¥20,000']} />
          <span style={{ color:'var(--text-faint)' }}>〜</span>
          <SSelect placeholder="上限" options={['¥20,000','¥30,000','¥50,000']} />
        </div>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:9 }}>
        <span style={{ font:'var(--fw-medium) var(--t-sm)/1.3 var(--font-body)', color:'var(--text-strong)' }}>こだわり条件</span>
        {['駐車場あり','24時間利用可','OAフロア','分割可'].map(c=>(
          <SCheck key={c} label={c} checked={!!feat[c]} onChange={()=>setFeat(f=>({...f,[c]:!f[c]}))} />
        ))}
      </div>
      <SButton variant="primary" full pill iconLeft={<window.Icon name="search" size={17}/>}>この条件で検索</SButton>
    </div>
  );

  return (
    <main style={{ background:'var(--bg-page)', minHeight:'70vh' }}>
      {/* breadcrumb + title */}
      <div style={{ background:'var(--surface)', borderBottom:'1px solid var(--border-subtle)' }}>
        <window.Container style={{ paddingTop:'var(--sp-6)', paddingBottom:'var(--sp-5)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12,
            font:'var(--fw-regular) var(--t-xs)/1 var(--font-body)', color:'var(--text-muted)' }}>
            <span style={{ cursor:'pointer' }} onClick={()=>onNav('home')}>ホーム</span><window.Icon name="chevR" size={12}/>
            <span style={{ color:'var(--text-body)' }}>賃貸物件を探す</span>
          </div>
          <div style={{ display:'flex', alignItems:'baseline', gap:16 }}>
            <h1 style={{ margin:0, font:'700 var(--t-h1)/1.2 var(--font-display)', color:'var(--text-strong)' }}>賃貸物件 検索結果</h1>
            <span style={{ display:'inline-flex', alignItems:'baseline', gap:5 }}>
              <span style={{ font:'700 var(--t-h2)/1 var(--font-num)', color:'var(--blue-600)' }}>{list.length}</span>
              <span style={{ font:'var(--fw-medium) var(--t-sm)/1 var(--font-body)', color:'var(--text-muted)' }}>件</span>
            </span>
          </div>
          {/* type tabs */}
          <div style={{ display:'flex', gap:4, marginTop:18, flexWrap:'wrap', overflowX: isMobile?'auto':'visible' }}>
            {TYPE_TABS.map(t=>{
              const on = type===t.key;
              return (
                <button key={t.key} onClick={()=>setType(t.key)} style={{ cursor:'pointer',
                  padding:'9px 16px', border:'none', borderRadius:'var(--r-sm) var(--r-sm) 0 0', whiteSpace:'nowrap',
                  background: on ? 'var(--blue-900)' : 'transparent',
                  color: on ? '#fff' : 'var(--text-body)',
                  font:`${on?'var(--fw-bold)':'var(--fw-medium)'} var(--t-sm)/1 var(--font-body)`,
                  borderBottom: on ? '2px solid var(--blue-500)' : '2px solid transparent' }}>{t.label}</button>
              );
            })}
          </div>
        </window.Container>
      </div>

      {/* 非公開物件バナー（表示件数の外に希少在庫がある＝問い合わせ動機） */}
      <window.Container style={{ paddingTop:'var(--sp-5)' }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:'var(--sp-4)', flexWrap:'wrap',
          background:'var(--blue-900)', borderRadius:'var(--r-md)', padding: isMobile?'var(--sp-5)':'var(--sp-5) var(--sp-7)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:14 }}>
            <span style={{ display:'grid', placeItems:'center', width:44, height:44, borderRadius:'var(--r-pill)', background:'rgba(255,255,255,0.12)', color:'#fff', flex:'none' }}><window.Icon name="search" size={20}/></span>
            <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
              <span style={{ font:'var(--fw-bold) var(--t-base)/1.4 var(--font-display)', color:'#fff' }}>
                Web掲載のほかに、非公開物件が {(window.SKRRS_DATA.privateListings||{}).count||'500'} 件以上。
              </span>
              <span style={{ font:'var(--fw-regular) var(--t-xs)/1.5 var(--font-body)', color:'rgba(255,255,255,0.72)' }}>
                条件に合う希少物件は、担当エージェントより個別にご案内します。まずはご希望条件をお聞かせください。
              </span>
            </div>
          </div>
          <SButton variant="inverse" pill full={isMobile} iconLeft={<window.Icon name="mail" size={16}/>} onClick={()=>onNav('contact')}>非公開物件を相談する</SButton>
        </div>
      </window.Container>

      <window.Container style={{ paddingTop:'var(--sp-8)', paddingBottom: isMobile?'var(--sp-16)':'var(--sp-20)' }}>
        <div style={{ display:'grid', gridTemplateColumns: isMobile?'1fr':'264px 1fr', gap:'var(--sp-8)' }}>
          {/* ── Filter rail ── */}
          {isMobile ? (
            <div>
              <SButton variant="secondary" full iconLeft={<window.Icon name="filter" size={16}/>} onClick={()=>setShowFilters(v=>!v)}>
                絞り込み条件{showFilters?'を閉じる':'を開く'}
              </SButton>
              {showFilters && <div style={{ marginTop:'var(--sp-4)' }}>{FilterPanel}</div>}
            </div>
          ) : (
            <aside style={{ display:'flex', flexDirection:'column', gap:'var(--sp-5)' }}>{FilterPanel}</aside>
          )}

          {/* ── Results ── */}
          <div style={{ display:'flex', flexDirection:'column', gap:'var(--sp-5)' }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:16, flexWrap:'wrap' }}>
              <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                {FEATURE_FILTERS.map(f=>(
                  <STag key={f} selected={!!feat[f]} onClick={()=>setFeat(s=>({...s,[f]:!s[f]}))}>{f}</STag>
                ))}
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:8, flex:'none' }}>
                <span style={{ font:'var(--fw-medium) var(--t-xs)/1 var(--font-body)', color:'var(--text-muted)' }}>並び替え</span>
                <div style={{ width:150 }}>
                  <SSelect value={sort} onChange={e=>setSort(e.target.value)}
                    options={[{value:'new',label:'新着順'},{value:'low',label:'賃料が安い順'},{value:'high',label:'賃料が高い順'},{value:'size',label:'面積が広い順'}]} />
                </div>
              </div>
            </div>

            <div style={{ display:'grid', gridTemplateColumns:`repeat(${cols}, 1fr)`, gap: isMobile?'var(--sp-3)':'var(--sp-5)' }}>
              {list.map(p=>{
                const n = parseFloat(p.size);
                const cap = n ? `${Math.max(2,Math.round(n*0.4))}〜${Math.round(n*0.6)}名` : null;
                const specRow = (icon,label,val,wrap)=>(
                  <div style={{ display:'flex', alignItems:'flex-start', gap:6, minWidth:0 }}>
                    <window.Icon name={icon} size={13} style={{ color:'var(--text-faint)', flex:'none', marginTop:wrap?2:0 }}/>
                    {label && <span style={{ font:'var(--fw-regular) var(--t-2xs)/1.3 var(--font-body)', color:'var(--text-muted)', flex:'none', marginTop:wrap?1:0 }}>{label}</span>}
                    <span style={{ font:`var(--fw-medium) ${isMobile?'var(--t-2xs)':'var(--t-xs)'}/1.4 var(--font-body)`, color:'var(--text-muted)', minWidth:0,
                      ...(wrap ? {} : { whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }) }}>{val}</span>
                  </div>
                );
                return (
                  <div key={p.id} style={{ display:'flex', flexDirection:'column', background:'var(--surface)', border:'1px solid var(--border-subtle)',
                    borderRadius:'var(--r-md)', overflow:'hidden', boxShadow:'var(--shadow-sm)' }}>
                    {/* photo + badges */}
                    <div style={{ position:'relative', cursor:'pointer' }} onClick={()=>onOpen(p)}>
                      <window.Photo src={p.img} alt={p.name} hue={p.hue} ratio="16 / 10" icon="building" />
                      <div style={{ position:'absolute', top:10, left:10, display:'flex', gap:6, flexWrap:'wrap' }}>
                        <SBg tone={p.type} size="xs">{p.typeLabel}</SBg>
                        {p.isNew && <SBg tone="info" solid size="xs">NEW</SBg>}
                      </div>
                      <button aria-label="お気に入り" onClick={(e)=>{ e.stopPropagation(); onToggleSave(p.id); }}
                        style={{ position:'absolute', ...(isMobile ? { bottom:8, left:8 } : { top:8, right:8 }), width:30, height:30, borderRadius:'var(--r-pill)', border:'none',
                          background:'rgba(255,255,255,0.92)', boxShadow:'var(--shadow-xs)', cursor:'pointer', display:'grid', placeItems:'center',
                          color: saved[p.id]?'var(--blue-600)':'var(--text-muted)' }}>
                        <window.Icon name="heart" size={15} fill={saved[p.id]?'currentColor':'none'}/>
                      </button>
                    </div>
                    {/* body */}
                    <div style={{ padding: isMobile?'var(--sp-3) var(--sp-4) var(--sp-4)':'var(--sp-5)', display:'flex', flexDirection:'column', gap: isMobile?6:8, flex:1 }}>
                      <h3 onClick={()=>onOpen(p)} style={{ margin:0, cursor:'pointer', font:`var(--fw-bold) ${isMobile?'var(--t-base)':'var(--t-h4)'}/1.4 var(--font-display)`, color:'var(--blue-900)',
                        display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden' }}>{p.name}</h3>
                      <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
                        {specRow('pin','', p.area, true)}
                        {specRow('train','', p.access, true)}
                      </div>
                      <div style={{ display:'grid', gridTemplateColumns: isMobile?'1fr':'1fr 1fr', gap:'4px 10px' }}>
                        {specRow('ruler','面積', p.size)}
                        {cap && specRow('users','人数', cap)}
                      </div>
                      <div style={{ display:'flex', alignItems:'baseline', gap:6 }}>
                        <span style={{ font:`var(--fw-bold) ${isMobile?'1.05rem':'1.25rem'}/1 var(--font-num)`, color:'var(--blue-900)', whiteSpace:'nowrap' }}>{p.rent}</span>
                      </div>
                      {p.zeroCommission && <div><SBg tone="amber" size="sm">仲介手数料0円</SBg></div>}
                      <div style={{ display:'flex', flexDirection: isMobile?'column':'row', gap:8, marginTop:'auto', paddingTop:6 }}>
                        <SButton variant="primary" size="sm" full pill onClick={()=>onOpen(p)}>詳細を見る</SButton>
                        {!isMobile && <SButton variant="secondary" size="sm" full iconLeft={<window.Icon name="mail" size={14}/>} onClick={()=>onNav('contact')}>相談</SButton>}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            <div style={{ display:'flex', alignItems:'center', justifyContent:'center', gap:6, marginTop:'var(--sp-8)' }}>
              <PageBtn disabled><window.Icon name="chevL" size={16}/></PageBtn>
              {[1,2,3,4,5].map(n=>(<PageBtn key={n} active={n===1}>{n}</PageBtn>))}
              <PageBtn><window.Icon name="chevR" size={16}/></PageBtn>
            </div>
          </div>
        </div>
      </window.Container>
    </main>
  );
}

function PageBtn({ children, active, disabled }) {
  return (
    <button disabled={disabled} style={{ minWidth:40, height:40, padding:'0 10px', cursor: disabled?'not-allowed':'pointer',
      borderRadius:'var(--r-sm)', border:`1px solid ${active?'var(--blue-900)':'var(--border-default)'}`,
      background: active?'var(--blue-900)':'var(--surface)', color: active?'#fff':'var(--text-body)',
      opacity: disabled?0.4:1, font:'var(--fw-bold) var(--t-sm)/1 var(--font-num)',
      display:'inline-flex', alignItems:'center', justifyContent:'center' }}>{children}</button>
  );
}

Object.assign(window, { SearchScreen });
