<template>
    <div class="weightLossGraph" ref="weightLossGraph">
        <div
            class="weightLossGraph__chart"
            :class="[
                series.length ? 'weightLossGraph__chart--visible' : '',
                chartRelative ? 'weightLossGraph__chart--relative' : '',
            ]"
        >
            <div class="weightLossGraph__box">
                <bmi-category-card
                    :bmi="bmi"
                    :bmi-categories="bmiCategories"
                    :assessment-link="assessmentLink"
                ></bmi-category-card>
            </div>

            <div class="weightLossGraph__box">
                <div class="weightLossGraph__chart__wrap">
                    <div class="weightLossGraph__header">
                        <h2 class="weightLossGraph__header__title">Your estimated weight loss in 1 year</h2>

                        <div class="weightLossGraph__header__loss" v-if="yearPoint">
                            <span class="weightLossGraph__header__loss__icon">
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    width="10"
                                    height="9"
                                    viewBox="0 0 10 9"
                                    fill="none"
                                >
                                    <path
                                        d="M5.42308 8.32827C5.22696 8.63965 4.77304 8.63965 4.57692 8.32827L0.286598 1.51647C0.0768878 1.18351 0.316177 0.75 0.709675 0.75L9.29032 0.750001C9.68382 0.750001 9.92311 1.18351 9.7134 1.51647L5.42308 8.32827Z"
                                        fill="currentColor"
                                    />
                                </svg>
                            </span>

                            <span class="weightLossGraph__header__loss__value" v-html="yearPoint.weight"></span>
                        </div>
                    </div>

                    <div class="weightLossGraph__apex">
                        <apexchart
                            ref="timeseriesChart"
                            type="area"
                            :height="height"
                            :options="chartOptions"
                            :series="series"
                        />
                    </div>
                </div>
                <!-- .weightLossGraph__chart -->
            </div>
        </div>

        <div
            class="weightLossGraph__slot"
            :class="[
                series.length ? 'weightLossGraph__slot--hidden' : '',
                chartRelative ? 'weightLossGraph__slot--absolute' : '',
            ]"
        >
            <slot></slot>
        </div>
    </div>
</template>

<script>
import VueApexCharts from 'vue-apexcharts'
import bmiCategoryCard from './bmi_category_card.vue'

