import { useState } from "react";

export default function APITest() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  async function fetchPlans() {
    setLoading(true);
    setError(null);
    
    try {
      // Using a CORS proxy to bypass CORS restrictions for testing
      const corsProxy = "https://corsproxy.io/?";
      const apiUrl = "https://api.reachplatform.com/product/fetch/service-serviceCode--serviceCode-";
      
      const response = await fetch(corsProxy + encodeURIComponent(apiUrl));
      
      if (!response.ok) {
        throw new Error(`API error: ${response.status}`);
      }
      
      const result = await response.json();
      setData(result);
    } catch (err) {
      setError(err.message || "An error occurred");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ padding: "20px", fontFamily: "sans-serif" }}>
      <h2>API Test</h2>
      <button 
        onClick={fetchPlans} 
        disabled={loading}
        style={{
          padding: "10px 15px",
          backgroundColor: "#0070f3",
          color: "white", 
          border: "none",
          borderRadius: "4px",
          cursor: loading ? "not-allowed" : "pointer"
        }}
      >
        {loading ? "Loading..." : "Fetch Plans"}
      </button>
      
      {error && (
        <div style={{ color: "red", marginTop: "15px" }}>
          Error: {error}
        </div>
      )}
      
      {data && (
        <div style={{ marginTop: "15px" }}>
          <h3>Results:</h3>
          <pre style={{ 
            background: "#f0f0f0", 
            padding: "10px", 
            borderRadius: "4px",
            overflow: "auto",
            maxHeight: "400px" 
          }}>
            {JSON.stringify(data, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
}

© Blue Whale Ventures 2025