#include "TutorialWindow.h"
#include <QVBoxLayout>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QScrollArea>
#include <QCoreApplication>
#include "widget/common/CollapsibleSection.h"

TutorialWindow::TutorialWindow(QWidget *parent)
    : QWidget(parent,
              Qt::Window
              | Qt::WindowTitleHint
              | Qt::WindowSystemMenuHint
              | Qt::WindowCloseButtonHint
              | Qt::WindowMinMaxButtonsHint) {
    setWindowTitle(tr("Инструкция"));
    setMinimumSize(800, 400);
    resize(1000, 600);

    // Основной контейнер со всеми разделами
    auto *container = new QWidget(this);
    auto *layout = new QVBoxLayout(container);
    layout->setSpacing(10);

    const QString tutorialsPath = QCoreApplication::applicationDirPath() + "/tutorials";
    // Загружаем Markdown-файлы
    const QDir dir(tutorialsPath);
    const QStringList files = dir.entryList({"*.md"}, QDir::Files, QDir::Name);
    for (int i = 0; i < files.size(); ++i) {
        const QString &fileName = files.at(i);

        QFile file(dir.absoluteFilePath(fileName));
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            continue;
        QTextStream in(&file);
        QString titleLine = in.readLine().trimmed();
        QString content = in.readAll().trimmed();
        file.close();

        QString title = !titleLine.isEmpty() ? titleLine.replace("#", "") : QFileInfo(file).baseName();

        auto *section = new CollapsibleSection(title, content, container, i == 0);
        layout->addWidget(section);

        if (i == 0) {
        }
    }
    layout->addStretch();

    QSpacerItem *spacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
    layout->addItem(spacer);

    // Скролл вокруг контейнера
    auto *scroll = new QScrollArea(this);
    scroll->setWidget(container);
    scroll->setWidgetResizable(true);
    scroll->setAlignment(Qt::AlignTop | Qt::AlignLeft);

    auto *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->addWidget(scroll);
    setLayout(mainLayout);
}
