class FB2Reader {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.pages = [];
        this.currentPageIndex = 0;
        this.chapters = [];
        this.fontSize = 18;
        this.fontFamily = 'serif';
        this.content = '';
        this.sections = [];
    }

    async load(xmlText) {
        const parser = new DOMParser();
        const doc = parser.parseFromString(xmlText, 'text/xml');

        const fb = 'http://www.gribuser.ru/xml/fictionbook/2.0';

        // Extract body sections
        const bodies = doc.getElementsByTagNameNS(fb, 'body');

        let html = '';
        this.chapters = [];

        for (let body of bodies) {
            const sections = body.getElementsByTagNameNS(fb, 'section');

            for (let i = 0; i < sections.length; i++) {
                const section = sections[i];
                const sectionHtml = this.parseFb2Section(section, fb, i);
                html += sectionHtml;
            }
        }

        this.content = html;
        this.render();
        this.paginate();
    }

    parseFb2Section(section, ns, index) {
        let html = '';
        let chapterTitle = '';

        for (let child of section.children) {
            const localName = child.localName;

            switch (localName) {
                case 'title':
                    const titleText = this.extractText(child);
                    chapterTitle = titleText;
                    html += `<h2 class="fb2-title" data-chapter="${index}">${titleText}</h2>`;
                    this.chapters.push({
                        label: titleText,
                        href: index.toString(),
                        index: index
                    });
                    break;

                case 'p':
                    html += `<p>${this.extractText(child)}</p>`;
                    break;

                case 'empty-line':
                    html += '<br/>';
                    break;

                case 'subtitle':
                    html += `<h3>${this.extractText(child)}</h3>`;
                    break;

                case 'epigraph':
                    html += `<blockquote class="epigraph">${this.parseInnerContent(child, ns)}</blockquote>`;
                    break;

                case 'poem':
                    html += `<div class="poem">${this.parsePoem(child, ns)}</div>`;
                    break;

                case 'cite':
                    html += `<blockquote>${this.parseInnerContent(child, ns)}</blockquote>`;
                    break;

                case 'image':
                    // Handle inline images if needed
                    break;

                case 'section':
                    html += this.parseFb2Section(child, ns, this.chapters.length);
                    break;
            }
        }

        return `<div class="fb2-section" data-section="${index}">${html}</div>`;
    }

    extractText(element) {
        let text = '';
        for (let node of element.childNodes) {
            if (node.nodeType === Node.TEXT_NODE) {
                text += node.textContent;
            } else if (node.nodeType === Node.ELEMENT_NODE) {
                const tag = node.localName;
                switch (tag) {
                    case 'strong':
                        text += `<strong>${this.extractText(node)}</strong>`;
                        break;
                    case 'emphasis':
                        text += `<em>${this.extractText(node)}</em>`;
                        break;
                    case 'a':
                        text += `<a>${this.extractText(node)}</a>`;
                        break;
                    case 'strikethrough':
                        text += `<s>${this.extractText(node)}</s>`;
                        break;
                    default:
                        text += this.extractText(node);
                }
            }
        }
        return text;
    }

    parseInnerContent(element, ns) {
        let html = '';
        for (let child of element.children) {
            if (child.localName === 'p') {
                html += `<p>${this.extractText(child)}</p>`;
            } else if (child.localName === 'text-author') {
                html += `<p class="text-author">— ${this.extractText(child)}</p>`;
            }
        }
        return html;
    }

    parsePoem(element, ns) {
        let html = '';
        for (let child of element.children) {
            if (child.localName === 'stanza') {
                html += '<div class="stanza">';
                for (let v of child.children) {
                    if (v.localName === 'v') {
                        html += `<p class="verse">${this.extractText(v)}</p>`;
                    }
                }
                html += '</div>';
            } else if (child.localName === 'title') {
                html += `<h4>${this.extractText(child)}</h4>`;
            } else if (child.localName === 'text-author') {
                html += `<p class="text-author">— ${this.extractText(child)}</p>`;
            }
        }
        return html;
    }

    render() {
        this.container.innerHTML = `
            <div id="fb2-inner" style="
                font-size: ${this.fontSize}px;
                font-family: ${this.fontFamily};
                line-height: 1.6;
                padding: 20px;
                height: 100%;
                overflow: hidden;
                column-width: ${window.innerWidth - 40}px;
                column-gap: 40px;
                column-fill: auto;
            ">
                <style>
                    .fb2-title { margin: 1em 0 0.5em; text-align: center; }
                    .fb2-section { margin-bottom: 1em; }
                    p { text-indent: 1.5em; margin-bottom: 0.3em; }
                    .epigraph { font-style: italic; margin: 1em 2em; }
                    .poem { margin: 1em 2em; }
                    .verse { text-indent: 0; }
                    .stanza { margin-bottom: 1em; }
                    .text-author { text-align: right; font-style: italic; }
                    blockquote { margin: 1em 2em; padding-left: 1em; border-left: 3px solid #ccc; }
                </style>
                ${this.content}
            </div>
        `;
    }

    paginate() {
        const inner = document.getElementById('fb2-inner');
        if (!inner) return;

        const containerWidth = this.container.clientWidth;
        const scrollWidth = inner.scrollWidth;
        const pageWidth = containerWidth;

        this.totalPages = Math.ceil(scrollWidth / pageWidth);
        if (this.totalPages < 1) this.totalPages = 1;

        this.showPage(this.currentPageIndex);
    }

    showPage(pageIndex) {
        if (pageIndex < 0) pageIndex = 0;
        if (pageIndex >= this.totalPages) pageIndex = this.totalPages - 1;

        this.currentPageIndex = pageIndex;
        const inner = document.getElementById('fb2-inner');
        if (inner) {
            const offset = pageIndex * this.container.clientWidth;
            inner.style.transform = `translateX(-${offset}px)`;
        }
    }

    nextPage() {
        if (this.currentPageIndex < this.totalPages - 1) {
            this.showPage(this.currentPageIndex + 1);
        }
    }

    prevPage() {
        if (this.currentPageIndex > 0) {
            this.showPage(this.currentPageIndex - 1);
        }
    }

    getProgress() {
        if (this.totalPages <= 1) return 0;
        return this.currentPageIndex / (this.totalPages - 1);
    }

    getCurrentPage() {
        return this.currentPageIndex + 1;
    }

    getTotalPages() {
        return this.totalPages || 1;
    }

    getCurrentChapter() {
        // Find which chapter we're in based on page position
        const inner = document.getElementById('fb2-inner');
        if (!inner) return '';

        const titles = inner.querySelectorAll('.fb2-title');
        let currentChapter = '';

        for (let title of titles) {
            const rect = title.getBoundingClientRect();
            const containerRect = this.container.getBoundingClientRect();
            const offset = this.currentPageIndex * this.container.clientWidth;

            if (title.offsetLeft <= offset + this.container.clientWidth) {
                currentChapter = title.textContent;
            }
        }

        return currentChapter;
    }

    getChapters() {
        return this.chapters;
    }

    setFontSize(size) {
        this.fontSize = size;
        this.render();
        setTimeout(() => this.paginate(), 100);
    }

    setFontFamily(family) {
        this.fontFamily = family;
        this.render();
        setTimeout(() => this.paginate(), 100);
    }

    goToChapter(chapterIndex) {
        const inner = document.getElementById('fb2-inner');
        if (!inner) return;

        const section = inner.querySelector(`[data-chapter="${chapterIndex}"]`);
        if (section) {
            const offset = section.offsetLeft;
            const pageIndex = Math.floor(offset / this.container.clientWidth);
            this.showPage(pageIndex);
        }
    }

    goToPosition(progress) {
        const pageIndex = Math.floor(progress * (this.totalPages - 1));
        this.showPage(pageIndex);
    }
}