var _useState_SP = React.useState;
var _useEffect_SP = React.useEffect;
var _useParams_SP = ReactRouterDOM.useParams;
var _useLocation_SP = ReactRouterDOM.useLocation;

/**
 * SpecialistProfilePage — Detailed specialist profile view, against the live Specialists
 * Search API (specialists-api-reference-pack) via SpecialistsService.getById.
 *
 * `:id` is now the stable `mds-…` id (INTEGRATION-GUIDE.md §9 — safe to persist, survives
 * re-crawls). SpecialistDirectoryPage's card navigates here with `navigate(path, {state:
 * {specialist}})` so the already-fetched record can paint instantly (MemoryRouter supports
 * navigation state — App.jsx uses it as the app's router); this page still ALWAYS fetches
 * by id itself, since that's the always-correct path when there's no nav state at all —
 * a bookmark, a reload, a deep link, or the ContactSpecialistPage back-navigation case.
 *
 * Route: /specialists/:id
 */
var SpecialistProfilePage = function () {
    var navigate = ReactRouterDOM.useNavigate();
    var params = _useParams_SP();
    var location = _useLocation_SP();
    var id = params.id;
    var navState = location && location.state;

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

    // 'loading' | 'ready' | 'error' — 'ready' the instant nav-state data is present, even
    // before the authoritative fetch below lands.
    var statusState = _useState_SP(specialist ? 'ready' : 'loading');
    var status = statusState[0];
    var setStatus = statusState[1];

    var errorState = _useState_SP(null); // { reason } — only set on a real failure
    var loadError = errorState[0];
    var setLoadError = errorState[1];

    _useEffect_SP(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;
                // A nav-state record is already on screen — a failed refresh is not news;
                // otherwise this is the page's own failure state.
                if (!specialist) {
                    setLoadError({ reason: res.reason });
                    setStatus('error');
                }
                return;
            }
            setSpecialist(res);
            setStatus('ready');
            AnalyticsService.specialistProfileViewed({
                specialist_category: (res.categories && res.categories[0]) || 'unknown',
                specialist_city: (res.location && res.location.suburb) || 'unknown',
            });
        });

        return function () {
            cancelled = true;
            controller.abort();
        };
        // eslint-disable-next-line -- intentionally id-only: re-running on `specialist`
        // changes would abort/refetch the very request that just populated it.
    }, [id]);

    var retry = function () {
        setStatus('loading');
        setLoadError(null);
        // Re-fetch by re-running the effect via a fresh id-scoped call is unnecessary
        // machinery here — a full remount is simplest and correct for a profile page's
        // retry button, so just re-invoke the same fetch inline.
        SpecialistsService.getById(id).then(function (res) {
            if (res && res.error) {
                setLoadError({ reason: res.reason });
                setStatus('error');
                return;
            }
            setSpecialist(res);
            setStatus('ready');
        });
    };


    if (status === 'loading') {
        return (
            <Layout>
                <main className="flex-1 overflow-y-auto overflow-x-hidden pb-36">
                    <PageHeader title="Specialist" 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-36">
                    <PageHeader title="Specialist" 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 categories = specialist.categories || [];
    var contact = specialist.contact || {};
    var loc = specialist.location || {};
    var mouldDetect = specialist.mould_detect || {};
    var accreditations = specialist.accreditations || [];
    var vetting = SpecialistVetting.describe(mouldDetect);

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

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

                    {/* Primary Actions */}
                    <section className="flex w-full gap-3 px-0 -mt-2 mb-4">
                            {contact.phone && (
                                <a
                                    href={'tel:' + contact.phone}
                                    className="flex-1 flex items-center justify-center gap-2 bg-forest text-white rounded-xl h-12 font-bold shadow-soft btn-nature hover:bg-primary transition-colors"
                                >
                                    <span className="material-symbols-outlined text-lg">call</span>
                                    <span className="text-sm">Call Now</span>
                                </a>
                            )}
                            <button
                                onClick={function () {
                                    AnalyticsService.contactProfessionalInitiated({ specialist_category: categories[0] || 'unknown' });
                                    navigate('/specialists/' + id + '/contact', { state: { specialist: specialist } });
                                }}
                                className="flex-1 flex items-center justify-center gap-2 bg-background-light text-forest rounded-xl h-12 font-bold btn-nature hover:text-white hover:bg-forest transition-colors border border-forest-200"
                            >
                                <span className="material-symbols-outlined text-lg">chat_bubble</span>
                                <span className="text-sm">Request Quote</span>
                            </button>
                    </section>

                    {/* Accreditations — silence when empty (pack §6: absence means "we
                        didn't capture one", never "they don't have one"; NEVER render
                        "No accreditations"). */}
                    {accreditations.length > 0 && (
                        <section className="py-4">
                            <h3 className="text-base font-extrabold text-forest mb-3 flex items-center gap-2">
                                <span className="material-symbols-outlined text-forest text-lg">workspace_premium</span>
                                Accreditations
                            </h3>
                            <div className="flex gap-2 flex-wrap">
                                {accreditations.map(function (a) {
                                    return (
                                        <span key={a} className="px-3 py-1.5 rounded-full bg-primary/10 text-primary text-xs font-bold border border-primary/20 flex items-center gap-1">
                                            <SpecialistVetting.CheckSeal size={12} />
                                            {a}
                                        </span>
                                    );
                                })}
                            </div>
                        </section>
                    )}

                    {/* Contact Details — sparse-field rule: render only what's present. */}
                    <section className="mb-4">
                        <h3 className="text-base font-extrabold text-forest mb-3 flex items-center gap-2">
                            <span className="material-symbols-outlined text-forest text-lg">contact_page</span>
                            Contact Details
                        </h3>
                        <div className="bio-bg bio-bg-10 rounded-xl p-4 shadow-soft border border-stone-100/50 space-y-3">
                            {loc.address && (
                                <div className="flex items-start gap-3">
                                    <span className="material-symbols-outlined text-forest text-lg mt-0.5">location_on</span>
                                    <p className="text-sm text-forest/80 font-medium">
                                        {loc.address}
                                        {loc.geocode_precision === 'postcode' ? ' (approx.)' : ''}
                                    </p>
                                </div>
                            )}
                            {contact.phone && (
                                <div className="flex items-center gap-3">
                                    <span className="material-symbols-outlined text-forest text-lg">call</span>
                                    <a href={'tel:' + contact.phone} className="text-sm text-primary font-bold">{contact.phone}</a>
                                </div>
                            )}
                            {contact.website && (
                                <div className="flex items-center gap-3">
                                    <span className="material-symbols-outlined text-forest text-lg">language</span>
                                    <a href={contact.website} target="_blank" rel="noopener noreferrer" className="text-sm text-primary font-bold truncate">{contact.website.replace(/^https?:\/\//, '').replace(/\/$/, '')}</a>
                                </div>
                            )}
                            {contact.email && (
                                <div className="flex items-center gap-3">
                                    <span className="material-symbols-outlined text-forest text-lg">mail</span>
                                    <a href={'mailto:' + contact.email} className="text-sm text-primary font-bold">{contact.email}</a>
                                </div>
                            )}
                            {!loc.address && !contact.phone && !contact.website && !contact.email && (
                                <p className="text-xs text-forest/60 font-medium">No contact details on file for this listing.</p>
                            )}
                        </div>
                    </section>

                    {/* Listed categories — SOURCED data only. The old "Services Offered"
                        chips were synthesized per-category boilerplate: claims the business
                        never made. Third-party information renders only from genuine API
                        fields (user decision 2026-08-08). */}
                    {categories.length > 1 && (
                        <section className="mb-4">
                            <h3 className="text-base font-extrabold text-forest mb-3 flex items-center gap-2">
                                <span className="material-symbols-outlined text-forest text-lg">list_alt</span>
                                Listed Categories
                            </h3>
                            <div className="flex gap-2 flex-wrap">
                                {categories.map(function (c) {
                                    return (
                                        <span key={c} className="px-3 py-1.5 rounded-full bg-forest/10 text-forest text-xs font-bold border border-forest/20">
                                            {c}
                                        </span>
                                    );
                                })}
                            </div>
                        </section>
                    )}

                    {/* Reviews — hidden until real data source available */}
                    <SpecialistReviews specialistName={name} visible={false} />

                    {/* Bottom CTA */}
                    <section className="mb-4">
                        <button
                            onClick={function () { navigate('/specialists/' + id + '/contact', { state: { specialist: specialist } }); }}
                            className="w-full bg-forest text-white font-extrabold py-4 rounded-xl shadow-soft btn-nature hover:bg-primary transition-colors flex items-center justify-center gap-2"
                        >
                            <span>Request a Quote</span>
                            <span className="material-symbols-outlined text-lg">send</span>
                        </button>
                    </section>
                </div>
            </main>
        </Layout>
    );
};

window.SpecialistProfilePage = SpecialistProfilePage;