export default {
    name: 'weightLossGraph',

    components: {
        apexchart: VueApexCharts,
        bmiCategoryCard,
    },

    props: {
        height: {
            type: Number,
            default: 400,
        },
    },

    data() {
        return {
            data: [],
            color: '#9872A8',
            weeksApart: 6,
            maxWeeks: 60,
            isMetric: true, // <-- track unit system here
            chartOptions: {
                chart: {
                    id: 'timeseries',
                    zoom: { enabled: false },
                    background: 'transparent',
                    toolbar: { show: false },
                },
                grid: {
                    show: false,
                    padding: { right: 32, bottom: 24 },
                },
                xaxis: {
                    type: 'numeric',
                    labels: {
                        formatter: (val) => `${val}`,
                        style: { cssClass: 'weightLossGraph__axisText' },
                    },
                    axisBorder: {
                        show: true,
                        color: '#D8D5E5',
                        strokeWidth: 4,
                    },
                    axisTicks: { show: false },
                    tooltip: { enabled: false },
                    title: {
                        text: 'Weeks',
                        offsetY: 16,
                        style: {
                            cssClass: 'weightLossGraph__axisText__x',
                            fontSize: '16px',
                            fontWeight: 500,
                        },
                    },
                },
                yaxis: {
                    min: undefined,
                    max: undefined,
                    labels: {
                        formatter: (val) => this.formatWeight(val), // <-- use your helper
                        style: { cssClass: 'weightLossGraph__axisText' },
                    },
                    axisBorder: {
                        show: true,
                        color: '#D8D5E5',
                        strokeWidth: 4,
                    },
                    axisTicks: { show: false },
                },
                dataLabels: { enabled: false },
                colors: ['#9872A8'],
                stroke: {
                    curve: 'straight',
                    width: 4,
                    colors: ['#9872A8'],
                    lineCap: 'round',
                },
                fill: {
                    type: 'gradient',
                    gradient: {
                        shade: 'dark',
                        type: 'vertical',
                        gradientToColors: ['#9872A8'],
                        opacityFrom: 0.6,
                        opacityTo: 0.0,
                        stops: [0, 100],
                    },
                },
                markers: {
                    size: 6,
                    hover: { size: 9 },
                    colors: ['#9872A8'],
                    strokeColors: ['#9872A8'],
                    strokeWidth: 0,
                    discrete: [
                        {
                            seriesIndex: 0,
                            dataPointIndex: 0,
                            fillColor: 'transparent',
                            strokeColor: 'transparent',
                            size: 0,
                        },
                    ],
                },
                tooltip: {
                    cssClass: 'weightLossGraph__tooltip',
                    x: {
                        show: false,
                        formatter: (val) => `Week ${val}`,
                    },
                    y: {
                        title: { formatter: () => '' },
                        formatter: (val, { series, seriesIndex, dataPointIndex, w }) => {
                            const point = w.config.series[seriesIndex].data[dataPointIndex]
                            const week = point.x
                            const percent = point.percentage.toFixed(1) // <-- use stored percentage
                            const weight = this.formatWeight(point.weight)

                            return `Weight Loss: <strong>${percent}%</strong><br/>Your Weight: <strong>${weight}</strong><br/>Week: <strong>${week}</strong>`
                        },
                    },
                },
                responsive: [
                    {
                        breakpoint: 640,
                        options: {
                            chart: {
                                height: 350,
                            },
                        },
                    },
                ],
            },
            chartPositionTimeout: null,
            slotPositionTimeout: null,
            chartRelative: false,
            yearData: false,
            bmiCategories: [],
            bmi: 0,
            assessmentLink: false,
        }
    },

    watch: {
        data(newVal) {
            this.chartRelative = newVal.length > 0
        },
    },

    mounted() {
        EventBus.$on('weightLossData', (payload) => {
            const {
                projection = [],
                isMetric = true,
                scrollIntoView = false,
                bmiCategories = [],
                bmi = 0,
                assessmentLink = false,
            } = payload

            this.isMetric = isMetric

            this.bmiCategories = bmiCategories

            this.assessmentLink = assessmentLink

            this.bmi = bmi

            //Build the data
            this.buildData(projection)

            //Scroll into view
            if (scrollIntoView) {
                this.scrollToGraph()
            }
        })
    },

    computed: {
        series() {
            return this.data.length ? this.data : []
        },

        yearPoint() {
            if (this.yearData) {
                return {
                    weightMetric: this.yearData.weight,
                    weight: this.formatWeight(this.yearData.weight),
                    percentage: this.yearData.percentage,
                }
            } else {
                return false
            }
        },
    },

    methods: {
        buildData(projection) {
            const filtered = projection
                .filter((p) => p.week <= this.maxWeeks)
                .filter(
                    (point, i, arr) =>
                        i % this.weeksApart === 0 || point.week === 0 || point.week === arr[arr.length - 1].week,
                )

            const weights = filtered.map((p) => p.weight)

            const maxWeight = Math.max(...weights)
            const minWeight = Math.min(...weights)

            // add a bit of padding above & below
            this.chartOptions.yaxis.max = Math.ceil(maxWeight + 2)
            this.chartOptions.yaxis.min = Math.floor(minWeight - 2)

            const yearData = projection.find((p) => p.week === 52)

            if (yearData) {
                this.yearData = yearData
            } else {
                this.yearData = false
            }

            this.data = [
                {
                    name: 'Weight',
                    data: filtered.map((p) => ({
                        x: p.week,
                        y: p.weight, // used for graph line
                        weight: p.weight, // actual weight
                        percentage: p.percentage, // keep % for tooltips
                    })),
                },
            ]

            return this.data
        },

        formatWeight(kg) {
            if (this.isMetric) {
                return `${kg.toFixed(1)}kg`
            } else {
                const totalLbs = kg * 2.20462
                const stones = Math.floor(totalLbs / 14)
                const pounds = Math.round(totalLbs % 14)
                return `${stones}st ${pounds}lbs`
            }
        },

        scrollToGraph() {
            this.$nextTick(() => {
                const el = this.$refs.weightLossGraph?.$el || this.$refs.weightLossGraph
                if (!el) return

                const headerOffset = 112
                const elementPosition = el.getBoundingClientRect().top + window.scrollY
                const offsetPosition = elementPosition - headerOffset

                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth',
                })
            })
        },
    },
}
</script>

