import { useState } from 'react';
import { loadDashboard } from './api/dashboardApi';

function App() {
  const [contextId, setContextId] = useState('demo-context');
  const [payload, setPayload] = useState<unknown>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const onLoad = async (): Promise<void> => {
    setLoading(true);
    setError(null);
    try {
      const response = await loadDashboard(contextId);
      setPayload(response);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Unknown request error';
      setError(message);
      setPayload(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <main className="app">
      <h1>Customer Orders Web</h1>
      <p>React baseline wired to its corresponding BFF via an API adapter module.</p>
      <div className="row">
        <input value={contextId} onChange={(event) => setContextId(event.target.value)} />
        <button type="button" onClick={onLoad} disabled={loading}>
          {loading ? 'Loading...' : 'Load'}
        </button>
      </div>
      {error && <p>{error}</p>}
      <pre>{JSON.stringify(payload, null, 2)}</pre>
    </main>
  );
}

export default App;
