import { Host, h } from "@stencil/core";
import { fb } from '../../utils/utils';
import { converter } from '../../utils/converter';
import { cdnAsset, formatCurrency, markdown } from '../../utils/utils';
export class BbListing {
    constructor() {
        this.overlay = {
            kind: '',
            selected: 0,
        };
        this.message = {
            name: '',
            email: '',
            telephone: '',
            content: ''
        };
        this.sendMessage = async () => {
            this.overlay = {
                kind: 'spinner',
                selected: 0
            };
            let response = await fetch(`https://beta.boaterbase.com/api/listings/${this.listingId}/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!');
                let body = await response.json();
                console.log(response, body);
            }
            else {
                this.overlay = {
                    kind: '',
                    selected: 0
                };
            }
        };
    }
    get listingId() {
        // Allow for pretty urls where the id is at the end
        return this.listingPath.split('-').pop();
    }
    async componentDidLoad() {
        // load async
        this.listingSnaphot = await fb.firestore().collection('listings').doc(this.listingId).get();
        // Change meta data
        document.title = this.listingSnaphot.exists ? this.listingSnaphot.get('title') : 'Listing Not Found';
        //const title = await document.querySelector("head title"); //.componentOnReady();
    }
    render() {
        console.log(this.listingSnaphot);
        if (!this.listingSnaphot)
            return h(Host, null,
                h("ion-icon", { name: "help-buoy", class: "spin", style: { width: '2rem', display: 'block', margin: '40vh auto', color: '#cde' } }));
        if (!this.listingSnaphot.exists)
            return h(Host, null, "Missing");
        const listing = this.listingSnaphot.data();
        console.log(listing, listing.created.toDate());
        const specs = listing.specifications || {};
        const media = listing.media || [];
        const content = listing.content || [];
        const primaryMedia = listing.media[0];
        const selectedMedia = this.overlay && listing.media[this.overlay.selected];
        //const primaryVariant = listing.variants && listing.variants[0];
        const shortTitle = ([specs.loa && Math.round(converter('length', 'm', 'ft', specs.loa)) + "'", specs.year, specs.manufacturer, specs.manufacturer && specs.model, specs.category, specs.classification]).filter(Boolean).slice(0, 3);
        let mediaLength = (listing.media || []).length;
        let mediaStack = (listing.media || []).slice(0, 12);
        return (h(Host, null,
            h("div", { class: "hover-zoom", style: { margin: '1rem', position: 'relative', borderRadius: 'var(--bb-border-radius)' } },
                h("svg", { viewBox: "0 0 16 9", style: { display: 'block', width: '100%', background: 'lightblue', borderRadius: 'var(--bb-border-radius)' } }),
                primaryMedia && h("div", { onClick: () => this.overlay = { kind: 'media', selected: 0 }, style: { position: 'absolute', top: '0', left: '0', width: '100%', height: '100%' } },
                    primaryMedia.info.resource_type == 'image' && h("img", { style: { borderRadius: 'var(--bb-border-radius)', display: 'block', width: '100%', height: '100%', objectFit: 'cover' }, src: cdnAsset(primaryMedia.info, 'jpg', 't_large_image') }),
                    primaryMedia.info.resource_type == 'video' && h("video", { style: { borderRadius: 'var(--bb-border-radius)', display: 'block', width: '100%', height: '100%', objectFit: 'cover' }, poster: cdnAsset(primaryMedia.info, 'jpg', 't_large_image'), controls: true },
                        h("source", { src: cdnAsset(primaryMedia.info, 'm3u8', 't_streaming_video'), type: "application/x-mpegURL" }),
                        h("source", { src: cdnAsset(primaryMedia.info, 'mp4', 't_progressive_video'), type: "video/mp4" }))),
                listing.message && h("div", { style: { position: 'absolute', top: '0.5rem', left: '0.5rem', background: 'rgba(255,50,0,0.8)', color: 'white', fontSize: '0.85rem', fontWeight: '600', padding: '0.5rem', borderRadius: '3px' } }, listing.message),
                h("div", { style: { position: 'absolute', paddingTop: '1rem', bottom: '0', left: '0', width: '100%', color: '#fff' } },
                    h("div", { style: { display: 'flex', alignItems: 'flex-end', margin: '0.5rem' } },
                        h("div", { style: { flex: 'auto' } },
                            h("div", { style: { fontWeight: '600', fontSize: '1.5rem', margin: '0 0 0.25rem 0' } }, shortTitle.join(' · ')),
                            listing.location && h("div", { style: { color: 'inherit', opacity: '0.5', fontWeight: '400' } },
                                h("ion-icon", { name: "pin" }),
                                listing.location)),
                        h("div", { style: { flex: 'auto', textAlign: 'right' } },
                            h("div", { style: { fontSize: '0.8rem', fontWeight: '500', textTransform: 'uppercase', opacity: '0.5' } }, listing.label),
                            h("div", { style: { fontSize: '1.3rem', fontWeight: '700' } }, listing.price && formatCurrency(listing.price, listing.currency)))))),
            h("div", null,
                h("div", { style: { margin: '1rem', display: 'flex', flexWrap: 'wrap' } },
                    h("div", { style: { flex: '5 1 600px', paddingRight: '1rem' } },
                        h("h1", { class: "title" }, listing.title),
                        h("p", { class: "summary" }, listing.summary)),
                    h("div", { style: { flex: '1 1 300px' } },
                        h("button", { class: "contact-button", onClick: () => this.overlay = { kind: 'contact' } },
                            h("img", { style: { display: 'none', borderRadius: '0.2rem', width: '4rem', height: '4rem' }, src: "https://gravatar.com/avatar/b6de1b5951e1ab139a39968f907c4f77?d=mp" }),
                            h("div", { style: { flex: 'auto', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0.5rem' } },
                                h("span", { style: { fontSize: '1.5rem', fontWeight: '600', display: 'block' } }, "Contact"),
                                h("span", { style: { fontSize: '1rem', opacity: '0.8' } }, listing.profile && listing.profile.data && listing.profile.data.name ? ` ${listing.profile.data.name}` : 'Owner'))))),
                h("ul", { class: "specs" },
                    specs.category && h("li", null,
                        h("h3", null, "Category"),
                        h("span", null, specs.category)),
                    specs.classification && h("li", null,
                        h("h3", null, "Classification"),
                        h("span", null, specs.classification)),
                    specs.manufacturer && h("li", null,
                        h("h3", null, "Manufacturer"),
                        h("span", null, specs.manufacturer)),
                    specs.model && h("li", null,
                        h("h3", null, "Model"),
                        h("span", null, specs.model)),
                    specs.designer && h("li", null,
                        h("h3", null, "Designer"),
                        h("span", null, specs.designer)),
                    specs.builder && h("li", null,
                        h("h3", null, "Builder"),
                        h("span", null, specs.builder)),
                    specs.loa ? h("li", null,
                        h("h3", null, "Length Overall"),
                        h("span", null,
                            converter('length', 'm', 'ft', specs.loa),
                            " ",
                            h("small", null, "ft"))) : null,
                    specs.lwl ? h("li", null,
                        h("h3", null, "Length At Waterline"),
                        h("span", null,
                            converter('length', 'm', 'ft', specs.lwl),
                            " ",
                            h("small", null, "ft"))) : null,
                    specs.beam ? h("li", null,
                        h("h3", null, "Beam"),
                        h("span", null,
                            converter('length', 'm', 'ft', specs.beam).toFixed(2),
                            " ",
                            h("small", null, "ft"))) : null,
                    specs.draft ? h("li", null,
                        h("h3", null, "Draft"),
                        h("span", null,
                            converter('length', 'm', 'ft', specs.draft).toFixed(2),
                            " ",
                            h("small", null, "ft"))) : null,
                    specs.haw ? h("li", null,
                        h("h3", null, "Height Above Waterline"),
                        h("span", null,
                            converter('length', 'm', 'ft', specs.haw),
                            " ",
                            h("small", null, "ft"))) : null,
                    specs.profile && h("li", null,
                        h("h3", null, "Profile"),
                        h("span", null, specs.profile)),
                    specs.material && h("li", null,
                        h("h3", null, "Material"),
                        h("span", null, specs.material)),
                    specs.displacement ? h("li", null,
                        h("h3", null, "Displacement"),
                        h("span", null,
                            specs.displacement.toFixed(2),
                            " ",
                            h("small", null, "kg"))) : null,
                    specs.weight ? h("li", null,
                        h("h3", null, "Weight"),
                        h("span", null,
                            specs.weight.toFixed(2),
                            " ",
                            h("small", null, "kg"))) : null,
                    specs.propulsion && h("li", null,
                        h("h3", null, "Propulsion"),
                        h("span", null, specs.propulsion)),
                    specs.engines ? h("li", null,
                        h("h3", null, "Engines"),
                        h("span", null, specs.engines)) : null,
                    specs.power ? h("li", null,
                        h("h3", null, "Engine Power"),
                        h("span", null,
                            specs.power.toFixed(2),
                            " ",
                            h("small", null, "kw"))) : null,
                    specs.fuelcapacity ? h("li", null,
                        h("h3", null, "Fuel Capacity"),
                        h("span", null,
                            specs.fuelcapacity.toFixed(2),
                            " ",
                            h("small", null, "l"))) : null,
                    specs.watercapacity ? h("li", null,
                        h("h3", null, "Water Capacity"),
                        h("span", null,
                            specs.watercapacity.toFixed(2),
                            " ",
                            h("small", null, "l"))) : null,
                    specs.berths ? h("li", null,
                        h("h3", null, "Berths"),
                        h("span", null, specs.berths)) : null,
                    specs.cabins ? h("li", null,
                        h("h3", null, "Cabins"),
                        h("span", null, specs.cabins)) : null,
                    specs.certification && h("li", null,
                        h("h3", null, "Certification"),
                        h("span", null, specs.certification)),
                    specs.hullid && h("li", null,
                        h("h3", null, "Hull Id"),
                        h("span", null, specs.hullid)),
                    specs.registry && h("li", null,
                        h("h3", null, "Registery"),
                        h("span", null, specs.registry)),
                    specs.name && h("li", null,
                        h("h3", null, "Name"),
                        h("span", null, specs.name))),
                h("div", { class: "media-flex" },
                    mediaStack.map((m, i) => (h("div", null,
                        h("img", { class: "hover-zoom", onClick: () => { this.overlay = { kind: 'media', selected: i }; }, src: cdnAsset(m.info, 'jpg', 't_small_image') })))),
                    h("div", { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '1rem', background: '#eee', color: '#666', borderRadius: '0.25rem' }, class: "hover-zoom", onClick: () => { this.overlay = { kind: 'media', selected: 0 }; } },
                        h("ion-icon", { name: "photos" }),
                        mediaLength)),
                h("div", { style: { margin: '1rem', fontSize: '1rem', lineHeight: '1.4rem', padding: '1px 0' } }, content.map(({ kind, text }) => h("div", { class: "markdown" }, kind == 'text' && markdown(text)))),
                h("div", null, listing.variants && listing.variants.map(variant => (h("div", { style: { display: 'flex', alignItems: 'center', color: '#000', padding: '1rem' } },
                    h("div", null,
                        h("div", { style: { textTransform: 'uppercase', fontSize: '0.75rem' } }, variant.label),
                        !variant.amount ? h("strong", { style: { fontSize: '1.5rem', fontWeight: '600' } }, "Price on Request") : h("strong", { style: { fontSize: '1.5rem', fontWeight: '600' } },
                            formatCurrency(variant.amount, variant.currency),
                            variant.rate != 'once' && h("small", { style: { opacity: '0.5', fontWeight: '100', fontSize: '0.9rem' } },
                                "/",
                                variant.rate))),
                    h("div", { style: { flex: 'auto', marginLeft: '1rem', paddingLeft: '1rem', borderLeft: '1px solid #eee' } },
                        h("h5", { style: { margin: '0', fontSize: '1rem' } }, variant.name),
                        h("p", { style: { color: '#aaa', fontWeight: '300', margin: '0' } }, variant.description)),
                    h("div", null,
                        variant.action == 'contact' && h("button", { class: "contact-button", style: { padding: '0.75rem', fontSize: '1rem', fontWeight: '500' }, onClick: () => this.overlay = { kind: 'contact' } }, variant.button || 'Contact'),
                        variant.action == 'link' && h("a", { class: "contact-button", href: variant.link, style: { padding: '0.75rem', fontSize: '1rem', fontWeight: '500' } }, variant.button || 'Link'))))))),
            this.overlay && this.overlay.kind == 'spinner' && 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("ion-icon", { name: "close", size: "large" })),
                h("ion-icon", { name: "help-buoy", class: "spin", style: { width: '2rem', display: 'block', margin: '40vh auto', color: '#cde' } })),
            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("ion-icon", { name: "close", size: "large" })),
                h("form", { onSubmit: this.sendMessage, class: "contact-form", style: { display: 'flex', flexDirection: 'column' } },
                    h("h2", null,
                        "Contact ",
                        listing.profile && listing.profile.data && listing.profile.data.name ? ` ${listing.profile.data.name}` : 'Owner'),
                    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"))),
            this.overlay && this.overlay.kind == 'media' && h("div", { id: "mediaOverlay", style: { position: 'fixed', zIndex: '999999', top: '0', left: '0', width: '100%', height: '100%', background: 'rgba(0,0,0,0.9)', backdropFilter: 'blur(15px)' } },
                h("div", { style: { position: 'absolute', bottom: '0', width: '100%', height: '58px', display: 'flex', flexDirection: 'column', alignItems: 'center' } },
                    h("div", { style: { flex: 'none', display: 'flex', overflowX: 'auto' } }, media.map((m, i) => (h("img", { class: "gallery-thumb", onClick: () => { this.overlay = { kind: 'media', selected: i }; }, style: { cursor: 'pointer', borderRadius: '3px', margin: '2px', flex: 'none', objectFit: 'cover', width: '52px', height: '52px' }, src: m.info.thumbnail_url }))))),
                h("div", { key: this.overlay.selected, style: { position: 'absolute', left: '0', width: '100%', top: '60px', bottom: '60px', padding: '0 10px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' } },
                    selectedMedia.info.resource_type == 'image' && h("img", { onLoad: (ev) => ev.target.style.opacity = '1.0', style: { opacity: '0', transition: 'opacity 0.5s', borderRadius: '3px', boxShadow: '0 0 20px rgba(0,0,0,0.5)', display: 'block', margin: 'auto', maxWidth: '100%', maxHeight: '100%' }, src: cdnAsset(selectedMedia.info, 'jpg', 't_large_image') }),
                    selectedMedia.info.resource_type == 'video' && h("video", { onLoad: (ev) => ev.target.style.opacity = '1.0', style: { opacity: '0', transition: 'opacity 0.5s', borderRadius: '3px', boxShadow: '0 0 20px rgba(0,0,0,0.5)', display: 'block', margin: 'auto', maxWidth: '100%', maxHeight: '100%' }, autoplay: true, poster: cdnAsset(selectedMedia.info, 'jpg', 't_large_image'), controls: true },
                        h("source", { src: cdnAsset(selectedMedia.info, 'm3u8', 't_streaming_video'), type: "application/x-mpegURL" }),
                        h("source", { src: cdnAsset(selectedMedia.info, 'mp4', 't_progressive_video'), type: "video/mp4" }))),
                h("button", { onClick: () => { this.overlay = { kind: 'media', selected: Math.max(0, this.overlay.selected - 1) }; }, style: { display: this.overlay.selected == 0 ? 'none' : 'block', cursor: 'pointer', position: 'absolute', left: '3px', top: '50%', padding: '9px', borderRadius: '3px', appearance: 'none', border: 'none', background: 'rgba(0,0,0,0.1)', color: 'white' } },
                    h("ion-icon", { name: "arrow-back", size: "large" })),
                h("button", { onClick: () => { this.overlay = { kind: 'media', selected: Math.min(media.length - 1, this.overlay.selected + 1) }; }, style: { display: this.overlay.selected == media.length - 1 ? 'none' : 'block', cursor: 'pointer', position: 'absolute', right: '3px', top: '50%', padding: '9px', borderRadius: '3px', appearance: 'none', border: 'none', background: 'rgba(0,0,0,0.1)', color: 'white' } },
                    h("ion-icon", { name: "arrow-forward", size: "large" })),
                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.1)', color: 'white' } },
                    h("ion-icon", { name: "close", size: "large" })),
                h("div", { style: { position: 'absolute', top: '5px', height: '50px', left: '60px', right: '60px', color: 'white', opacity: '0.9', display: 'block', textOverflow: 'ellipsis', fontWeight: '300', lineHeight: '16px', fontSize: '14px', textAlign: 'center', overflow: 'hidden', lineClamp: '3' } }, selectedMedia.description)),
            h("div", { style: { display: 'none' } },
                h("form", { style: { borderRadius: '0.5rem', background: '#f1f1f1', padding: '1rem' } },
                    "Updates",
                    h("input", { type: "email", placeholder: "Enter your email for updates..." }),
                    h("button", null, "Subscribe"))),
            h("div", { style: { display: 'none', opacity: '0.5' } },
                "Listing Created on ",
                listing.created.toDate().toLocaleString())));
    }
    static get is() { return "bb-listing"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["bb-listing.css"]
    }; }
    static get styleUrls() { return {
        "$": ["bb-listing.css"]
    }; }
    static get properties() { return {
        "listingPath": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "listing-path",
            "reflect": false
        },
        "history": {
            "type": "any",
            "mutable": false,
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "history",
            "reflect": false
        }
    }; }
    static get states() { return {
        "listingSnaphot": {},
        "overlay": {},
        "message": {}
    }; }
}
