/* GETCOURSE — SCHEDULE PAGE / v1.0 */
(function () {
    'use strict';

    const IS_TARGET =
        window.controllerId === 'control/schedule' &&
        window.actionId === 'index';

    if (!IS_TARGET) return;

    document.documentElement.classList.add('psych-schedule-loading');

    const cleanText = value =>
        String(value || '').replace(/\s+/g, ' ').trim();

    const months = {
        янв: 0, фев: 1, мар: 2, апр: 3, май: 4, июн: 5,
        июл: 6, авг: 7, сен: 8, окт: 9, ноя: 10, дек: 11
    };

    function currentTime() {
        return window.nowTime instanceof Date
            ? new Date(window.nowTime.getTime())
            : new Date();
    }

    function parseDate(text) {
        const now = currentTime();
        const source = cleanText(text).toLowerCase();

        const timeMatch = source.match(/(\d{1,2}):(\d{2})/);
        const hours = timeMatch ? Number(timeMatch[1]) : 0;
        const minutes = timeMatch ? Number(timeMatch[2]) : 0;

        if (source.includes('вчера')) {
            return new Date(
                now.getFullYear(),
                now.getMonth(),
                now.getDate() - 1,
                hours,
                minutes
            );
        }

        if (source.includes('сегодня')) {
            return new Date(
                now.getFullYear(),
                now.getMonth(),
                now.getDate(),
                hours,
                minutes
            );
        }

        if (source.includes('завтра')) {
            return new Date(
                now.getFullYear(),
                now.getMonth(),
                now.getDate() + 1,
                hours,
                minutes
            );
        }

        const dateMatch = source.match(
            /(\d{1,2})\s+(янв|фев|мар|апр|май|июн|июл|авг|сен|окт|ноя|дек)/
        );

        if (!dateMatch) return null;

        let date = new Date(
            now.getFullYear(),
            months[dateMatch[2]],
            Number(dateMatch[1]),
            hours,
            minutes
        );

        const halfYear = 183 * 24 * 60 * 60 * 1000;

        if (date.getTime() < now.getTime() - halfYear) {
            date.setFullYear(date.getFullYear() + 1);
        } else if (date.getTime() > now.getTime() + halfYear) {
            date.setFullYear(date.getFullYear() - 1);
        }

        return date;
    }

    function getState(date) {
        if (!date) {
            return { key: 'future', label: 'Событие' };
        }

        const now = currentTime();

        const sameDay =
            date.getFullYear() === now.getFullYear() &&
            date.getMonth() === now.getMonth() &&
            date.getDate() === now.getDate();

        if (sameDay) {
            return date.getTime() > now.getTime()
                ? { key: 'today', label: 'Сегодня' }
                : { key: 'past', label: 'Прошло' };
        }

        return date.getTime() > now.getTime()
            ? { key: 'future', label: 'Скоро' }
            : { key: 'past', label: 'Прошло' };
    }

    function splitDate(text) {
        const source = cleanText(text);
        const timeMatch = source.match(/(\d{1,2}:\d{2})/);

        return {
            day: cleanText(
                source.replace(timeMatch?.[0] || '', '')
            ),
            time: timeMatch?.[1] || ''
        };
    }

    function getEvents() {
        const rows = Array.from(
            document.querySelectorAll(
                '.standard-page-content table.table tbody tr, ' +
                '.standard-page-content table.table > tr'
            )
        );

        return rows.map(row => {
            const cells = row.querySelectorAll('td');
            if (cells.length < 2) return null;

            const dateText = cleanText(
                cells[0].querySelector('.lesson-state')?.textContent ||
                cells[0].textContent
            );

            const link = cells[1].querySelector('a[href]');
            if (!link) return null;

            const lessonNode = link.querySelector('i');
            const lesson = cleanText(lessonNode?.textContent);
            const full = cleanText(link.textContent);

            let course = full;
            if (lesson) {
                course = cleanText(
                    full.replace(lesson, '')
                ).replace(/:\s*$/, '');
            }

            const teacher =
                cells[2] ? cleanText(cells[2].textContent) : '';

            const date = parseDate(dateText);
            const state = getState(date);
            const dateParts = splitDate(dateText);

            return {
                href: link.getAttribute('href'),
                course,
                lesson: lesson || full,
                teacher,
                date,
                dateText,
                day: dateParts.day,
                time: dateParts.time,
                state
            };
        }).filter(Boolean);
    }

    function isPrivileged() {
        const u = window.userInfo || {};
        return !!(u.isAdmin || u.isManager || u.isTeacher);
    }

    function buildCard(event) {
        const privileged = isPrivileged();
        const future =
            event.date &&
            event.date.getTime() > currentTime().getTime();

        const clickable = privileged || !future;
        const card = document.createElement(
            clickable ? 'a' : 'div'
        );

        card.className =
            'psych-schedule-card' +
            (!clickable ? ' is-disabled' : '');

        if (clickable) {
            card.href = event.href;
        } else {
            card.setAttribute('aria-disabled', 'true');
        }

        card.innerHTML = `
            <div class="psych-schedule-date">
                <span class="psych-schedule-date__day"></span>
                <span class="psych-schedule-date__time"></span>
            </div>

            <div class="psych-schedule-content">
                <div class="psych-schedule-course"></div>
                <h2 class="psych-schedule-lesson"></h2>
                ${event.teacher
                    ? '<div class="psych-schedule-teacher"></div>'
                    : ''}
            </div>

            <span class="psych-schedule-status is-${event.state.key}">
                ${event.state.label}
            </span>
        `;

        card.querySelector(
            '.psych-schedule-date__day'
        ).textContent = event.day || event.dateText;

        card.querySelector(
            '.psych-schedule-date__time'
        ).textContent = event.time;

        card.querySelector(
            '.psych-schedule-course'
        ).textContent = event.course;

        card.querySelector(
            '.psych-schedule-lesson'
        ).textContent = event.lesson;

        const teacherNode =
            card.querySelector('.psych-schedule-teacher');

        if (teacherNode) {
            teacherNode.textContent =
                'Преподаватель: ' + event.teacher;
        }

        return card;
    }

    function buildDashboard(events) {
        const root = document.createElement('section');
        root.className = 'psych-schedule-dashboard';

        root.innerHTML = `
            <div class="psych-schedule-hero">
                <h1 class="psych-schedule-title">Расписание</h1>
                <p class="psych-schedule-subtitle">
                    Ближайшие занятия и события
                </p>
            </div>
            <div class="psych-schedule-list"></div>
        `;

        const list = root.querySelector(
            '.psych-schedule-list'
        );

        if (!events.length) {
            list.outerHTML = `
                <div class="psych-schedule-empty">
                    <h2 class="psych-schedule-empty__title">
                        Пока нет запланированных событий
                    </h2>
                    <p class="psych-schedule-empty__text">
                        Новые занятия появятся здесь, когда будут добавлены в расписание.
                    </p>
                </div>
            `;
            return root;
        }

        events.forEach(event => {
            list.appendChild(buildCard(event));
        });

        return root;
    }

    function init() {
        const container =
            document.querySelector('.demo-hh > .container');

        if (!container) return;

        if (
            document.querySelector(
                '.psych-schedule-dashboard'
            )
        ) {
            release(true);
            return;
        }

        const events = getEvents();

        container.appendChild(
            buildDashboard(events)
        );

        release(true);
    }

    function release(ready) {
        document.documentElement.classList.remove(
            'psych-schedule-loading'
        );

        if (ready) {
            document.documentElement.classList.add(
                'psych-schedule-ready'
            );
            document.body.classList.add(
                'psych-schedule-ready'
            );
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener(
            'DOMContentLoaded',
            init,
            { once: true }
        );
    } else {
        init();
    }

    [250, 700, 1400].forEach(delay => {
        window.setTimeout(init, delay);
    });

    window.setTimeout(() => {
        if (
            !document.querySelector(
                '.psych-schedule-dashboard'
            )
        ) {
            release(false);
        }
    }, 2200);
})();
