// Minimal fix for worker signup error handling
// This wraps the existing handleConfirm function with try-catch

// Add this at the top of the file with other useState declarations:
const [error, setError] = useState<string | null>(null);

// Replace the handleConfirm function with this wrapper:
async function handleConfirm() {
  if (!availability || experience === null) return;
  setSaving(true);
  setError(null); // Clear any previous errors

  try {
    // Original function code here
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) return;

    const workerData: WorkerData = {
      trades: selectedTrades,
      experience,
      suburb,
      availability,
      certifications,
    };

    const bio = generateBio(workerData);

    // Add logging to help debug
    console.log("Updating profile...", { userId: user.id, suburb });
    const profileUpdate = await supabase.from("profiles").update({
      name: user.email?.split("@")[0] ?? "",
      suburb,
      onboarding_completed: true,
    }).eq("id", user.id);

    if (profileUpdate.error) {
      console.error("Profile update failed:", profileUpdate.error);
      throw new Error(`Profile update failed: ${profileUpdate.error.message}`);
    }

    console.log("Inserting worker profile...", { 
      profile_id: user.id, 
      trades_count: selectedTrades.length,
      experience_years: experience 
    });
    
    const workerInsert = await supabase.from("worker_profiles").insert({
      profile_id: user.id,
      trades: selectedTrades,
      experience_years: experience,
      availability,
      certifications,
      bio,
      ai_extracted: {
        source: "typed_answers",
        created_at: new Date().toISOString(),
      },
    });

    if (workerInsert.error) {
      console.error("Worker profile insert failed:", workerInsert.error);
      throw new Error(`Worker profile insert failed: ${workerInsert.error.message}`);
    }

    console.log("Profile created successfully!");
    router.push("/dashboard");
    router.refresh();
    
  } catch (error: any) {
    console.error("Profile creation failed:", error);
    setError(error.message || "Failed to create profile");
    alert(`Failed to create profile: ${error.message}`);
  } finally {
    setSaving(false);
  }
}