import { viewRegistry } from "./registries.js";

export default class Window {

    constructor(options = {}) {

        this.title = options.title || "Window";
        this.width = options.width || 600;
        this.height = options.height || 400;

        this.viewName = options.view || null;
        this.props = options.props || {};

        this.viewInstance = null;
        this.events = {};

        this.el = null;
        this.body = null;

        this.dragging = false;
        this.offsetX = 0;
        this.offsetY = 0;
    }

    on(name, handler) {

        if (!this.events[name]) {
            this.events[name] = [];
        }

        this.events[name].push(handler);
    }

    emit(name, data) {

        const list = this.events[name] || [];

        list.forEach(fn => fn(data));
    }

    render(container = document.body) {

        this.el = document.createElement("div");
        this.el.className = "acc-window-overlay";

        this.el.innerHTML = `
        <div class="acc-window">
            <div class="acc-window-header">
                <div class="acc-window-title">${this.title}</div>
                <button class="acc-window-close">×</button>
            </div>
            <div class="acc-window-body"></div>
        </div>
        `;

        container.appendChild(this.el);

        const win = this.el.querySelector(".acc-window");
        const header = this.el.querySelector(".acc-window-header");

        this.body = this.el.querySelector(".acc-window-body");

        win.style.width = this.width + "px";
        win.style.height = this.height + "px";

        this.center();

        this.bindClose();
        this.bindDrag(win, header);

        this.mountView();

        this.injectStyles();

        return this;
    }

    center() {

        const win = this.el.querySelector(".acc-window");

        win.style.left = "50%";
        win.style.top = "50%";
        win.style.transform = "translate(-50%,-50%)";
        win.style.position = "fixed";
    }

    bindClose() {

        this.el.querySelector(".acc-window-close").onclick = () => {
            this.close();
        };

        this.el.onclick = (e) => {
            if (e.target === this.el) {
                this.close();
            }
        };
    }

    bindDrag(win, header) {

        header.style.cursor = "move";

        header.addEventListener("mousedown", (e) => {

            this.dragging = true;

            const rect = win.getBoundingClientRect();

            this.offsetX = e.clientX - rect.left;
            this.offsetY = e.clientY - rect.top;

            win.style.transform = "none";
        });

        document.addEventListener("mousemove", (e) => {

            if (!this.dragging) return;

            win.style.left = (e.clientX - this.offsetX) + "px";
            win.style.top = (e.clientY - this.offsetY) + "px";

        });

        document.addEventListener("mouseup", () => {
            this.dragging = false;
        });
    }

    async mountView() {

        if (!this.viewName) return;

        const ViewClass = viewRegistry.views
            ? viewRegistry.views[this.viewName]
            : viewRegistry[this.viewName];

        if (!ViewClass) {

            this.body.innerHTML = "View not found: " + this.viewName;

            console.error("View not found in registry:", this.viewName, viewRegistry);

            return;
        }

        this.viewInstance = new ViewClass(this.props);

        await this.viewInstance.render(this.body);

        if (this.viewInstance.on) {

            this.viewInstance.on("saved", (data) => {

                this.emit("saved", data);

                this.close();

            });

        }
    }


    close() {

        if (this.viewInstance && this.viewInstance.destroy) {
            this.viewInstance.destroy();
        }

        this.el.remove();
    }

    injectStyles() {

        if (document.getElementById("acc-window-style")) return;

        const style = document.createElement("style");
        style.id = "acc-window-style";

        style.innerHTML = `

        .acc-window-overlay{
            position:fixed;
            inset:0;
            background:rgba(0,0,0,0.35);
            z-index:9999;
            display:flex;
            align-items:center;
            justify-content:center;
        }

        .acc-window{
            background:#fff;
            border-radius:10px;
            box-shadow:0 10px 40px rgba(0,0,0,0.2);
            display:flex;
            flex-direction:column;
            overflow:hidden;
        }

        .acc-window-header{
            display:flex;
            justify-content:space-between;
            align-items:center;
            padding:10px 14px;
            background:#f5f5f5;
            border-bottom:1px solid #eee;
            font-weight:600;
        }

        .acc-window-title{
            font-size:14px;
        }

        .acc-window-close{
            border:none;
            background:transparent;
            font-size:20px;
            cursor:pointer;
            line-height:1;
        }

        .acc-window-body{
            flex:1;
            overflow:auto;
            padding:10px;
        }

        `;

        document.head.appendChild(style);
    }

}