<style lang="less">
.weightLossGraph {
    position: relative;
    display: flex;
    flex-direction: column;

    @media all and (max-width: 1020px) {
        max-width: 560px;
        margin: 0 auto;
    }

    &__header {
        text-align: left;
        margin: 0 0 12px;

        &__title {
            text-align: inherit;
            margin: 0;
            .rems(18);
            font-weight: 400;
            line-height: 1.2em;
            font-family: var(--primary_font);
        }

        &__loss {
            text-align: inherit;
            padding: 20px 0 0;
            display: flex;
            gap: 6px;
            align-items: center;

            &__icon {
                width: 16px;
                height: 16px;
                display: flex;
                align-items: center;
                color: #7e4f92;

                svg {
                    width: 100%;
                    height: 100%;
                }
            }

            &__value {
                .rems(40);
                line-height: 1.2em;
                font-weight: 400;
                color: inherit;
                font-family: var(--secondary_font);
            }
        }
    }

    &__apex {
        margin-top: auto;
        transform: translate(-10px, -10px);
        margin-bottom: -24px;
        width: calc(100% + 35px);

        @media @mobile {
            transform: translateY(-10px);
            margin-bottom: -24px;
            width: 100%;
        }

        & > div {
            display: flex;
            flex-direction: column;
            justify-content: flex-end;

            @media @mobile {
                width: 100%;
                max-width: 100%;
                min-width: calc(100% + 64px);
                transform: translateX(-24px);
            }

            .apexcharts-canvas {
                margin-top: auto;
            }
        }
    }

    &__box {
        border-radius: 18px;
        background: #fff;
        padding: 30px;
        margin: 0 0 30px;
        width: 100%;

        &:last-child {
            margin: 0;
        }
    }

    &__chart {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 2;
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;

        border-radius: 20px;
        background: #f2fafa;
        padding: 30px;
        margin: 0 0 0 40px;
        min-width: 0;
        //width: 100%;
        max-width: 560px;

        opacity: 0;
        visibility: hidden;
        pointer-events: none;
        transition:
            opacity 200ms linear,
            visibility 200ms linear;

        @media all and (max-width: 1120px) {
            margin: 0;
        }

        @media @mobile {
            background: transparent;
            padding: 0;
        }

        &--visible {
            opacity: 1;
            visibility: visible;
            pointer-events: auto;
            transition:
                opacity 200ms linear,
                visibility 200ms linear;
        }

        &--relative {
            position: relative;
        }

        &__wrap {
            width: 100%;
            margin: 0 auto 0 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100%;
        }
    }

    &__slot {
        z-index: 1;

        position: relative;
        opacity: 1;
        visibility: visible;
        pointer-events: auto;
        transition:
            opacity 200ms linear,
            visibility 200ms linear;

        &--absolute {
            position: absolute;
        }

        &--hidden {
            opacity: 0;
            visibility: hidden;
            pointer-events: none;
            transition: none;
        }
    }

    &__title {
        .rems(16);
        font-weight: 500;
        line-height: 1.2em;
        color: var(--text_color);
        margin: 0;
        font-family: var(--body_font);
        flex: 1 1 50%;
        display: flex;
        align-items: center;
    }

    &__axisText__x {
        .rems(14);
        line-height: 1.2em;
        font-weight: 500;
        fill: var(--text_color);
    }

    &__axisText {
        .rems(14);
        line-height: 1.2em;
        font-weight: 500;
        fill: var(--text_color);
    }

    &__tooltip {
        .apexcharts-tooltip-title {
            background: #f2edf4 !important;
            color: var(--text_color);
            border-color: var(--text_color);
        }
    }

    .apexcharts {
        &-xaxis,
        &-yaxis {
            line {
                stroke-width: 3px !important; /* change to your desired thickness */
            }
        }

        &-yaxis {
            & > line {
                stroke-width: 3px !important; /* change to your desired thickness */
            }
        }

        &-tooltip {
            &-text {
                &-y {
                    &-value {
                        .rems(14);
                        line-height: 1.2em;
                        font-weight: 400;
                        color: var(--text_color);

                        strong {
                            font-weight: bold;
                        }
                    }
                }
            }

            &-y {
                &-groupd {
                    padding: 14px 0 5px;
                }
            }
        }
    }
}
</style>
