// App principal — router de pantallas + tab bar + tweaks
function App() {
  const [tweaks, setTweak] = useTweaks(window.__BI_DEFAULTS || {
    accent: '#5A6B3F',
    dark: false,
    dense: false,
    detail: true,
    showOnboarding: false,
  });

  // expose theme to components
  window.__bi_theme = {
    dark: tweaks.dark, dense: tweaks.dense, detail: tweaks.detail, accent: tweaks.accent,
  };

  const T = useTheme();
  const [criteria, setCriteria] = React.useState(window.DEFAULT_CRITERIA);
  const [tab, setTab] = React.useState('home');
  const [stack, setStack] = React.useState([]);  // overlay stack: 'detail', 'criteria', 'import'
  const [currentId, setCurrentId] = React.useState(null);
  const [savedIds, setSavedIds] = React.useState([]);
  const [compareIds, setCompareIds] = React.useState([]);
  const [query, setQuery] = React.useState('');
  const [showOnb, setShowOnb] = React.useState(tweaks.showOnboarding);
  const [, forceRender] = React.useState(0);

  React.useEffect(() => {
    setShowOnb(tweaks.showOnboarding);
  }, [tweaks.showOnboarding]);

  // Cargar imports persistidos al montar y empujarlos a window.PROPERTIES
  // (los screens existentes leen window.PROPERTIES, así heredan los imports
  // sin cambios en el ranking, mapa, comparador, etc.)
  React.useEffect(() => {
    try {
      const raw = localStorage.getItem('bi.imported');
      if (!raw) return;
      const arr = JSON.parse(raw);
      if (!Array.isArray(arr)) return;
      const existing = new Set(window.PROPERTIES.map(p => p.id));
      arr.forEach(p => { if (!existing.has(p.id)) window.PROPERTIES.push(p); });
      forceRender(n => n + 1);
    } catch (e) { /* ignore */ }
  }, []);

  const openProperty = (id) => { setCurrentId(id); setStack([...stack, 'detail']); };
  const closeOverlay = () => setStack(stack.slice(0, -1));
  const openCriteria = () => setStack([...stack, 'criteria']);
  const openImport   = () => setStack([...stack, 'import']);

  const onImported = (property) => {
    window.PROPERTIES.push(property);
    try {
      const raw = localStorage.getItem('bi.imported');
      const arr = raw ? JSON.parse(raw) : [];
      arr.push(property);
      localStorage.setItem('bi.imported', JSON.stringify(arr));
    } catch (e) { /* ignore */ }
    forceRender(n => n + 1);
    // Abrimos el detalle inmediatamente
    setCurrentId(property.id);
    setStack(['detail']);
  };

  const toggleSave = (id) => {
    setSavedIds(savedIds.includes(id) ? savedIds.filter(x => x !== id) : [...savedIds, id]);
  };
  const addCompare = (id) => {
    if (compareIds.includes(id)) return;
    setCompareIds(compareIds.length >= 3 ? [...compareIds.slice(1), id] : [...compareIds, id]);
    setTab('compare'); setStack([]);
  };

  const tabs = [
    { id: 'home',     label: 'Inicio',  icon: HomeIcon },
    { id: 'map',      label: 'Mapa',    icon: MapIcon },
    { id: 'compare',  label: 'Comparar', icon: CompareIcon, badge: compareIds.length },
    { id: 'saved',    label: 'Guardados', icon: SaveIcon, badge: savedIds.length },
  ];

  return (
    <div style={{ height: '100%', position: 'relative', background: T.bg, color: T.ink }}>
      {showOnb && <Onboarding onDone={() => setShowOnb(false)} />}

      {/* Pantalla activa */}
      {tab === 'home' && (
        <HomeScreen
          criteria={criteria}
          query={query}
          onQuery={setQuery}
          onOpenProperty={openProperty}
          onOpenCriteria={openCriteria}
          onOpenMap={() => setTab('map')}
          onOpenImport={openImport}
        />
      )}
      {tab === 'map' && (
        <MapScreen criteria={criteria} onOpenProperty={openProperty} />
      )}
      {tab === 'compare' && (
        <CompareScreen ids={compareIds} criteria={criteria}
          onRemove={(id) => setCompareIds(compareIds.filter(x => x !== id))}
          onAdd={() => setTab('home')}
          onOpenProperty={openProperty}/>
      )}
      {tab === 'saved' && (
        <SavedScreen savedIds={savedIds} criteria={criteria}
          onOpenProperty={openProperty}
          onRemove={(id) => setSavedIds(savedIds.filter(x => x !== id))}/>
      )}

      {/* Overlays (detail / criteria) */}
      {stack.includes('detail') && currentId && (
        <Overlay>
          <DetailScreen
            propertyId={currentId}
            criteria={criteria}
            onBack={closeOverlay}
            onCompare={addCompare}
            onSave={toggleSave}
            savedIds={savedIds}
          />
        </Overlay>
      )}
      {stack.includes('criteria') && (
        <Overlay>
          <CriteriaScreen criteria={criteria} setCriteria={setCriteria} onClose={closeOverlay}/>
        </Overlay>
      )}
      {stack.includes('import') && (
        <Overlay>
          <ImportScreen onClose={closeOverlay} onImported={onImported}/>
        </Overlay>
      )}

      {/* Tab bar */}
      <TabBar tabs={tabs} active={tab} onChange={setTab} />

      {/* Tweaks panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Marca">
          <TweakColor label="Color acento" value={tweaks.accent}
            options={['#5A6B3F','#3F5C6B','#8B6F3F','#6B3F5A','#1A1714']}
            onChange={(v) => setTweak('accent', v)}/>
        </TweakSection>
        <TweakSection label="Modo">
          <TweakRadio label="Tema" value={tweaks.dark ? 'dark' : 'light'}
            options={[{ value: 'light', label: 'Claro' }, { value: 'dark', label: 'Oscuro' }]}
            onChange={(v) => setTweak('dark', v === 'dark')}/>
          <TweakRadio label="Densidad" value={tweaks.dense ? 'compact' : 'relaxed'}
            options={[{ value: 'relaxed', label: 'Aireada' }, { value: 'compact', label: 'Densa' }]}
            onChange={(v) => setTweak('dense', v === 'compact')}/>
        </TweakSection>
        <TweakSection label="Resultados">
          <TweakToggle label="Mostrar score detallado en cards" value={tweaks.detail}
            onChange={(v) => setTweak('detail', v)}/>
          <TweakButton onClick={() => setTweak('showOnboarding', true)} label="Ver onboarding" />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function Overlay({ children }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'inherit',
      animation: 'bi-slide 0.32s cubic-bezier(0.2, 0.8, 0.2, 1)',
      overflow: 'auto', zIndex: 5,
    }}>
      {children}
    </div>
  );
}

function TabBar({ tabs, active, onChange }) {
  const T = useTheme();
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      paddingBottom: 26, paddingTop: 6,
      background: T.bg + 'EE', backdropFilter: 'blur(20px) saturate(180%)',
      WebkitBackdropFilter: 'blur(20px) saturate(180%)',
      borderTop: `0.5px solid ${T.line}`, zIndex: 40,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-around', padding: '4px 12px' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => onChange(t.id)} style={{
            appearance: 'none', border: 'none', background: 'transparent',
            cursor: 'pointer', padding: '6px 8px',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            minWidth: 60, position: 'relative',
          }}>
            <t.icon color={active === t.id ? T.ink : T.ink2}/>
            <span style={{
              fontFamily: T.sans, fontSize: 10, fontWeight: 500,
              color: active === t.id ? T.ink : T.ink2, letterSpacing: 0.1,
            }}>{t.label}</span>
            {t.badge > 0 && (
              <span style={{
                position: 'absolute', top: 2, right: 8,
                minWidth: 14, height: 14, padding: '0 3px', borderRadius: 999,
                background: T.accent, color: '#fff', fontFamily: T.mono, fontSize: 9,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{t.badge}</span>
            )}
          </button>
        ))}
      </div>
    </div>
  );
}

function HomeIcon({ color }) {
  return <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
    <path d="M3 10l8-7 8 7v9a1 1 0 01-1 1h-4v-6h-6v6H4a1 1 0 01-1-1v-9z"
      stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
  </svg>;
}
function MapIcon({ color }) {
  return <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
    <path d="M3 5l5-2 6 2 5-2v14l-5 2-6-2-5 2V5z" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
    <path d="M8 3v14M14 5v14" stroke={color} strokeWidth="1.5"/>
  </svg>;
}
function CompareIcon({ color }) {
  return <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
    <rect x="3" y="4" width="7" height="14" rx="1.5" stroke={color} strokeWidth="1.5"/>
    <rect x="12" y="7" width="7" height="11" rx="1.5" stroke={color} strokeWidth="1.5"/>
  </svg>;
}
function SaveIcon({ color }) {
  return <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
    <path d="M5 3h12v17l-6-4-6 4V3z" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
  </svg>;
}

// Onboarding (overlay sencillo)
function Onboarding({ onDone }) {
  const T = useTheme();
  const [step, setStep] = React.useState(0);
  const steps = [
    { kicker: 'Bienvenido', title: 'Tu búsqueda inmobiliaria, en una sola app.',
      body: 'BusquedaInmuebles rastrea portales nacionales y marketplaces sociales para entregarte solo los inmuebles que se ajustan a tu vida.' },
    { kicker: 'Cómo funciona', title: 'Tú defines criterios. Nosotros priorizamos.',
      body: 'Precio, área, estrato, sector, calle/carrera, piso, transporte, sostenibilidad… cada criterio tiene un peso ajustable.' },
    { kicker: 'Inteligencia de mercado', title: 'Sabemos cuánto vale en realidad.',
      body: 'En modo compra, una IA analiza dinámicamente la zona y te dice si la oferta tiene descuento o sobreprecio.' },
  ];
  const cur = steps[step];
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 200, background: T.bg,
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ flex: 1, padding: '90px 28px 0', display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.accent,
          letterSpacing: 2, textTransform: 'uppercase', marginBottom: 14, fontWeight: 600 }}>
          {cur.kicker}
        </div>
        <div style={{ fontFamily: T.serif, fontSize: 38, color: T.ink, lineHeight: 1.05,
          fontWeight: 400, letterSpacing: -0.5, marginBottom: 18 }}>
          {cur.title}
        </div>
        <div style={{ fontFamily: T.sans, fontSize: 15, color: T.ink2, lineHeight: 1.5 }}>
          {cur.body}
        </div>

        {/* Decoración */}
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px 0' }}>
          <div style={{
            width: 220, height: 220, borderRadius: 18,
            background: `linear-gradient(135deg, ${T.accent}DD 0%, ${T.ink} 120%)`,
            position: 'relative', overflow: 'hidden',
            boxShadow: '0 30px 60px rgba(26,23,20,0.25)',
          }}>
            <div style={{
              position: 'absolute', inset: 0,
              backgroundImage: `repeating-linear-gradient(135deg, rgba(255,255,255,0.06) 0 2px, transparent 2px 16px)`,
            }}/>
            <div style={{
              position: 'absolute', left: 18, bottom: 16,
              fontFamily: T.serif, fontSize: 60, color: '#fff', lineHeight: 1, fontStyle: 'italic',
            }}>0{step + 1}</div>
            <div style={{
              position: 'absolute', right: 16, top: 16,
              fontFamily: T.mono, fontSize: 10, color: '#fff', opacity: 0.7,
              letterSpacing: 1.5,
            }}>BI · v1.0</div>
          </div>
        </div>
      </div>

      <div style={{ padding: '20px 28px 40px' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 20 }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              flex: i === step ? 2 : 1, height: 3, borderRadius: 999,
              background: i <= step ? T.ink : T.line, transition: 'all 0.3s',
            }}/>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <Pill onClick={onDone}>Saltar</Pill>
          <div style={{ flex: 1 }}/>
          <Pill primary onClick={() => step < steps.length - 1 ? setStep(step + 1) : onDone()}>
            {step < steps.length - 1 ? 'Continuar →' : 'Comenzar'}
          </Pill>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { App });
