interface SupabaseConfig {
    url: string;
    anonKey: string;
}

class SmartDriveEngine {
    private supabaseClient: any;

    constructor(config: SupabaseConfig) {
        // Initialize real-time tracking capabilities via standard decoupled connection handles
        if (typeof supabase !== 'undefined') {
            this.supabaseClient = (window as any).supabase.createClient(config.url, config.anonKey);
            console.log("SmartDrive BD Client Engine Layer Successfully Initialized.");
        }
    }

    /**
     * Authenticates user using an SMS-based One-Time Password (OTP)
     */
    public async initializePhoneOtpVerification(phoneNumber: string): Promise<boolean> {
        try {
            const { data, error } = await this.supabaseClient.auth.signInWithOtp({
                phone: phoneNumber,
            });
            if (error) throw error;
            return data ? true : false;
        } catch (err) {
            console.error("OTP Handshake Pipeline Failure Encountered:", err);
            return false;
        }
    }

    /**
     * Submits an asynchronous booking request to the backend API
     */
    public async dispatchBookingPayload(formId: string): Promise<void> {
        const structuralForm = document.getElementById(formId) as HTMLFormElement;
        if (!structuralForm) return;

        structuralForm.addEventListener('submit', async (e: Event) => {
            e.preventDefault();
            const rawFormData = new FormData(structuralForm);
            const conversionPayload = Object.fromEntries(rawFormData.entries());

            try {
                const apiResponse = await fetch('/api/bookings/create', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(conversionPayload)
                });

                const finalResult = await apiResponse.json();
                if (apiResponse.ok && finalResult.status === 'success') {
                    alert(`Order Initialized. Track Reference ID: ${finalResult.booking_reference}`);
                    window.location.href = `/dashboard/customer?ref=${finalResult.booking_reference}`;
                } else {
                    alert(`Transaction Interrupted: ${finalResult.message}`);
                }
            } catch (networkError) {
                console.error("Booking Transmission Error Encountered:", networkError);
            }
        });
    }
}

// Instantiate dynamic runtime execution hooks
document.addEventListener('DOMContentLoaded', () => {
    const appEngine = new SmartDriveEngine({
        url: 'https://xyzcompany.supabase.co',
        anonKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dummyStringIndex'
    });
    
    if (document.getElementById('bookingPipelineForm')) {
        appEngine.dispatchBookingPayload('bookingPipelineForm');
    }
});