import { Component, Prop, Host, h, State, Event, Watch } from '@stencil/core';
import { cdnAsset, buildMetaData } from '../../utils/utils';
import { Head } from 'stencil-head';
let BB_API = 'https://api.boaterbase.com/api';
export class BbProfile {
    constructor() {
        this.root = '/';
        this.profileHeader = 'full';
        this.overlay = {
            kind: '',
            selected: 0,
        };
        this.message = {
            name: '',
            email: '',
            telephone: '',
            content: ''
        };
        this.filter = {
            collection: '',
            model: '',
            manufacturer: '',
            location: ''
        };
        this.linkClickHandler = (path) => (ev) => {
            let event = this.linkClick.emit({
                path: path
            });
            if (event.defaultPrevented) {
                ev.preventDefault();
            }
        };
        this.loadCount = 6;
        this.loadMoreRefHandler = (button) => {
            if ('IntersectionObserver' in window) {
                if (button) {
                    this.loadMoreIntersectionObserver && this.loadMoreIntersectionObserver.disconnect();
                    this.loadMoreIntersectionObserver = new IntersectionObserver(data => {
                        if (data[0].isIntersecting) {
                            this.loadCount = this.loadCount + 6;
                        }
                    });
                    this.loadMoreIntersectionObserver.observe(button);
                }
                else {
                    // ref is called with null when removed so remove the observer        
                    this.loadMoreIntersectionObserver && this.loadMoreIntersectionObserver.disconnect();
                }
            }
        };
        this.loadMoreClickHandler = () => {
            this.loadCount = this.loadCount + 6;
        };
        this.sendMessage = async (ev) => {
            ev.preventDefault();
            this.overlay = {
                kind: 'spinner',
                selected: 0
            };
            let response = await fetch(`${BB_API}/profiles/${this.profileResponse.id}/messages`, {
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                method: "POST",
                body: JSON.stringify(this.message)
            });
            if (response.status != 200) {
                this.overlay = {
                    kind: 'contact',
                    selected: 0
                };
                alert('There was an error, please try again!');
                console.log(response);
            }
            else {
                this.overlay = {
                    kind: '',
                    selected: 0
                };
            }
        };
    }
    fetchData() {
        return fetch(`${BB_API}/profiles/${this.profilePath}`, {
            headers: {
                'Accept': 'application/json',
            },
            method: 'GET'
        }).then();
    }
    async componentWillLoad() {
        //console.log('componentWillLoad')
        this.profileResponse = await this.fetchData().then(response => response.json());
        //console.log(this.collectionResponse)
    }
    async componentDidLoad() {
        window.scrollTo(0, 0);
    }
    async watchPath() {
        //console.log('Path Changed', newValue, oldValue)
        this.profileResponse = await this.fetchData().then(response => response.json());
    }
    watchFilterHandler() {
        // Reset the load count
        this.loadCount = 6;
    }
    render() {
        var _a, _c, _d, _e, _f, _g;
        console.log('profile', this.profileResponse);
        if (!this.profileResponse)
            return h(Host, null, "Loading...");
        else if (!this.profileResponse.id)
            return h(Host, null, "Missing!");
        else {
            const profile = this.profileResponse;
            let collections = this.profileResponse.collections || [];
            // TODO - temporary hack to push featured to top
            collections = collections.sort((a, _b) => (a.data.title.toLowerCase().includes('feature') ? -1 : 1));
            // All listings fallback
            let allListings = this.profileResponse.listings || [];
            // Only unique
            allListings = allListings && allListings.filter((obj, index, arr) => arr.findIndex(f => (f.id === obj.id)) === index);
            const models = allListings && [...new Set(allListings.map(l => l.data.specifications.model).filter(Boolean))];
            const manufacturers = allListings && [...new Set(allListings.map(l => l.data.specifications.manufacturer).filter(Boolean))];
            const locations = allListings && [...new Set(allListings.map(l => l.data.location).filter(Boolean))];
            let filteredListings = allListings;
            if (this.filter.collection) {
                filteredListings = filteredListings && collections.filter(({ id }) => id == this.filter.collection)[0].data.listings;
            }
            if (this.filter.model) {
                filteredListings = filteredListings && filteredListings.filter(l => l.data.specifications.model == this.filter.model);
            }
            if (this.filter.manufacturer) {
                filteredListings = filteredListings && filteredListings.filter(l => l.data.specifications.manufacturer == this.filter.manufacturer);
            }
            if (this.filter.location) {
                filteredListings = filteredListings && filteredListings.filter(l => l.data.location == this.filter.location);
            }
            const filteredCount = filteredListings ? filteredListings.length : 0;
            filteredListings = filteredListings && filteredListings.slice(0, this.loadCount);
            const meta = buildMetaData(profile.name || profile.handle, profile.summary, 'profile', ((_c = (_a = profile === null || profile === void 0 ? void 0 : profile.header) === null || _a === void 0 ? void 0 : _a.info) === null || _c === void 0 ? void 0 : _c.secure_url) && cdnAsset(profile.header.info, 'jpg', 't_large_image'));
            return h(Host, null,
                h("div", { style: { display: 'none' } },
                    h(Head, { data: meta })),
                this.profileHeader == 'overlay' && h("div", { class: "header", style: { backgroundImage: profile.header && profile.header.info && profile.header.info.secure_url && `url('${cdnAsset(profile.header.info, 'jpg', 't_large_image')}')` } },
                    h("svg", { viewBox: "0 0 3 1", style: { display: 'block', width: '100%' } }),
                    h("div", { class: "header-overlay" },
                        profile.avatar && profile.avatar.info && profile.avatar.info.secure_url && h("img", { src: profile.avatar.info.secure_url, class: "header-avatar" }),
                        h("h1", { style: { margin: '0.5rem 1rem' } }, profile.name || profile.handle),
                        h("div", { style: { margin: '0.5rem 1rem' } }, profile.summary),
                        h("div", { style: { display: 'flex', padding: '0.25rem' } },
                            h("button", { class: "contact-button", onClick: () => this.overlay = { kind: 'contact' } }, "Send Message"),
                            ((_d = profile === null || profile === void 0 ? void 0 : profile.data) === null || _d === void 0 ? void 0 : _d.email) && h("a", { class: "contact-button", href: `mailto:${(_e = profile === null || profile === void 0 ? void 0 : profile.data) === null || _e === void 0 ? void 0 : _e.email}` }, "Email"),
                            ((_f = profile === null || profile === void 0 ? void 0 : profile.data) === null || _f === void 0 ? void 0 : _f.telephone) && h("a", { class: "contact-button", href: `tel:${(_g = profile === null || profile === void 0 ? void 0 : profile.data) === null || _g === void 0 ? void 0 : _g.telephone}` }, "Call")))),
                this.profileHeader == 'image' && h("div", { class: "header", style: { backgroundImage: profile.header && profile.header.info && profile.header.info.secure_url && `url('${cdnAsset(profile.header.info, 'jpg', 't_large_image')}')` } },
                    h("svg", { viewBox: "0 0 3 1", style: { display: 'block', width: '100%' } })),
                this.profileHeader == 'full' && h("div", null,
                    h("div", { class: "header", style: { backgroundImage: profile.header && profile.header.info && profile.header.info.secure_url && `url('${cdnAsset(profile.header.info, 'jpg', 't_large_image')}')` } },
                        h("svg", { viewBox: "0 0 3 1", style: { display: 'block', width: '100%' } })),
                    h("div", { style: { display: 'flex', alignItems: 'center', margin: '0 1rem 1rem 1rem' } },
                        profile.avatar && profile.avatar.info && profile.avatar.info.secure_url && h("img", { src: profile.avatar.info.secure_url, class: "full-avatar" }),
                        h("div", { style: { width: '1rem', height: '1rem', flex: 'none' } }),
                        h("div", null,
                            h("h1", { style: { margin: '0', fontSize: '1.35rem', fontWeight: '600' } }, profile.name || profile.handle),
                            h("p", { style: { margin: '0', fontSize: '1rem', opacity: '0.75' } }, profile.summary),
                            h("div", { style: { fontSize: '0.9rem', opacity: '0.5', marginTop: '0.25rem' } },
                                profile.location,
                                " ",
                                profile.website && h("a", { href: profile.website, class: "link-button" },
                                    h("i", { style: { display: 'inline-block', width: '1rem', height: '1rem', background: `url('https://api.iconify.design/fa-solid:link.svg')` } }),
                                    " Website"),
                                " ",
                                profile.twitter && h("a", { href: profile.twitter, class: "link-button" },
                                    h("i", { style: { display: 'inline-block', width: '1rem', height: '1rem', background: `url('https://api.iconify.design/fa:twitter-square.svg')` } }),
                                    " Twitter"),
                                " ",
                                profile.facebook && h("a", { href: profile.facebook, class: "link-button" },
                                    h("i", { style: { display: 'inline-block', width: '1rem', height: '1rem', background: `url('https://api.iconify.design/brandico:facebook-rect.svg')` } }),
                                    " Facebook"))),
                        h("div", { style: { padding: '0.25rem', margin: '0 1rem', flex: 'none' } },
                            h("button", { class: "contact-button", onClick: () => this.overlay = { kind: 'contact' } }, "Send Message"),
                            (profile === null || profile === void 0 ? void 0 : profile.email) && h("a", { class: "contact-button", href: `mailto:${profile === null || profile === void 0 ? void 0 : profile.email}` }, "Email"),
                            (profile === null || profile === void 0 ? void 0 : profile.telephone) && h("a", { class: "contact-button", href: `tel:${profile === null || profile === void 0 ? void 0 : profile.telephone}` }, "Call")))),
                collections && h("div", null, collections.map((collection) => (collection.listings && collection.listings.length > 0 && h("div", null,
                    h("a", { style: { display: 'flex', alignItems: 'center', margin: '0.5rem 1rem', fontWeight: '300', textDecoration: 'none', color: 'inherit', }, onClick: this.linkClickHandler(`collections/${collection.id}`), href: `${this.root}collections/${collection.id}` },
                        h("h2", { style: { flex: 'auto', textDecoration: 'none', color: 'inherit', margin: '0', fontSize: '1.3rem' } }, collection.data.title),
                        h("span", null,
                            "All ",
                            h("i", { style: { display: 'inline-block', width: '1rem', height: '1rem', background: `url('https://api.iconify.design/ion:arrow-forward-sharp.svg')` } }))),
                    h("div", { class: "card-grid" },
                        collection.listings.map(listing => h("div", { class: "card-grid-item" },
                            h("bb-listing-card", { listingId: listing.id, listingData: listing.data, root: this.root }))),
                        h("div", { class: "card-grid-item" }),
                        h("div", { class: "card-grid-item" })))))),
                (!collections || collections.length == 0) && h("div", null,
                    h("form", { class: "search-form" },
                        h("select", { class: "search-form-select", onChange: ({ target }) => this.filter = Object.assign(Object.assign({}, this.filter), { location: target.value }) },
                            h("option", { selected: this.filter.location == '', value: "" }, "All Locations"),
                            locations && locations.map(location => h("option", { selected: this.filter.location == location, value: location }, location))),
                        h("select", { class: "search-form-select", onChange: ({ target }) => this.filter = Object.assign(Object.assign({}, this.filter), { model: target.value }) },
                            h("option", { selected: this.filter.model == '', value: "" }, "All Models"),
                            models && models.map(model => h("option", { selected: this.filter.model == model, value: model }, model))),
                        h("select", { class: "search-form-select", onChange: ({ target }) => this.filter = Object.assign(Object.assign({}, this.filter), { manufacturer: target.value }) },
                            h("option", { selected: this.filter.manufacturer == '', value: "" }, "All Manufacturers"),
                            manufacturers && manufacturers.map(manufacturer => h("option", { selected: this.filter.manufacturer == manufacturer, value: manufacturer }, manufacturer)))),
                    filteredListings && h("div", { class: "card-grid" },
                        filteredListings.map(listing => h("div", { class: "card-grid-item" },
                            h("bb-listing-card", { listingId: listing.id, listingData: listing.data, root: this.root }))),
                        h("div", { class: "card-grid-item" }),
                        h("div", { class: "card-grid-item" })),
                    (this.loadCount < filteredCount) && h("button", { ref: this.loadMoreRefHandler, onClick: this.loadMoreClickHandler }, "Load More")),
                this.overlay && this.overlay.kind == 'contact' && h("div", { style: { position: 'fixed', zIndex: '999999', top: '0', left: '0', width: '100%', height: '100%', background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(5px)' } },
                    h("button", { onClick: () => this.overlay = null, style: { cursor: 'pointer', position: 'absolute', top: '3px', right: '3px', padding: '9px', borderRadius: '3px', appearance: 'none', border: 'none', background: 'rgba(0,0,0,0.5)', color: 'white' } },
                        h("bb-icon", { icon: "fe:close", color: "white", size: "2rem" })),
                    h("form", { onSubmit: this.sendMessage, class: "contact-form", style: { display: 'flex', flexDirection: 'column' } },
                        h("h2", null,
                            "Contact ",
                            profile.name || profile.handle || profile.id),
                        h("input", { type: "text", required: true, placeholder: "Name *", value: this.message.name, onChange: (event) => this.message = Object.assign(Object.assign({}, this.message), { name: event.target.value }) }),
                        h("input", { type: "email", required: true, placeholder: "Email *", value: this.message.email, onChange: (event) => this.message = Object.assign(Object.assign({}, this.message), { email: event.target.value }) }),
                        h("input", { type: "telephone", placeholder: "Telephone", value: this.message.telephone, onChange: (event) => this.message = Object.assign(Object.assign({}, this.message), { telephone: event.target.value }) }),
                        h("textarea", { required: true, placeholder: "Message *", value: this.message.content, onChange: (event) => this.message = Object.assign(Object.assign({}, this.message), { content: event.target.value }) }),
                        h("button", { type: "submit" }, "Send Message"))));
        }
    }
    static get is() { return "bb-profile"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["bb-profile.css"]
    }; }
    static get styleUrls() { return {
        "$": ["bb-profile.css"]
    }; }
    static get properties() { return {
        "profilePath": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "profile-path",
            "reflect": false
        },
        "root": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "root",
            "reflect": false,
            "defaultValue": "'/'"
        },
        "profileHeader": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "'none' | 'overlay' | 'image' | 'full'",
                "resolved": "\"full\" | \"image\" | \"none\" | \"overlay\"",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "profile-header",
            "reflect": false,
            "defaultValue": "'full'"
        }
    }; }
    static get states() { return {
        "profileResponse": {},
        "overlay": {},
        "message": {},
        "filter": {},
        "loadCount": {}
    }; }
    static get events() { return [{
            "method": "linkClick",
            "name": "linkClick",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": ""
            },
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            }
        }]; }
    static get watchers() { return [{
            "propName": "profilePath",
            "methodName": "watchPath"
        }, {
            "propName": "filter",
            "methodName": "watchFilterHandler"
        }]; }
}
