import React, { useState } from 'react';
import Header from './components/Header';
import InputSection from './components/InputSection';
import Results from './components/Results';

function App() {
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleAnalyze = async (data) => {
    setLoading(true);
    try {
      let payload = {};
      if (data.type === 'text') {
        payload = { text: data.content };
      }
      // Note: File upload would need FormData, keeping it simple JSON for text for now

      const response = await fetch('/api/analyze/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        throw new Error('Analysis failed');
      }

      const resultData = await response.json();
      // Attach original text for the report
      setResult({ ...resultData, originalText: payload.text || "Uploaded File Content" });
    } catch (error) {
      console.error("Error analyzing:", error);
      alert("Failed to connect to local backend. Make sure Django is running!");
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setResult(null);
  };

  return (
    <>
      <Header />
      <main className="w-full flex-1 flex flex-col items-center px-4 pb-12">
        {!result && !loading && (
          <InputSection onAnalyze={handleAnalyze} />
        )}

        {loading && (
          <div className="mt-12 flex flex-col items-center">
            <div className="w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin mb-4"></div>
            <p className="text-secondary animate-pulse">Analyzing patterns...</p>
          </div>
        )}

        {result && (
          <Results result={result} onReset={handleReset} />
        )}
      </main>

      <footer className="w-full py-6 text-center text-[rgba(255,255,255,0.2)] text-sm">
        &copy; 2026 DetectAI Project. POC Version.
      </footer>
    </>
  );
}

export default App;
