// BrokerTab_Rapide.jsx — Analyse rapide d'une fiche Centris
// No import/export — vanilla React 18 in-browser Babel

function BrokerTabRapide({ allListings, lang }) {
  const { useState: useRapideState, useEffect: useRapideEffect, useRef: useRapideRef } = React;

  const STORAGE_KEY = 'vestora_broker_recent';
  const MAX_RECENT = 10;

  const [inputVal, setInputVal] = useRapideState('');
  const [error, setError] = useRapideState('');
  const [notFound, setNotFound] = useRapideState(false);
  const [notFoundUrl, setNotFoundUrl] = useRapideState('');
  const [loading, setLoading] = useRapideState(false);
  const [copied, setCopied] = useRapideState(false);
  const [recents, setRecents] = useRapideState([]);
  const inputRef = useRapideRef(null);

  // Load history on mount
  useRapideEffect(() => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (raw) {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed)) {
          setRecents(parsed);
        }
      }
    } catch (_) {
      // ignore corrupt storage
    }
  }, []);

  function saveToRecent(listing) {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      let existing = [];
      try {
        const parsed = JSON.parse(raw);
        if (Array.isArray(parsed)) existing = parsed;
      } catch (_) {}

      // Dedupe by id (remove old entry if present)
      const deduped = existing.filter(item => String(item.id) !== String(listing.id));

      const entry = {
        id: listing.id,
        address: listing.address || listing.address_fr || listing.Address || '',
        city: listing.city || listing.City || '',
        price: listing.price || listing.Price || 0,
        timestamp: Date.now(),
      };

      const updated = [entry, ...deduped].slice(0, MAX_RECENT);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
      setRecents(updated);
    } catch (_) {
      // ignore storage errors
    }
  }

  function extractId(raw) {
    const trimmed = raw.trim();
    if (!trimmed) return null;

    // Pure numeric ID (7-9 digits typical for Centris, but accept any numeric)
    if (/^\d+$/.test(trimmed)) {
      return trimmed;
    }

    // Centris URL — extract 7-9 digit sequence
    const match = trimmed.match(/(\d{7,9})/);
    if (match) {
      return match[1];
    }

    return null;
  }

  function handleAnalyze() {
    setError('');
    setNotFound(false);
    setNotFoundUrl('');

    const id = extractId(inputVal);
    if (!id) {
      setError('Format non reconnu. Colle une URL Centris ou un ID numérique.');
      return;
    }

    setLoading(true);

    // Lookup is synchronous/local; use brief timeout for UX feedback
    setTimeout(() => {
      setLoading(false);
      const listings = allListings || window.LISTINGS || [];
      const found = listings.find(l => String(l.id) === String(id));

      if (found) {
        saveToRecent(found);
        window.navigateTo('#/analyze/' + id);
      } else {
        setNotFound(true);
        setNotFoundUrl(inputVal.trim());
      }
    }, 120);
  }

  function handleKeyDown(e) {
    if (e.key === 'Enter') handleAnalyze();
  }

  function handleClear() {
    setInputVal('');
    setError('');
    setNotFound(false);
    setNotFoundUrl('');
    if (inputRef.current) inputRef.current.focus();
  }

  function handleCopySupport() {
    const subject = encodeURIComponent('Analyse manuelle Vestora');
    const body = encodeURIComponent('Bonjour,\n\nJe souhaite une analyse de la fiche suivante :\n' + notFoundUrl + '\n\nMerci.');
    const mailto = 'mailto:contact@vestora.ca?subject=' + subject + '&body=' + body;

    try {
      navigator.clipboard.writeText(notFoundUrl).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }).catch(() => {
        window.open(mailto, '_blank');
      });
    } catch (_) {
      window.open(mailto, '_blank');
    }
  }

  function formatPrice(price) {
    if (!price) return '—';
    return new Intl.NumberFormat('fr-CA', { style: 'currency', currency: 'CAD', maximumFractionDigits: 0 }).format(price);
  }

  function formatDate(ts) {
    if (!ts) return '';
    try {
      return new Date(ts).toLocaleDateString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
    } catch (_) {
      return '';
    }
  }

  // Styles — inline to avoid needing external CSS
  const containerStyle = {
    maxWidth: '700px',
    margin: '0 auto',
    padding: '32px 16px',
    fontFamily: 'inherit',
  };

  const titleStyle = {
    fontSize: '1.5rem',
    fontWeight: 700,
    color: '#1a1a2e',
    marginBottom: '8px',
  };

  const subtitleStyle = {
    fontSize: '0.95rem',
    color: '#555',
    marginBottom: '24px',
  };

  const inputRowStyle = {
    display: 'flex',
    gap: '8px',
    alignItems: 'center',
    marginBottom: '12px',
  };

  const inputWrapStyle = {
    position: 'relative',
    flex: 1,
  };

  const inputStyle = {
    width: '100%',
    padding: '12px 40px 12px 14px',
    fontSize: '1rem',
    border: '1.5px solid #d1d5db',
    borderRadius: '8px',
    outline: 'none',
    boxSizing: 'border-box',
    transition: 'border-color 0.2s',
  };

  const clearBtnStyle = {
    position: 'absolute',
    right: '10px',
    top: '50%',
    transform: 'translateY(-50%)',
    background: 'none',
    border: 'none',
    cursor: 'pointer',
    color: '#9ca3af',
    fontSize: '1.1rem',
    padding: '0 2px',
    lineHeight: 1,
    display: inputVal ? 'block' : 'none',
  };

  const analyzeBtnStyle = {
    padding: '12px 22px',
    background: loading ? '#94a3b8' : '#1a1a2e',
    color: '#fff',
    border: 'none',
    borderRadius: '8px',
    fontSize: '1rem',
    fontWeight: 600,
    cursor: loading ? 'not-allowed' : 'pointer',
    whiteSpace: 'nowrap',
    transition: 'background 0.2s',
  };

  const errorStyle = {
    color: '#dc2626',
    fontSize: '0.875rem',
    marginBottom: '12px',
  };

  const notFoundBannerStyle = {
    background: '#fefce8',
    border: '1px solid #fde047',
    borderRadius: '8px',
    padding: '14px 16px',
    marginBottom: '24px',
    display: 'flex',
    alignItems: 'flex-start',
    gap: '12px',
    flexWrap: 'wrap',
  };

  const notFoundTextStyle = {
    flex: 1,
    fontSize: '0.9rem',
    color: '#78350f',
    minWidth: '200px',
  };

  const copyBtnStyle = {
    padding: '6px 14px',
    background: '#fbbf24',
    color: '#1c1917',
    border: 'none',
    borderRadius: '6px',
    fontSize: '0.85rem',
    fontWeight: 600,
    cursor: 'pointer',
    whiteSpace: 'nowrap',
    alignSelf: 'center',
  };

  const sectionTitleStyle = {
    fontSize: '1rem',
    fontWeight: 600,
    color: '#374151',
    marginBottom: '12px',
    marginTop: '32px',
  };

  const emptyStyle = {
    color: '#9ca3af',
    fontSize: '0.9rem',
    fontStyle: 'italic',
    padding: '16px 0',
  };

  const cardStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '12px 14px',
    border: '1px solid #e5e7eb',
    borderRadius: '8px',
    marginBottom: '8px',
    background: '#fff',
    gap: '12px',
    flexWrap: 'wrap',
  };

  const cardInfoStyle = {
    flex: 1,
    minWidth: '180px',
  };

  const cardAddressStyle = {
    fontWeight: 600,
    fontSize: '0.9rem',
    color: '#1a1a2e',
    marginBottom: '2px',
  };

  const cardMetaStyle = {
    fontSize: '0.8rem',
    color: '#6b7280',
  };

  const reopenBtnStyle = {
    padding: '6px 14px',
    background: '#f0f4ff',
    color: '#1a1a2e',
    border: '1px solid #c7d2fe',
    borderRadius: '6px',
    fontSize: '0.82rem',
    fontWeight: 600,
    cursor: 'pointer',
    whiteSpace: 'nowrap',
  };

  function handleReopen(item) {
    const listings = allListings || window.LISTINGS || [];
    const found = listings.find(l => String(l.id) === String(item.id));
    if (found) {
      saveToRecent(found);
      window.navigateTo('#/analyze/' + item.id);
    } else {
      // Still navigate — AnalyzePage handles not-found gracefully
      window.navigateTo('#/analyze/' + item.id);
    }
  }

  return (
    <div style={containerStyle}>
      {/* Section 1 — Input */}
      <h2 style={titleStyle}>Analyse rapide d'une fiche Centris</h2>
      <p style={subtitleStyle}>
        Colle l'URL Centris ou l'ID de la fiche pour ouvrir l'analyse Vestora
      </p>

      <div style={inputRowStyle}>
        <div style={inputWrapStyle}>
          <input
            ref={inputRef}
            type="text"
            value={inputVal}
            onChange={e => { setInputVal(e.target.value); setError(''); setNotFound(false); }}
            onKeyDown={handleKeyDown}
            placeholder="https://www.centris.ca/fr/... ou 12345678"
            style={inputStyle}
            disabled={loading}
            autoComplete="off"
            spellCheck={false}
          />
          <button
            style={clearBtnStyle}
            onClick={handleClear}
            tabIndex={-1}
            aria-label="Effacer"
            title="Effacer"
          >
            ✕
          </button>
        </div>
        <button
          style={analyzeBtnStyle}
          onClick={handleAnalyze}
          disabled={loading || !inputVal.trim()}
          aria-busy={loading}
        >
          {loading ? 'Chargement…' : 'Analyser'}
        </button>
      </div>

      {/* Error message */}
      {error && <p style={errorStyle}>⚠ {error}</p>}

      {/* Not-found banner */}
      {notFound && (
        <div style={notFoundBannerStyle} role="alert">
          <span style={{ fontSize: '1.2rem' }}>ℹ</span>
          <span style={notFoundTextStyle}>
            Fiche non indexée dans Vestora. Envoie-nous le lien pour analyse manuelle.
          </span>
          <button style={copyBtnStyle} onClick={handleCopySupport}>
            {copied ? 'Lien copié ✓' : 'Copier lien support'}
          </button>
        </div>
      )}

      {/* Section 3 — History */}
      <h3 style={sectionTitleStyle}>Récentes (10 dernières)</h3>

      {recents.length === 0 ? (
        <p style={emptyStyle}>Aucune analyse récente</p>
      ) : (
        <div>
          {recents.map(item => (
            <div key={item.id + '-' + (item.timestamp || 0)} style={cardStyle}>
              <div style={cardInfoStyle}>
                <div style={cardAddressStyle}>{item.address || 'Fiche #' + item.id}</div>
                <div style={cardMetaStyle}>
                  {[item.city, item.price ? formatPrice(item.price) : null, item.timestamp ? formatDate(item.timestamp) : null]
                    .filter(Boolean)
                    .join(' · ')}
                </div>
              </div>
              <button style={reopenBtnStyle} onClick={() => handleReopen(item)}>
                Re-ouvrir
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
