var _useState_CS = React.useState;
var _useEffect_CS = React.useEffect;
var _useRef_CS = React.useRef;
var _useParams_CS = ReactRouterDOM.useParams;
var _useLocation_CS = ReactRouterDOM.useLocation;

/**
 * ContactSpecialistPage — Send a quote request / message to a specialist.
 *
 * Launch rework (Oct 2026, email-referrals-board.html): SMS is gone — exactly two contact
 * methods, sourced from `specialist.contact` (never both shown if the field is absent):
 *   - Call: a plain `tel:` link, instant, no form.
 *   - Email: selecting it progressively discloses the quote-request form, which POSTs same-
 *     origin `/api/quote` for real (the old fake instant-success flow is gone — that was the
 *     launch bug this rework fixes).
 * No contact.phone AND no contact.email -> a friendly "no direct contact details" state,
 * per the sourced-fields-only rule (nothing inferred or padded in).
 *
 * `:id` is the stable `mds-…` id — fetched via SpecialistsService.getById, with the
 * navigation-state record (passed from SpecialistProfilePage) painting instantly when
 * present. See SpecialistProfilePage.jsx's header for why the fetch always happens
 * regardless (deep links, reloads, bookmarks have no nav state at all).
 *
 * Route: /specialists/:id/contact
 */

// Namespaced `cs` — see CLAUDE.md: every top-level var is a window global here.
var CS_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var CS_CUSTOMER_KEY = 'mould-detect-contact-customer';
var csCustomerStore = (typeof localforage !== 'undefined')
    ? localforage.createInstance({ name: 'MouldDetect', storeName: 'app_data' })
    : null;

var CS_GENERIC_ERROR = "We couldn't send your request just now. Check your connection and try again — your message is still here.";
var CS_QUOTA_ERROR = "You've sent quite a few requests today — please try again tomorrow.";

// Progressive-disclosure reveal — transform/opacity + a pre-measured max-height only,
// matching AirQualityPage's AQG_CSS collapse pattern. Respects prefers-reduced-motion.
var CS_CSS = [
    '.cs-reveal{max-height:0;opacity:0;overflow:hidden;transition:max-height .32s ease,opacity .22s ease;}',
    '.cs-reveal.cs-open{max-height:1400px;opacity:1;}',
    '@media (prefers-reduced-motion: reduce){',
    '.cs-reveal{transition:opacity .22s ease;max-height:none !important;}',
    '}',
].join('');

/**
 * QuoteSuccessDialog — success confirmation, ConfirmDialog's visual chrome (surface card,
 * rounded-xl, shadow-soft) but a single OK action and a forest check instead of the warning
 * icon + Cancel/Delete pair, since this isn't a destructive confirmation.
 */
var QuoteSuccessDialog = function (props) {
    if (!props.isOpen) return null;
    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 px-6">
            <div className="bg-surface rounded-xl p-6 max-w-sm w-full shadow-soft space-y-4 text-center">
                <div className="w-14 h-14 rounded-full bg-primary/15 flex items-center justify-center mx-auto">
                    <span className="material-symbols-outlined text-primary text-3xl">check_circle</span>
                </div>
                <div>
                    <h3 className="font-extrabold text-forest">Request sent to {props.name}</h3>
                    <p className="text-sm font-medium text-forest/70 mt-1">They'll reply to your email as soon as they can.</p>
                    {props.referralId && (
                        <p className="text-[11px] font-bold text-forest/40 mt-2">Reference: {props.referralId}</p>
                    )}
                </div>
                <button onClick={props.onOk} className="w-full py-3 rounded-xl bg-forest text-white text-sm font-extrabold btn-nature">OK</button>
            </div>
        </div>
    );
};

