// Pantalla Importar — pega URL de portal, Worker la descarga y Claude la parsea
const DEFAULT_WORKER_URL = 'https://busquedainmuebles.edinsonja.workers.dev';

function ImportScreen({ onClose, onImported }) {
  const T = useTheme();
  const [url, setUrl] = React.useState('');
  const [phase, setPhase] = React.useState('idle'); // idle | loading | result | error
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [showConfig, setShowConfig] = React.useState(false);
  const [cfgWorker, setCfgWorker] = React.useState(
    localStorage.getItem('bi.workerUrl') || DEFAULT_WORKER_URL
  );
  const [cfgToken, setCfgToken] = React.useState(localStorage.getItem('bi.token') || '');

  // Detectar al montar si falta configuración → abrir setup automáticamente
  React.useEffect(() => {
    const wu = localStorage.getItem('bi.workerUrl');
    const tk = localStorage.getItem('bi.token');
    if (!wu || !tk) setShowConfig(true);
  }, []);

  const saveConfig = () => {
    if (!cfgWorker.trim() || !cfgToken.trim()) return;
    localStorage.setItem('bi.workerUrl', cfgWorker.trim());
    localStorage.setItem('bi.token', cfgToken.trim());
    setShowConfig(false);
  };

  const PORTALS_INFO = [
    { name: 'Metrocuadrado',  example: 'https://www.metrocuadrado.com/inmueble/...' },
    { name: 'Finca Raíz',     example: 'https://www.fincaraiz.com.co/inmueble/...' },
    { name: 'Ciencuadras',    example: 'https://www.ciencuadras.com/inmueble/...' },
    { name: 'MercadoLibre',   example: 'https://inmuebles.mercadolibre.com.co/...' },
  ];

  const submit = async () => {
    if (!url.trim()) return;
    setPhase('loading');
    setError(null);
    setResult(null);

    const workerUrl = (localStorage.getItem('bi.workerUrl') || '').replace(/\/$/, '');
    const tok = localStorage.getItem('bi.token') || '';
    if (!workerUrl || !tok) {
      setPhase('error');
      setError('Configura primero el Worker — toca "Configurar conexión" abajo.');
      setShowConfig(true);
      return;
    }

    // Timeout explícito (90s — más que suficiente para fetch del portal + Claude)
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 90000);
    const startedAt = Date.now();

    try {
      const resp = await fetch(workerUrl + '/import', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tok },
        body: JSON.stringify({ url: url.trim() }),
        signal: controller.signal,
        keepalive: true,
      });
      clearTimeout(timeoutId);
      let data = null;
      try { data = await resp.json(); } catch (_) { /* ignore */ }
      if (!resp.ok) {
        setPhase('error');
        setError((data && (data.detail || data.error)) || ('HTTP ' + resp.status));
        return;
      }
      setResult(data);
      setPhase('result');
    } catch (e) {
      clearTimeout(timeoutId);
      setPhase('error');
      const elapsed = ((Date.now() - startedAt) / 1000).toFixed(1);
      if (e.name === 'AbortError') {
        setError('Tiempo agotado a los ' + elapsed + 's. El portal puede estar lento o tu conexión es inestable. Reintenta.');
      } else if (/load failed|network|failed to fetch/i.test(e.message || '')) {
        setError('La red interrumpió la petición a los ' + elapsed + 's. ' +
                 'En iPhone con modo de bajo consumo activo, Safari corta fetches largos. ' +
                 'Desactiva bajo consumo o intenta de nuevo con buena señal.');
      } else {
        setError(e.message || 'Error desconocido');
      }
    }
  };

  const testConnection = async () => {
    setPhase('loading');
    setError(null);
    const workerUrl = (cfgWorker || localStorage.getItem('bi.workerUrl') || '').replace(/\/$/, '');
    const tok = cfgToken || localStorage.getItem('bi.token') || '';
    if (!workerUrl) { setPhase('error'); setError('Falta Worker URL'); return; }
    try {
      const t0 = Date.now();
      // /health no requiere auth; valida que el Worker responde
      const r1 = await fetch(workerUrl + '/health', { cache: 'no-store' });
      const healthOk = r1.ok && (await r1.text()).trim() === 'ok';
      const lat = Date.now() - t0;
      if (!healthOk) { setPhase('error'); setError('/health no respondió ok (HTTP ' + r1.status + ')'); return; }
      // Si hay token, intentamos /analyze con body inválido para validar bearer
      if (tok) {
        const r2 = await fetch(workerUrl + '/analyze', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tok },
          body: '{}',
        });
        if (r2.status === 401) { setPhase('error'); setError('Token rechazado (401). Verifica el BI_TOKEN.'); return; }
        // 400 es OK aquí: significa que pasó el auth y falló por body inválido
      }
      setPhase('idle');
      setError(null);
      alert('Conexión OK. /health: ' + lat + 'ms. Token: ' + (tok ? 'válido' : 'no probado'));
    } catch (e) {
      setPhase('error');
      setError('No se pudo contactar al Worker: ' + (e.message || e.name));
    }
  };

  const accept = () => {
    if (!result || !result.property) return;
    onImported(result.property);
    onClose();
  };

  return (
    <div style={{ background: T.bg, minHeight: '100%', paddingBottom: 100 }}>
      {/* Header */}
      <div style={{
        padding: '60px 20px 14px',
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
            letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 6 }}>
            Importar URL
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 32, color: T.ink, lineHeight: 1, fontWeight: 400 }}>
            Pega un <span style={{ fontStyle: 'italic' }}>listing</span>
          </div>
        </div>
        <button onClick={onClose} style={{
          appearance: 'none', cursor: 'pointer', padding: '8px 14px', borderRadius: 999,
          background: 'transparent', color: T.ink, border: '0.5px solid ' + T.line,
          fontFamily: T.sans, fontSize: 13, fontWeight: 500,
        }}>Cerrar</button>
      </div>

      {/* Configuración inline (se abre solo si faltan credenciales) */}
      {showConfig && (
        <div style={{ padding: '0 20px 14px' }}>
          <div style={{
            padding: 14, borderRadius: T.radius,
            background: T.ink, color: T.bg,
          }}>
            <div style={{ fontFamily: T.sans, fontSize: 11, opacity: 0.7,
              letterSpacing: 1, textTransform: 'uppercase', marginBottom: 10, fontWeight: 600 }}>
              Configurar conexión
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 12.5, opacity: 0.78,
              lineHeight: 1.5, marginBottom: 14 }}>
              Pega el <span style={{ fontWeight: 600 }}>BI_TOKEN</span> que generaste con
              <span style={{ fontFamily: T.mono }}> openssl rand -hex 32</span>. La URL del Worker ya viene prellenada.
            </div>

            <div style={{ fontFamily: T.sans, fontSize: 10, opacity: 0.55,
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 4 }}>
              Worker URL
            </div>
            <input
              type="url"
              value={cfgWorker}
              onChange={(e) => setCfgWorker(e.target.value)}
              autoCapitalize="off" autoCorrect="off" spellCheck={false}
              style={{
                width: '100%', boxSizing: 'border-box', border: 'none', outline: 'none',
                background: 'rgba(255,255,255,0.08)', color: T.bg,
                fontFamily: T.mono, fontSize: 12, padding: '10px 12px',
                borderRadius: 8, marginBottom: 10,
              }}/>

            <div style={{ fontFamily: T.sans, fontSize: 10, opacity: 0.55,
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 4 }}>
              BI_TOKEN
            </div>
            <input
              type="text"
              value={cfgToken}
              onChange={(e) => setCfgToken(e.target.value)}
              autoCapitalize="off" autoCorrect="off" spellCheck={false}
              placeholder="pega aquí el token de 64 caracteres"
              style={{
                width: '100%', boxSizing: 'border-box', border: 'none', outline: 'none',
                background: 'rgba(255,255,255,0.08)', color: T.bg,
                fontFamily: T.mono, fontSize: 12, padding: '10px 12px',
                borderRadius: 8, marginBottom: 14,
              }}/>

            <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              {(localStorage.getItem('bi.workerUrl') && localStorage.getItem('bi.token')) && (
                <button onClick={() => setShowConfig(false)} style={{
                  appearance: 'none', cursor: 'pointer',
                  padding: '11px 16px', borderRadius: 999,
                  background: 'transparent', color: T.bg,
                  border: '0.5px solid rgba(255,255,255,0.3)',
                  fontFamily: T.sans, fontSize: 13, fontWeight: 500,
                }}>Cancelar</button>
              )}
              <button onClick={saveConfig} style={{
                appearance: 'none', cursor: 'pointer', flex: 1,
                padding: '11px 16px', borderRadius: 999,
                background: T.bg, color: T.ink, border: 'none',
                fontFamily: T.sans, fontSize: 14, fontWeight: 600,
              }}>Guardar y continuar</button>
            </div>
            <button onClick={testConnection} style={{
              appearance: 'none', cursor: 'pointer', width: '100%',
              padding: '9px 12px', borderRadius: 999,
              background: 'transparent', color: T.bg,
              border: '0.5px solid rgba(255,255,255,0.25)',
              fontFamily: T.sans, fontSize: 12, fontWeight: 500,
            }}>Probar conexión</button>
          </div>
        </div>
      )}

      {/* Input */}
      <div style={{ padding: '0 20px 14px' }}>
        <div style={{
          padding: 14, borderRadius: T.radius,
          background: T.surf, border: '0.5px solid ' + T.line,
        }}>
          <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
            letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8 }}>
            URL del inmueble
          </div>
          <input
            type="url"
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
            placeholder="https://www.metrocuadrado.com/inmueble/…"
            disabled={phase === 'loading'}
            style={{
              width: '100%', boxSizing: 'border-box', border: 'none', outline: 'none',
              background: 'transparent', fontFamily: T.mono, fontSize: 13, color: T.ink,
              padding: '8px 0', borderBottom: '0.5px solid ' + T.line,
            }}/>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <Pill primary full onClick={submit}>
              {phase === 'loading' ? 'Importando…' : 'Importar inmueble'}
            </Pill>
          </div>
        </div>
      </div>

      {/* Estado de carga */}
      {phase === 'loading' && (
        <div style={{ padding: '0 20px 16px' }}>
          <div style={{
            padding: 16, borderRadius: T.radius, background: T.ink, color: T.bg,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div className="bi-pulse" style={{
              width: 8, height: 8, borderRadius: 999, background: T.accent,
            }}/>
            <div>
              <div style={{ fontFamily: T.sans, fontSize: 13, fontWeight: 500 }}>
                Descargando del portal y leyendo con IA…
              </div>
              <div style={{ fontFamily: T.sans, fontSize: 11, opacity: 0.6, marginTop: 2 }}>
                Tarda ~3-6 segundos
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Error */}
      {phase === 'error' && (
        <div style={{ padding: '0 20px 16px' }}>
          <div style={{
            padding: 16, borderRadius: T.radius,
            background: 'rgba(181,72,46,0.08)', border: '0.5px solid rgba(181,72,46,0.25)',
          }}>
            <div style={{ fontFamily: T.sans, fontSize: 12, color: T.bad, fontWeight: 600,
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>
              No se pudo importar
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink, lineHeight: 1.5 }}>
              {error}
            </div>
          </div>
        </div>
      )}

      {/* Resultado */}
      {phase === 'result' && result && (
        <div style={{ padding: '0 20px 16px' }}>
          <div style={{
            padding: 16, borderRadius: T.radius,
            background: T.surf, border: '0.5px solid ' + T.line,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              marginBottom: 10,
            }}>
              <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
                letterSpacing: 1, textTransform: 'uppercase', fontWeight: 500 }}>
                Extraído por IA
              </div>
              <div style={{
                fontFamily: T.mono, fontSize: 11, padding: '3px 8px', borderRadius: 999,
                background: result.property._confidence >= 70 ? 'rgba(63,122,78,0.10)' : 'rgba(199,110,74,0.10)',
                color:      result.property._confidence >= 70 ? T.good : T.warn,
              }}>conf: {result.property._confidence}/100</div>
            </div>

            <div style={{ fontFamily: T.serif, fontSize: 22, color: T.ink, lineHeight: 1.15, marginBottom: 4 }}>
              {result.property.title}
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 12, color: T.ink2, marginBottom: 12 }}>
              {result.property.sector} · {result.property.city} · {result.property.type} · Estrato {result.property.estrato || '?'}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <Cell label="Precio" value={fmt.copFull(result.property.price)} />
              <Cell label="Área"   value={fmt.m2(result.property.areaM2)} />
              <Cell label="Hab."   value={result.property.rooms || '—'} />
              <Cell label="Baños"  value={result.property.baths || '—'} />
              <Cell label="Parq."  value={result.property.parking ?? '—'} />
              <Cell label="$/m²"   value={fmt.cop(result.property.price / Math.max(1, result.property.areaM2))} />
            </div>

            {result.property._missing && result.property._missing.length > 0 && (
              <div style={{ marginTop: 12, padding: 10, borderRadius: 8,
                background: T.surf2, fontFamily: T.sans, fontSize: 11, color: T.ink2 }}>
                Faltó: {result.property._missing.join(', ')}
              </div>
            )}

            <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
              <Pill onClick={() => { setPhase('idle'); setUrl(''); setResult(null); }}>Otro</Pill>
              <Pill primary full onClick={accept}>Agregar al ranking</Pill>
            </div>

            <div style={{ marginTop: 10, fontFamily: T.mono, fontSize: 9.5, color: T.ink3,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {result.property.sourceUrl}
            </div>
          </div>
        </div>
      )}

      {/* Portales soportados */}
      <div style={{ padding: '8px 20px 16px' }}>
        <div style={{ fontFamily: T.sans, fontSize: 11, color: T.ink2,
          letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 10 }}>
          Portales soportados
        </div>
        <div style={{
          padding: 12, borderRadius: T.radius,
          background: T.surf, border: '0.5px solid ' + T.line,
        }}>
          {PORTALS_INFO.map((p, i) => (
            <div key={p.name} style={{
              padding: '8px 0', display: 'flex', alignItems: 'center', gap: 10,
              borderBottom: i === PORTALS_INFO.length - 1 ? 'none' : '0.5px solid ' + T.line,
            }}>
              <div style={{ width: 6, height: 6, borderRadius: 999, background: T.accent }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink, fontWeight: 500 }}>
                  {p.name}
                </div>
                <div style={{ fontFamily: T.mono, fontSize: 9.5, color: T.ink3, marginTop: 2 }}>
                  {p.example}
                </div>
              </div>
            </div>
          ))}
        </div>
        <div style={{
          marginTop: 10, fontFamily: T.sans, fontSize: 11, color: T.ink2,
          fontStyle: 'italic', lineHeight: 1.5,
        }}>
          Cada importación cuesta ~$0.002 USD. Los datos se guardan en este dispositivo.
        </div>
        {!showConfig && (
          <div style={{ marginTop: 14, display: 'flex', justifyContent: 'center', gap: 18 }}>
            <button onClick={() => setShowConfig(true)} style={{
              appearance: 'none', cursor: 'pointer', border: 'none',
              background: 'transparent', color: T.ink2,
              fontFamily: T.sans, fontSize: 11.5, textDecoration: 'underline',
              padding: 6,
            }}>Reconfigurar conexión</button>
            <button onClick={() => {
              const n = (JSON.parse(localStorage.getItem('bi.imported') || '[]')).length;
              if (n === 0) {
                alert('No hay inmuebles importados para borrar.');
                return;
              }
              if (!confirm('Borrar ' + n + ' inmueble' + (n>1?'s':'') + ' importado' + (n>1?'s':'') + '? Esta acción es local y no afecta los portales.')) return;
              localStorage.removeItem('bi.imported');
              alert('Listo. Vuelve a abrir la app para ver los cambios.');
              location.reload();
            }} style={{
              appearance: 'none', cursor: 'pointer', border: 'none',
              background: 'transparent', color: T.bad,
              fontFamily: T.sans, fontSize: 11.5, textDecoration: 'underline',
              padding: 6,
            }}>Borrar importados</button>
          </div>
        )}
      </div>
    </div>
  );
}

function Cell({ label, value }) {
  const T = useTheme();
  return (
    <div style={{
      padding: 10, borderRadius: 10, background: T.surf2,
    }}>
      <div style={{ fontFamily: T.sans, fontSize: 9.5, color: T.ink2,
        letterSpacing: 0.6, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontFamily: T.mono, fontSize: 14, color: T.ink, fontWeight: 500, marginTop: 3 }}>
        {value}
      </div>
    </div>
  );
}

Object.assign(window, { ImportScreen });
