// ECR Property Summary — main app
const { useState, useMemo, useEffect, useRef } = React;

function App() {
  const [typeFilter, setTypeFilter] = useState('All');
  const [status, setStatus] = useState('All');
  const [sort, setSort] = useState('default');
  const [favoriteIds, setFavoriteIds] = useState(() => {
    try { return new Set(JSON.parse(localStorage.getItem('ecr-favs') || '[]')); } catch { return new Set(); }
  });
  const [showFavsOnly, setShowFavsOnly] = useState(false);
  const [hoveredId, setHoveredId] = useState(null);
  const [activeId, setActiveId] = useState(PROPERTIES[0].id);
  const [fullscreenId, setFullscreenId] = useState(null);
  const listRef = useRef(null);

  // Persist favorites
  useEffect(() => {
    try { localStorage.setItem('ecr-favs', JSON.stringify([...favoriteIds])); } catch {}
  }, [favoriteIds]);

  const toggleFav = (id) => {
    setFavoriteIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  // Filter + sort
  const filtered = useMemo(() => {
    let list = PROPERTIES.filter(p => {
      if (typeFilter !== 'All' && p.type !== typeFilter) return false;
      if (status !== 'All' && p.status !== status) return false;
      if (showFavsOnly && !favoriteIds.has(p.id)) return false;
      return true;
    });
    if (sort === 'sf-desc') list = [...list].sort((a, b) => b.sf - a.sf);
    else if (sort === 'sf-asc') list = [...list].sort((a, b) => a.sf - b.sf);
    else if (sort === 'rate-asc') list = [...list].sort((a, b) => a.rateNum - b.rateNum);
    else if (sort === 'rate-desc') list = [...list].sort((a, b) => b.rateNum - a.rateNum);
    return list;
  }, [typeFilter, status, sort, showFavsOnly, favoriteIds]);

  // Make sure active property exists in filtered list; otherwise pick first
  useEffect(() => {
    if (filtered.length === 0) return;
    if (!filtered.some(p => p.id === activeId)) {
      setActiveId(filtered[0].id);
    }
  }, [filtered, activeId]);

  const activeProperty = useMemo(
    () => PROPERTIES.find(p => p.id === activeId) || filtered[0] || PROPERTIES[0],
    [activeId, filtered]
  );

  // Auto-scroll list when active changes
  useEffect(() => {
    if (!listRef.current) return;
    const el = listRef.current.querySelector(`[data-pid="${activeId}"]`);
    if (el && typeof el.scrollIntoView === 'function') {
      // Use parent-level scrollTop to avoid the whole page jumping
      const container = listRef.current;
      const rect = el.getBoundingClientRect();
      const cRect = container.getBoundingClientRect();
      if (rect.top < cRect.top || rect.bottom > cRect.bottom) {
        container.scrollTop += rect.top - cRect.top - 12;
      }
    }
  }, [activeId]);

  // Fullscreen prev/next
  const fullscreenIdx = filtered.findIndex(p => p.id === fullscreenId);
  const fullscreenProperty = fullscreenId ? PROPERTIES.find(p => p.id === fullscreenId) : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh', background: ECR.cream80 }}>
      <SiteHeader />
      <FilterToolbar
        count={filtered.length} total={PROPERTIES.length}
        typeFilter={typeFilter} onTypeFilter={setTypeFilter}
        status={status} onStatus={setStatus}
        sort={sort} onSort={setSort}
        favCount={favoriteIds.size}
        showFavs={showFavsOnly} onToggleFavs={() => setShowFavsOnly(s => !s)}
      />

      {/* Main 3-col split — explicit pixel height so flex children sized correctly */}
      <div style={{
        flex: 'none',
        display: 'flex',
        height: 'min(900px, calc(100vh - 68px - 86px - 72px))',
        minHeight: 560,
        overflow: 'hidden',
        background: ECR.white,
        borderTop: `1px solid ${ECR.grayLight}`,
      }}>

        {/* COLUMN 1 — Property list */}
        <div ref={listRef} style={{
          width: 296,
          flexShrink: 0,
          borderRight: `1px solid ${ECR.grayLight}`,
          background: ECR.cream80,
          overflowY: 'auto',
          display: 'flex',
          flexDirection: 'column',
        }}>
          <div style={{ padding: '14px 16px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', background: ECR.white, borderBottom: `1px solid ${ECR.grayLight}`, position: 'sticky', top: 0, zIndex: 2 }}>
            <div style={{ fontFamily: 'Montserrat', fontWeight: 700, fontSize: 9, letterSpacing: '0.26em', textTransform: 'uppercase', color: ECR.charcoal }}>
              Property List
            </div>
            <div style={{ fontFamily: 'Montserrat', fontWeight: 600, fontSize: 9, letterSpacing: '0.12em', color: ECR.grayMid }}>
              {filtered.length} <span style={{ color: ECR.charcoal20 }}>/ {PROPERTIES.length}</span>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '14px 12px 16px' }}>
            {filtered.length === 0 ? (
              <div style={{ padding: '30px 12px', textAlign: 'center', fontFamily: 'FreightText', fontSize: 13, lineHeight: 1.6, color: ECR.charcoal70 }}>
                No properties match these filters.<br />
                <a href="#" onClick={(e) => { e.preventDefault(); setTypeFilter('All'); setStatus('All'); setShowFavsOnly(false); }} style={{ color: ECR.red, textDecoration: 'underline' }}>Clear filters</a>
              </div>
            ) : filtered.map((p, idx) => (
              <div key={p.id} data-pid={p.id}>
                <ListCard
                  property={p}
                  index={idx}
                  isActive={p.id === activeId}
                  isFav={favoriteIds.has(p.id)}
                  onClick={() => setActiveId(p.id)}
                  onHover={setHoveredId}
                  onToggleFav={toggleFav}
                />
              </div>
            ))}
          </div>
        </div>

        {/* COLUMN 2 — Map */}
        <div style={{ flex: 1, position: 'relative', minWidth: 0, overflow: 'hidden', borderRight: `1px solid ${ECR.grayLight}` }}>
          <AustinMap
            properties={filtered}
            activeId={activeId}
            hoveredId={hoveredId}
            favoriteIds={favoriteIds}
            onHover={setHoveredId}
            onSelect={setActiveId}
          />

          {/* Floating top-left legend */}
          <div style={{ position: 'absolute', top: 16, left: 16, background: ECR.white, padding: '12px 16px', boxShadow: '0 4px 12px rgba(63,68,67,0.12)', pointerEvents: 'none', maxWidth: 360 }}>
            <div style={{ fontFamily: 'Montserrat', fontWeight: 600, fontSize: 8, letterSpacing: '0.26em', textTransform: 'uppercase', color: ECR.red, marginBottom: 4 }}>Greater Austin · TX</div>
            <div style={{ fontFamily: 'Montserrat', fontWeight: 700, fontSize: 12, letterSpacing: '0.10em', textTransform: 'uppercase', color: ECR.charcoal, marginBottom: 6 }}>
              {filtered.length} {filtered.length === 1 ? 'Property' : 'Properties'} Plotted
            </div>
            <div style={{ display: 'flex', gap: 12, paddingTop: 6, borderTop: `1px solid ${ECR.charcoal10}` }}>
              {['Office', 'Industrial', 'Medical', 'Land'].map(t => (
                <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 4, background: TYPE_COLORS[t] }}></span>
                  <span style={{ fontFamily: 'Montserrat', fontWeight: 600, fontSize: 7.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: ECR.charcoal70 }}>{t}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Bottom-right attribution */}
          <div style={{ position: 'absolute', bottom: 12, right: 16, fontFamily: 'Montserrat', fontWeight: 500, fontSize: 8, letterSpacing: '0.16em', textTransform: 'uppercase', color: ECR.charcoal70, opacity: 0.6, pointerEvents: 'none' }}>
            ECR // Schematic — not to scale
          </div>
        </div>

        {/* COLUMN 3 — Detail panel */}
        <div style={{ width: 520, flexShrink: 0, display: 'flex', flexDirection: 'column' }}>
          {activeProperty && (
            <DetailPanel
              property={activeProperty}
              isFav={favoriteIds.has(activeProperty.id)}
              onToggleFav={() => toggleFav(activeProperty.id)}
              onOpenFullscreen={() => setFullscreenId(activeProperty.id)}
            />
          )}
        </div>
      </div>

      <SiteFooter />

      {/* Fullscreen detail overlay */}
      {fullscreenProperty && (
        <FullscreenDetail
          property={fullscreenProperty}
          isFav={favoriteIds.has(fullscreenProperty.id)}
          onToggleFav={() => toggleFav(fullscreenProperty.id)}
          onClose={() => setFullscreenId(null)}
          onPrev={() => {
            if (fullscreenIdx > 0) setFullscreenId(filtered[fullscreenIdx - 1].id);
            else setFullscreenId(filtered[filtered.length - 1].id);
          }}
          onNext={() => {
            if (fullscreenIdx < filtered.length - 1) setFullscreenId(filtered[fullscreenIdx + 1].id);
            else setFullscreenId(filtered[0].id);
          }}
        />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