var ContactSpecialistPage = function () {
    var navigate = ReactRouterDOM.useNavigate();
    var params = _useParams_CS();
    var location = _useLocation_CS();
    var id = params.id;
    var navState = location && location.state;
    var store = useScanStore();

    var dataState = _useState_CS((navState && navState.specialist) || null);
    var specialist = dataState[0];
    var setSpecialist = dataState[1];

    var statusState = _useState_CS(specialist ? 'ready' : 'loading');
    var status = statusState[0];
    var setStatus = statusState[1];

    var errorState = _useState_CS(null);
    var loadError = errorState[0];
    var setLoadError = errorState[1];

    var descState = _useState_CS('');
    var description = descState[0];
    var setDescription = descState[1];

    var quoteState = _useState_CS(true);
    var requestQuote = quoteState[0];
    var setRequestQuote = quoteState[1];

    var selectedState = _useState_CS({});
    var selectedScans = selectedState[0];
    var setSelectedScans = selectedState[1];

    var contactMethodState = _useState_CS(''); // '' | 'email'
    var contactMethod = contactMethodState[0];
    var setContactMethod = contactMethodState[1];

    var nameState = _useState_CS('');
    var customerName = nameState[0];
    var setCustomerName = nameState[1];

    var emailState = _useState_CS('');
    var customerEmail = emailState[0];
    var setCustomerEmail = emailState[1];

    var emailErrState = _useState_CS(null);
    var emailFieldError = emailErrState[0];
    var setEmailFieldError = emailErrState[1];

    var honeypotState = _useState_CS('');
    var honeypot = honeypotState[0];
    var setHoneypot = honeypotState[1];

    // 'idle' | 'sending' | 'success' | 'error'
    var sendState_ = _useState_CS('idle');
    var sendState = sendState_[0];
    var setSendState = sendState_[1];

    var sendErrorState = _useState_CS(null);
    var sendErrorMessage = sendErrorState[0];
    var setSendErrorMessage = sendErrorState[1];

    var referralState = _useState_CS(null);
    var referralId = referralState[0];
    var setReferralId = referralState[1];

    var abortRef = _useRef_CS(null);

    _useEffect_CS(function () {
        var controller = new AbortController();
        var cancelled = false;

        SpecialistsService.getById(id, { signal: controller.signal }).then(function (res) {
            if (cancelled) return;
            if (res && res.error) {
                if (res.reason === 'aborted') return;
                if (!specialist) {
                    setLoadError({ reason: res.reason });
                    setStatus('error');
                }
                return;
            }
            setSpecialist(res);
            setStatus('ready');
        });

        return function () {
            cancelled = true;
            controller.abort();
        };
        // eslint-disable-next-line -- id-only, see SpecialistProfilePage.jsx's identical note.
    }, [id]);

    // Remember the customer's name/email for next time — read on mount, written on a
    // successful send (below). A broken cache must never block the form, so both directions
    // swallow errors, matching SpecialistsService's saved-location contract.
    _useEffect_CS(function () {
        if (!csCustomerStore) return;
        csCustomerStore.getItem(CS_CUSTOMER_KEY).then(function (rec) {
            if (!rec || typeof rec !== 'object') return;
            if (rec.email) setCustomerEmail(rec.email);
            if (rec.name) setCustomerName(rec.name);
        })['catch'](function () {});
    }, []);

    // Abort any in-flight submission on unmount (navigate-away mid-send).
    _useEffect_CS(function () {
        return function () {
            if (abortRef.current) abortRef.current.abort();
        };
    }, []);

    var retry = function () {
        setStatus('loading');
        setLoadError(null);
        SpecialistsService.getById(id).then(function (res) {
            if (res && res.error) {
                setLoadError({ reason: res.reason });
                setStatus('error');
                return;
            }
            setSpecialist(res);
            setStatus('ready');
        });
    };

    var toggleScan = function (scanId) {
        setSelectedScans(function (prev) {
            var next = {};
            for (var k in prev) { next[k] = prev[k]; }
            if (next[scanId]) {
                delete next[scanId];
            } else {
                next[scanId] = true;
            }
            return next;
        });
    };

    var handleSubmit = function (e) {
        if (e && e.preventDefault) e.preventDefault();
        if (sendState === 'sending') return;

        var email = (customerEmail || '').trim();
        if (!CS_EMAIL_RE.test(email)) {
            setEmailFieldError('Please enter a valid email address.');
            return;
        }
        setEmailFieldError(null);

        var scanIds = Object.keys(selectedScans);
        var scansPayload = [];
        for (var i = 0; i < scanIds.length && scansPayload.length < 3; i++) {
            var found = null;
            for (var j = 0; j < store.scans.length; j++) {
                if (store.scans[j].id === scanIds[i]) { found = store.scans[j]; break; }
            }
            if (found) {
                scansPayload.push({
                    id: found.id,
                    thumbnail: found.thumbnail || '',
                    severity: found.severity || '',
                    room: found.roomName || null,
                });
            }
        }

        var controller = new AbortController();
        abortRef.current = controller;
        setSendState('sending');
        setSendErrorMessage(null);

        var contact = specialist.contact || {};
        var payload = {
            specialist_id: specialist.id,
            specialist_name: specialist.name,
            specialist_email: contact.email || '',
            customer_name: (customerName || '').trim(),
            customer_email: email,
            description: description,
            quote_requested: requestQuote,
            scans: scansPayload,
            website: honeypot, // honeypot — always empty from a real user
        };

        var bodyText = JSON.stringify(payload);
        // CloudFront OAC signs Lambda-URL requests; POST bodies must carry their own
        // sha256 in x-amz-content-sha256 or the edge rejects with a signature error
        // (same requirement AWSVisionService documents — found live 2026-08-08).
        AWSVisionService.sha256Hex(bodyText).then(function (hash) {
        var hdrs = { 'Content-Type': 'application/json', 'Accept': 'application/json' };
        if (hash) hdrs['x-amz-content-sha256'] = hash;
        return fetch('/api/quote', {
            method: 'POST',
            headers: hdrs,
            body: bodyText,
            signal: controller.signal,
        }).then(function (res) {
            return res.json()['catch'](function () { return null; }).then(function (body) {
                return { ok: res.ok, status: res.status, body: body };
            });
        }).then(function (result) {
            abortRef.current = null;
            if (result.ok) {
                AnalyticsService.contactProfessionalSubmitted({
                    specialist_category: (specialist.categories && specialist.categories[0]) || 'unknown',
                    has_scan_attached: scansPayload.length > 0,
                    contact_method: 'email',
                });
                if (csCustomerStore) {
                    csCustomerStore.setItem(CS_CUSTOMER_KEY, { v: 1, email: email, name: (customerName || '').trim() })['catch'](function () {});
                }
                setReferralId((result.body && result.body.referral_id) || null);
                setSendState('success');
                return;
            }
            setSendErrorMessage(result.status === 429 ? CS_QUOTA_ERROR : CS_GENERIC_ERROR);
            setSendState('error');
        })['catch'](function (err) {
            abortRef.current = null;
            if (err && err.name === 'AbortError') { setSendState('idle'); return; }
            setSendErrorMessage(CS_GENERIC_ERROR);
            setSendState('error');
        });
        });
    };

    if (status === 'loading') {
        return (
            <Layout>
                <main className="flex-1 overflow-y-auto overflow-x-hidden pb-10">
                    <PageHeader title="Contact" showBack={true} showMenu={true} />
                    <div className="px-6">
                        <div className="flex items-center justify-center py-20">
                            <div className="w-10 h-10 rounded-full border-4 border-forest/20 border-t-forest animate-spin"></div>
                        </div>
                    </div>
                </main>
            </Layout>
        );
    }

    if (status === 'error' || !specialist) {
        return (
            <Layout>
                <main className="flex-1 overflow-y-auto overflow-x-hidden pb-10">
                    <PageHeader title="Contact" showBack={true} showMenu={true} />
                    <div className="px-6">
                        <div className="text-center py-16">
                            <span className="material-symbols-outlined text-4xl text-sage mb-2">cloud_off</span>
                            <p className="text-sm font-bold text-forest">Couldn't load this specialist</p>
                            <p className="text-xs text-forest/70 mt-1 mb-4">{(loadError && loadError.reason) || 'Check your connection and try again.'}</p>
                            <button
                                onClick={retry}
                                className="bg-primary text-white font-extrabold px-6 py-2.5 rounded-xl shadow-clay btn-nature hover:brightness-110 transition-all text-sm inline-flex items-center gap-2"
                            >
                                <span className="material-symbols-outlined text-base">refresh</span>
                                Try again
                            </button>
                        </div>
                    </div>
                </main>
            </Layout>
        );
    }

    var name = specialist.name;
    var contact = specialist.contact || {};
    var hasPhone = !!contact.phone;
    var hasEmail = !!contact.email;
    var noContact = !hasPhone && !hasEmail;
    var emailOpen = contactMethod === 'email';

    return (
        <Layout>
            <style dangerouslySetInnerHTML={{ __html: CS_CSS }} />
            <main className="flex-1 overflow-y-auto overflow-x-hidden pb-36">
                <PageHeader title="Contact Specialist" showBack={true} showMenu={true} />
                <div className="px-6">

                    {/* Specialist Identity */}
                    <SpecialistIdentity specialist={specialist} />

                    {noContact ? (
                        <div className="text-center py-16">
                            <span className="material-symbols-outlined text-4xl text-sage mb-2">contact_support</span>
                            <p className="text-sm font-bold text-forest">This listing has no direct contact details</p>
                            <p className="text-xs text-forest/70 mt-1">Try another specialist nearby, or check back later.</p>
                        </div>
                    ) : (
                        <React.Fragment>
                            {/* Preferred Contact Method */}
                            <section className="mt-5">
                                <h3 className="text-sm font-extrabold text-forest mb-2">Preferred Contact</h3>
                                <div className="space-y-2">
                                    {hasPhone && (
                                        <a
                                            href={'tel:' + contact.phone}
                                            className="flex items-center gap-3 p-3 rounded-xl bg-background-light border border-stone-200 cursor-pointer btn-nature hover:border-primary/50 transition-colors"
                                        >
                                            <span className="w-8 h-8 rounded-full bg-forest text-white flex items-center justify-center shrink-0">
                                                <span className="material-symbols-outlined text-base">call</span>
                                            </span>
                                            <div className="min-w-0">
                                                <p className="text-sm font-bold text-forest">Call</p>
                                                <p className="text-xs text-forest/60 font-medium truncate">{contact.phone} · instant</p>
                                            </div>
                                        </a>
                                    )}
                                    {hasEmail && (
                                        <button
                                            type="button"
                                            aria-expanded={emailOpen}
                                            aria-controls="cs-email-form"
                                            onClick={function () { setContactMethod(emailOpen ? '' : 'email'); }}
                                            className={
                                                'w-full flex items-center gap-3 p-3 rounded-xl border cursor-pointer btn-nature transition-colors text-left ' +
                                                (emailOpen ? 'bg-background-light border-primary/50 ring-1 ring-primary/30' : 'bg-background-light border-stone-200 hover:border-primary/50')
                                            }
                                        >
                                            <span className={'w-5 h-5 rounded-full flex items-center justify-center border-2 transition-colors shrink-0 ' + (emailOpen ? 'bg-primary border-primary' : 'border-stone-300')}>
                                                {emailOpen && <span className="material-symbols-outlined text-white text-sm">check</span>}
                                            </span>
                                            <div className="min-w-0">
                                                <p className="text-sm font-bold text-forest">Email</p>
                                                <p className="text-xs text-forest/60 font-medium truncate">Describe your issue and send scans</p>
                                            </div>
                                        </button>
                                    )}
                                </div>
                            </section>

                            {/* Progressive disclosure: form only when Email is selected */}
                            <div id="cs-email-form" className={'cs-reveal ' + (emailOpen ? 'cs-open' : '')}>
                                <form onSubmit={handleSubmit}>
                                    {/* Issue Details */}
                                    <section className="mt-5">
                                        <h3 className="text-sm font-extrabold text-forest mb-2">Describe Your Issue</h3>
                                        <textarea
                                            className="w-full min-h-[120px] p-4 rounded-xl border border-stone-200 bg-surface text-forest text-sm font-medium placeholder:text-sage focus:ring-2 focus:ring-primary focus:border-transparent transition-all resize-none"
                                            placeholder="Briefly describe the mould issue, affected areas, and any symptoms you've noticed..."
                                            value={description}
                                            onChange={function (e) { setDescription(e.target.value); }}
                                        ></textarea>
                                    </section>

                                    {/* Attach Scans — up to 3 */}
                                    <ScanSelector
                                        selected={selectedScans}
                                        onToggle={toggleScan}
                                        rows={3}
                                        title="Attach Scans"
                                        max={3}
                                    />

                                    {/* Quote Request Toggle */}
                                    <section className="mt-5">
                                        <label
                                            className="flex items-center gap-3 p-4 rounded-xl bio-bg bio-bg-40 cursor-pointer btn-nature"
                                            onClick={function () { setRequestQuote(!requestQuote); }}
                                        >
                                            <div className={'w-5 h-5 rounded flex items-center justify-center border-2 transition-colors ' + (requestQuote ? 'bg-primary border-primary' : 'border-stone-300')}>
                                                {requestQuote && <span className="material-symbols-outlined text-white text-sm">check</span>}
                                            </div>
                                            <div>
                                                <p className="font-extrabold text-sm text-forest">Request a quote</p>
                                                <p className="text-xs text-forest/50 font-medium">Receive a pricing estimate for the consultation</p>
                                            </div>
                                        </label>
                                    </section>

                                    {/* Your details */}
                                    <section className="mt-5 space-y-3">
                                        <h3 className="text-sm font-extrabold text-forest mb-2">Your Details</h3>
                                        <div>
                                            <input
                                                type="text"
                                                className="w-full p-3.5 rounded-xl border border-stone-200 bg-surface text-forest text-sm font-medium placeholder:text-sage focus:ring-2 focus:ring-primary focus:border-transparent transition-all"
                                                placeholder="Your name (optional)"
                                                value={customerName}
                                                onChange={function (e) { setCustomerName(e.target.value); }}
                                            />
                                        </div>
                                        <div>
                                            <input
                                                type="email"
                                                required={true}
                                                className={
                                                    'w-full p-3.5 rounded-xl border bg-surface text-forest text-sm font-medium placeholder:text-sage focus:ring-2 focus:ring-primary focus:border-transparent transition-all ' +
                                                    (emailFieldError ? 'border-terracotta' : 'border-stone-200')
                                                }
                                                placeholder="Your email — so they can reply"
                                                value={customerEmail}
                                                onChange={function (e) { setCustomerEmail(e.target.value); if (emailFieldError) setEmailFieldError(null); }}
                                            />
                                            {emailFieldError && <p className="text-xs text-terracotta font-bold mt-1">{emailFieldError}</p>}
                                        </div>
                                        {/* Honeypot — never visible or reachable by keyboard/AT; a real user never fills this. */}
                                        <input
                                            type="text"
                                            name="website"
                                            value={honeypot}
                                            onChange={function (e) { setHoneypot(e.target.value); }}
                                            tabIndex={-1}
                                            autoComplete="off"
                                            aria-hidden="true"
                                            style={{ position: 'absolute', left: '-9999px', top: '-9999px', width: '1px', height: '1px', opacity: 0 }}
                                        />
                                    </section>

                                    {/* Friendly, recoverable error — form state stays intact */}
                                    {sendState === 'error' && sendErrorMessage && (
                                        <div className="mt-4 bg-background-light rounded-xl p-3 flex items-start gap-3 border border-stone-200">
                                            <span className="material-symbols-outlined text-sage text-xl">cloud_off</span>
                                            <p className="text-xs text-forest/70 leading-snug flex-1">{sendErrorMessage}</p>
                                        </div>
                                    )}

                                    {/* Send Request */}
                                    <section className="mt-5 mb-4">
                                        <button
                                            type="submit"
                                            disabled={sendState === 'sending'}
                                            className={'w-full font-extrabold py-4 rounded-xl shadow-soft btn-nature flex items-center justify-center gap-2 transition-all ' +
                                                (sendState === 'sending' ? 'bg-forest/50 text-white/70' : 'bg-forest text-white hover:bg-primary')}
                                        >
                                            {sendState === 'sending' ? (
                                                <React.Fragment>
                                                    <span className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin"></span>
                                                    <span>Sending…</span>
                                                </React.Fragment>
                                            ) : (
                                                <React.Fragment>
                                                    <span>Send Request</span>
                                                    <span className="material-symbols-outlined text-lg">send</span>
                                                </React.Fragment>
                                            )}
                                        </button>
                                    </section>
                                </form>
                            </div>
                        </React.Fragment>
                    )}
                </div>
            </main>

            <QuoteSuccessDialog
                isOpen={sendState === 'success'}
                name={name}
                referralId={referralId}
                onOk={function () { navigate('/specialists/' + id); }}
            />
        </Layout>
    );
};

window.ContactSpecialistPage = ContactSpecialistPage;
