/**
 * Public Product Sign-Up - customer-facing page (QR scan landing)
 * No login required. Store is fixed from URL ?storeId=...
 */
var { useState, useEffect } = React;

const CONTACT_OPTIONS = ['Email', 'SMS', 'WeChat'];
const AU_PHONE_PREFIX = '+61';

function parsePhoneForInput(phone) {
    if (!phone) return '';
    const digits = phone.replace(/\D/g, '');
    if (digits.startsWith('61')) return digits.slice(2);
    if (digits.startsWith('0')) return digits.slice(1);
    return digits;
}

function validateAusPhone(phone) {
    if (!phone || !phone.trim()) return true;
    let digits = phone.replace(/\D/g, '');
    if (digits.startsWith('61')) digits = digits.slice(2);
    if (digits.startsWith('0')) digits = digits.slice(1);
    return digits.length >= 8 && digits.length <= 9;
}
function validateProductSignupContact(form) {
    const email = (form.email || '').trim();
    const phoneNumber = (form.phoneNumber || '').trim();
    const wechatId = (form.wechatId || '').trim();
    const preferred = (form.preferredMethodOfContact || 'Email').trim();

    if (!email && !phoneNumber && !wechatId) {
        return 'Please provide at least one contact method: email, phone number, or WeChat ID';
    }
    if (preferred === 'Email' && !email) {
        return 'Email is required when Email is your preferred contact method';
    }
    if (preferred === 'SMS' && !phoneNumber) {
        return 'Phone number is required when SMS is your preferred contact method';
    }
    if (preferred === 'WeChat' && !wechatId) {
        return 'WeChat ID is required when WeChat is your preferred contact method';
    }
    if (phoneNumber && !validateAusPhone(phoneNumber)) {
        return 'Phone number must be a valid Australian number (8–9 digits after +61)';
    }
    return '';
}

function getStoreIdFromUrl() {
    return new URLSearchParams(window.location.search).get('storeId') || '';
}

