import React, { useState, useCallback } from 'react';
import ReactDOM from 'react-dom/client';
import '../index.css';
import { createMcpApp } from '../lib/mcp-app-sdk';
import { SearchBuilder } from '../apps/SearchBuilder';

const app = createMcpApp();

function SearchEntry() {
  const [loading, setLoading] = useState(false);

  const handleStartScrape = useCallback(async (config: any) => {
    setLoading(true);
    try {
      await app.callServerTool('reonomy_search', config);
      app.updateModelContext({
        text: `User started Reonomy search: ${config.location}, ${config.maxProperties} max properties, types: ${config.propertyTypes?.join(', ') || 'all'}`,
      });
    } catch (err) {
      // In standalone mode, log the config for testing
      console.log('[SearchBuilder] Config:', JSON.stringify(config, null, 2));
      app.updateModelContext({
        text: `Search config ready: ${JSON.stringify(config)}`,
      });
    } finally {
      setLoading(false);
    }
  }, []);

  return <SearchBuilder onStartScrape={handleStartScrape} loading={loading} />;
}

const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<SearchEntry />);

// Connect to host
app.connect().catch(() => {
  console.log('[SearchBuilder] Running in standalone mode');
});
