/**
 * lib/api.ts — Laravel API client for ShophyFast
 *
 * Replaces /api/* with /api/* (Laravel routes).
 * All endpoints, method names and return shapes are preserved
 * so existing component code works without changes.
 */

const API_BASE = '/api';

// ── Tenant detection ──────────────────────────────────────────────────────────
export const getStoreSlug = (): string => {
    try {
        const host  = window.location.hostname;
        const parts = host.split('.');
        if (host.includes('localhost')) {
            if (parts.length > 1 && parts[0] !== 'localhost') return parts[0];
        } else {
            if (parts.length >= 3 && parts[0] !== 'www' && !/^\d+$/.test(parts[0])) return parts[0];
        }
        
        const cached = localStorage.getItem('preview_store_slug');
        if (cached) return cached;
        
        const tenantData = localStorage.getItem('tenant_data');
        if (tenantData) {
            try {
                const parsed = JSON.parse(tenantData);
                if (parsed.business_slug) return parsed.business_slug;
            } catch (e) {}
        }
        
        // Fallback for root domains (like macrowaveit.com) or localhost testing
        return 'ubaidi';
    } catch { return 'ubaidi'; }
};

const withSlug = (url: string): string => {
    const slug = getStoreSlug();
    if (!slug) return url;
    const sep = url.includes('?') ? '&' : '?';
    return `${url}${sep}slug=${encodeURIComponent(slug)}`;
};

const getTenantHeaders = (): Record<string, string> => {
    const token = localStorage.getItem('tenant_token') || '';
    const slug  = getStoreSlug();
    return {
        'Content-Type': 'application/json',
        'Accept':       'application/json',
        ...(token ? { 'X-Tenant-Token': token }    : {}),
        ...(slug  ? { 'X-Tenant-Slug':  slug  }    : {}),
    };
};

const handleResponse = async (res: Response) => {
    const text = await res.text();
    try {
        const data = JSON.parse(text);
        if (!res.ok) throw new Error(data.error || data.message || `HTTP ${res.status}`);
        return data;
    } catch (e) {
        throw new Error(`API error at ${res.url}: ${text.slice(0, 120)}`);
    }
};

// ── Facebook Ads — talks to Laravel /api/ads/* ───────────────────────────────
export const fbAdsApi = {
    summary:   (token: string, account: string, preset = 'this_month') =>
        fetch(`${API_BASE}/ads/summary?token=${token}&account=${account}&date_preset=${preset}`,
            { headers: getTenantHeaders() }).then(handleResponse),

    campaigns: (token: string, account: string, preset = 'this_month') =>
        fetch(`${API_BASE}/ads/campaigns?token=${token}&account=${account}&date_preset=${preset}`,
            { headers: getTenantHeaders() }).then(handleResponse),

    topAds:    (token: string, account: string, preset = 'this_month') =>
        fetch(`${API_BASE}/ads/top-ads?token=${token}&account=${account}&date_preset=${preset}`,
            { headers: getTenantHeaders() }).then(handleResponse),

    verify:    (token: string, account: string) =>
        fetch(`${API_BASE}/ads/verify?token=${token}&account=${account}`,
            { headers: getTenantHeaders() }).then(handleResponse),

    // Ubaidi AI — replaces /api/ubaidi-ads-ai
    analyze:   (data: string, period = 'this_month') =>
        fetch(`${API_BASE}/ads/analyze`, {
            method:  'POST',
            headers: getTenantHeaders(),
            body:    JSON.stringify({ data, period }),
        }).then(handleResponse),

    history: () =>
        fetch(`${API_BASE}/ads/history`, { headers: getTenantHeaders() }).then(handleResponse),
};