function PublicSignupApp() {
    const storeId = getStoreIdFromUrl();
    const [loading, setLoading] = useState(true);
    const [loadError, setLoadError] = useState('');
    const [storeName, setStoreName] = useState('');
    const [launchProducts, setLaunchProducts] = useState([]);
    const [submitted, setSubmitted] = useState(false);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [form, setForm] = useState({
        name: '',
        email: '',
        phoneNumber: '',
        wechatId: '',
        preferredMethodOfContact: 'Email',
        productSeries: ''
    });

    useEffect(() => {
        if (!storeId) {
            setLoadError('Invalid link. Please scan the QR code at the store again.');
            setLoading(false);
            return;
        }

        let mounted = true;
        (async () => {
            let attempts = 0;
            while (!window.functions && attempts < 50) {
                await new Promise(r => setTimeout(r, 100));
                attempts++;
            }
            if (!mounted) return;
            if (!window.functions || !window.httpsCallable) {
                setLoadError('Unable to connect. Please refresh and try again.');
                setLoading(false);
                return;
            }
            try {
                const fn = window.httpsCallable(window.functions, 'getPublicProductSignupOptions');
                const res = await fn({ storeId });
                if (!mounted) return;
                if (res.data?.success) {
                    setStoreName(res.data.storeName || '');
                    setLaunchProducts(res.data.launchProducts || []);
                } else {
                    setLoadError('Unable to load signup form.');
                }
            } catch (err) {
                if (!mounted) return;
                setLoadError(err.message || 'Store not found. Please scan the QR code again.');
            } finally {
                if (mounted) setLoading(false);
            }
        })();
        return () => { mounted = false; };
    }, [storeId]);

    const handleChange = (field, value) => {
        if (field === 'phoneNumber') {
            let digits = value.replace(/\D/g, '');
            if (digits.startsWith('61')) digits = digits.slice(2);
            if (digits.startsWith('0')) digits = digits.slice(1);
            const limited = digits.length > 9 ? digits.slice(0, 9) : digits;
            setForm(prev => ({ ...prev, [field]: limited ? AU_PHONE_PREFIX + limited : '' }));
        } else {
            setForm(prev => ({ ...prev, [field]: value }));
        }
        setError('');
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!form.name.trim()) {
            setError('Name is required');
            return;
        }
        const contactError = validateProductSignupContact(form);
        if (contactError) {
            setError(contactError);
            return;
        }
        if (!form.productSeries.trim()) {
            setError('Please select a product');
            return;
        }
        setSaving(true);
        setError('');
        try {
            const fn = window.httpsCallable(window.functions, 'submitPublicProductSignupCustomer');
            await fn({
                storeId,
                name: form.name,
                email: form.email,
                phoneNumber: form.phoneNumber,
                wechatId: form.wechatId,
                preferredMethodOfContact: form.preferredMethodOfContact,
                productSeries: form.productSeries
            });
            setSubmitted(true);
        } catch (err) {
            setError(err.message || 'Failed to submit. Please try again.');
        } finally {
            setSaving(false);
        }
    };

    if (loading) {
        return (
            <div className="ps-public-page">
                <div className="ps-public-card text-center py-5">
                    <div className="spinner-border text-primary mb-3" role="status"></div>
                    <p className="text-muted mb-0">Loading signup form…</p>
                </div>
            </div>
        );
    }

    if (loadError) {
        return (
            <div className="ps-public-page">
                <div className="ps-public-card text-center">
                    <i className="fas fa-exclamation-circle text-danger fa-2x mb-3"></i>
                    <h1 className="ps-public-title">Sign-up unavailable</h1>
                    <p className="text-muted mb-0">{loadError}</p>
                </div>
            </div>
        );
    }

    if (submitted) {
        return (
            <div className="ps-public-page">
                <div className="ps-public-card text-center">
                    <div className="ps-public-success-icon mb-3">
                        <i className="fas fa-check"></i>
                    </div>
                    <h1 className="ps-public-title">You&apos;re signed up!</h1>
                    <p className="text-muted mb-0">
                        We&apos;ll contact you when <strong>{form.productSeries}</strong> launches.
                        You can close this page now.
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div className="ps-public-page">
            <div className="ps-public-card">
                <div className="ps-public-header text-center mb-4">
                    <h1 className="ps-public-title">New Product Sign-Up</h1>
                    <p className="text-muted mb-0">Register your interest for upcoming launches</p>
                </div>

                <form onSubmit={handleSubmit}>
                    {error && (
                        <div className="alert alert-danger py-2" role="alert">{error}</div>
                    )}

                    <div className="mb-3">
                        <label className="form-label">Store</label>
                        <input type="text" className="form-control" value={storeName} readOnly disabled />
                    </div>

                    <div className="mb-3">
                        <label className="form-label">Product <span className="text-danger">*</span></label>
                        {launchProducts.length > 0 ? (
                            <select
                                className="form-select"
                                value={form.productSeries}
                                onChange={e => handleChange('productSeries', e.target.value)}
                                required
                            >
                                <option value="">Select a product</option>
                                {launchProducts.map(p => (
                                    <option key={p.id} value={p.title}>{p.title}</option>
                                ))}
                            </select>
                        ) : (
                            <p className="text-muted small mb-0">No products available for sign-up at this time.</p>
                        )}
                    </div>

                    <div className="mb-3">
                        <label className="form-label">Name <span className="text-danger">*</span></label>
                        <input
                            type="text"
                            className="form-control"
                            value={form.name}
                            onChange={e => handleChange('name', e.target.value)}
                            placeholder="Your full name"
                            required
                        />
                    </div>

                    <p className="text-muted small mb-3">Provide at least one contact method. Your preferred method must be filled in.</p>

                    <div className="mb-3">
                        <label className="form-label">Email</label>
                        <input
                            type="email"
                            className="form-control"
                            value={form.email}
                            onChange={e => handleChange('email', e.target.value)}
                            placeholder="you@example.com"
                        />
                    </div>

                    <div className="mb-3">
                        <label className="form-label">Phone Number</label>
                        <div className="input-group">
                            <span className="input-group-text">+61</span>
                            <input
                                type="tel"
                                className="form-control"
                                inputMode="numeric"
                                pattern="[0-9]*"
                                maxLength={9}
                                value={parsePhoneForInput(form.phoneNumber)}
                                onChange={e => handleChange('phoneNumber', e.target.value)}
                                placeholder="4XX XXX XXX"
                            />
                        </div>
                        <small className="text-muted">8–9 digits (e.g. 400 000 000)</small>
                    </div>

                    <div className="mb-3">
                        <label className="form-label">WeChat ID</label>
                        <input
                            type="text"
                            className="form-control"
                            value={form.wechatId}
                            onChange={e => handleChange('wechatId', e.target.value)}
                            placeholder="Your WeChat ID"
                        />
                    </div>

                    <div className="mb-4">
                        <label className="form-label">Preferred Method of Contact <span className="text-danger">*</span></label>
                        <select
                            className="form-select"
                            value={form.preferredMethodOfContact}
                            onChange={e => handleChange('preferredMethodOfContact', e.target.value)}
                            required
                        >
                            {CONTACT_OPTIONS.map(opt => (
                                <option key={opt} value={opt}>{opt}</option>
                            ))}
                        </select>
                    </div>

                    <button
                        type="submit"
                        className="btn btn-primary w-100 ps-public-submit"
                        disabled={saving || launchProducts.length === 0}
                    >
                        {saving ? <span className="spinner-border spinner-border-sm me-1" role="status"></span> : null}
                        Sign Up
                    </button>
                </form>
            </div>
        </div>
    );
}

function mountApp() {
    var appEl = document.getElementById('app');
    if (appEl && window.ReactDOM) {
        var root = ReactDOM.createRoot(appEl);
        root.render(<PublicSignupApp />);
    }
}

function waitForFirebaseThenMount() {
    if (window.functions && window.httpsCallable) {
        mountApp();
        return;
    }
    var attempts = 0;
    var interval = setInterval(function () {
        attempts++;
        if (window.functions && window.httpsCallable) {
            clearInterval(interval);
            mountApp();
        } else if (attempts >= 50) {
            clearInterval(interval);
            var appEl = document.getElementById('app');
            if (appEl) {
                appEl.innerHTML = '<div class="ps-public-page"><div class="ps-public-card text-center text-danger">Failed to load. Please refresh the page.</div></div>';
            }
        }
    }, 100);
}

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', waitForFirebaseThenMount);
} else {
    waitForFirebaseThenMount();
}
