import { useState, useEffect } from 'react';
import { supabase } from '../lib/supabase';

export function useOrderTracking(token) {
  const [order, setOrder] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!token) {
      setLoading(false);
      return;
    }

    let isMounted = true;

    supabase
      .from('orders')
      .select('*')
      .eq('public_token', token)
      .single()
      .then(({ data, error }) => {
        if (!isMounted) return;
        if (error) setError(error.message);
        else setOrder(data);
        setLoading(false);
      });

    return () => {
      isMounted = false;
    };
  }, [token]);

  return { order, loading, error };
}