// ── Core api object (same interface as old lib/api.ts) ───────────────────────
export const api = {
    products: {
        getAll: async () => {
            try {
                const token = localStorage.getItem('tenant_token');
                if (token) {
                    const res = await fetch(`${API_BASE}/admin/products`, { headers: getTenantHeaders() });
                    const d = await handleResponse(res);
                    return d.data || [];
                }
                if (!getStoreSlug()) return [];
                const res = await fetch(withSlug(`${API_BASE}/shop`), { headers: getTenantHeaders() });
                const d = await handleResponse(res);
                return d.products || d.data || [];
            } catch { return []; }
        },
        getById: async (id: string) => {
            try {
                if (!getStoreSlug()) return null;
                const res = await fetch(`${API_BASE}/shop?product=${id}`, { headers: getTenantHeaders() });
                const d = await handleResponse(res);
                return d.data || null;
            } catch { return null; }
        },
        create: async (product: any) => {
            try {
                const res = await fetch(`${API_BASE}/admin/products`, {
                    method: 'POST', headers: getTenantHeaders(), body: JSON.stringify(product),
                });
                return await handleResponse(res);
            } catch { return { success: false, error: 'Failed to create product' }; }
        },
        update: async (product: any) => {
            try {
                const res = await fetch(`${API_BASE}/admin/products/${product.id}`, {
                    method: 'PUT', headers: getTenantHeaders(), body: JSON.stringify(product),
                });
                return await handleResponse(res);
            } catch { return { success: false, error: 'Failed to update product' }; }
        },
        delete: async (id: string) => {
            try {
                const res = await fetch(`${API_BASE}/admin/products/${id}`, {
                    method: 'DELETE', headers: getTenantHeaders(),
                });
                return await handleResponse(res);
            } catch { return { success: false, error: 'Failed to delete product' }; }
        },
        checkStock:  async (productId: string, _qty = 1, _size?: string): Promise<{ success: boolean; available: boolean; stock?: number }> => ({ success: true, available: true }),
        updateStock: async (productId: string, stock: number) => {
            try {
                const res = await fetch(`${API_BASE}/admin/products/${productId}`, {
                    method: 'PUT', headers: getTenantHeaders(), body: JSON.stringify({ stock }),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
    },

    orders: {
        create: async (order: any) => {
            try {
                const res = await fetch(`${API_BASE}/shop/checkout`, {
                    method: 'POST', headers: getTenantHeaders(),
                    body: JSON.stringify({
                        customer_name:    order.customerName,
                        customer_phone:   order.phone,
                        customer_address: order.address,
                        items:            order.items,
                        total:            order.total,
                        payment_method:   order.paymentMethod || 'cod',
                    }),
                });
                return await handleResponse(res);
            } catch { return { success: false, error: 'Failed to create order' }; }
        },
        getAll: async () => {
            try {
                const res = await fetch(`${API_BASE}/admin/orders`, { headers: getTenantHeaders() });
                const d = await handleResponse(res);
                return (d.data || []).map((o: any) => ({
                    id: o.id, customerName: o.customer_name, phone: o.customer_phone,
                    address: o.customer_address, items: o.items, subtotal: o.subtotal,
                    deliveryCharge: o.delivery_charge, total: o.total, status: o.status,
                    date: o.created_at,
                }));
            } catch { return []; }
        },
        updateStatus: async (id: string, status: string) => {
            try {
                const res = await fetch(`${API_BASE}/admin/orders/${id}/status`, {
                    method: 'PATCH', headers: getTenantHeaders(), body: JSON.stringify({ status }),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
        delete: async (id: string) => {
            try {
                const res = await fetch(`${API_BASE}/admin/orders/${id}`, {
                    method: 'DELETE', headers: getTenantHeaders(),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
    },

    settings: {
        get: async () => {
            try {
                if (!getStoreSlug()) return null;
                const res = await fetch(withSlug(`${API_BASE}/shop`), { headers: getTenantHeaders() });
                const d = await handleResponse(res);
                const s = d.settings;
                if (!s) return null;
                return {
                    logo: s.logo, favicon: s.favicon, footerLogo: s.footer_logo,
                    heroTitle: s.hero_title, heroSubtitle: s.hero_subtitle, heroImage: s.hero_image,
                    address: s.address, phone: s.phone, email: s.email,
                    facebook: s.facebook, instagram: s.instagram, youtube: s.youtube,
                    free_delivery_enabled: s.free_delivery_enabled,
                    homePageJson: s.home_page_json,
                    siteName: s.site_name, tabTitle: s.tab_title,
                    messengerAiEnabled: s.messenger_ai_enabled,
                    playStoreLink: s.play_store_link, appStoreLink: s.app_store_link,
                    gtm_id: s.gtm_id,
                    marketingCoupons: typeof s.marketing_coupons === 'string' ? JSON.parse(s.marketing_coupons) : (s.marketing_coupons || []),
                };
            } catch { return null; }
        },
        update: async (settings: any) => {
            try {
                const res = await fetch(`${API_BASE}/admin/settings`, {
                    method: 'POST', headers: getTenantHeaders(), body: JSON.stringify(settings),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
    },

    leads: {
        upsert: async (lead: any) => {
            try {
                const res = await fetch(`${API_BASE}/admin/leads`, {
                    method: 'POST', headers: getTenantHeaders(), body: JSON.stringify(lead),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
        getAll: async () => {
            try {
                const res = await fetch(`${API_BASE}/admin/leads`, { headers: getTenantHeaders() });
                const d = await handleResponse(res);
                return d.data || [];
            } catch { return []; }
        },
        getByPhone: async (phone: string) => {
            try {
                const res = await fetch(`${API_BASE}/admin/leads?phone=${encodeURIComponent(phone)}`, { headers: getTenantHeaders() });
                const d = await handleResponse(res);
                return d.data;
            } catch { return null; }
        },
        delete: async (phone: string) => {
            try {
                const res = await fetch(`${API_BASE}/admin/leads/${encodeURIComponent(phone)}`, {
                    method: 'DELETE', headers: getTenantHeaders(),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
    },

    testimonials: {
        getAll: async () => {
            try {
                if (!getStoreSlug()) return [];
                const res = await fetch(withSlug(`${API_BASE}/shop`), { headers: getTenantHeaders() });
                const d = await handleResponse(res);
                return d.testimonials || [];
            } catch { return []; }
        },
        getFeatured: async () => [],
        getStats: async () => ({ total: 0, average_rating: 0, distribution: {}, recent_30_days: 0 }),
        getByRating: async (_r: number) => [],
        create: async (t: any) => {
            try {
                const res = await fetch(`${API_BASE}/admin/testimonials`, {
                    method: 'POST', headers: getTenantHeaders(), body: JSON.stringify(t),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
        update: async (t: any) => {
            try {
                const res = await fetch(`${API_BASE}/admin/testimonials/${t.id}`, {
                    method: 'PUT', headers: getTenantHeaders(), body: JSON.stringify(t),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
        delete: async (id: string) => {
            try {
                const res = await fetch(`${API_BASE}/admin/testimonials/${id}`, {
                    method: 'DELETE', headers: getTenantHeaders(),
                });
                return await handleResponse(res);
            } catch { return { success: false }; }
        },
    },

    upload: {
        image: async (file: File, type = 'general') => {
            const fd = new FormData();
            fd.append('image', file);
            fd.append('type', type);
            try {
                const res = await fetch(`${API_BASE}/admin/upload`, {
                    method: 'POST',
                    headers: { 'Accept': 'application/json', ...{ 'X-Tenant-Token': localStorage.getItem('tenant_token') || '' } },
                    body: fd,
                });
                return await handleResponse(res);
            } catch { return { success: false, error: 'Upload failed' }; }
        },
    },
};