// SmartFlowTestView.js

import BaseView from "../../core/BaseView.js";
import { viewRegistry } from "../../core/registries.js";
import { SmartFlowComponent } from "../../smartflow/smartflow-component.js";

class SmartFlowTestView extends BaseView {
    static title = "SmartFlow Test";

    async render(container) {
        await super.render(container);

        const body = this.ref("body");
        body.innerHTML = `
            <div style="padding:1rem;">
                <h2>📦 SmartFlow Test</h2>

                <div style="margin:1rem 0;">
                    <label>شناسه سند:</label>
                    <input type="number" id="sf-voucher-id" value="1" style="width:120px;">
                    <button id="sf-load-btn" class="button">بارگذاری</button>
                </div>

                <div id="sf-root" style="border:1px solid #ccc; padding:1rem; min-height:400px;"></div>
            </div>
        `;

        this.initSmartFlow();
        return this;
    }

    // initSmartFlow() {
    //     const container = this.ref("body").querySelector("#sf-root");

    //     this.smartflow = new SmartFlowComponent(container, {
    //         dimensions: ['cost_center', 'project'],
    //         greedyFlow: true
    //     });

    //     const btn = this.ref("body").querySelector("#sf-load-btn");
    //     btn.addEventListener("click", () => {
    //         const id = this.ref("body").querySelector("#sf-voucher-id").value;
    //         this.smartflow.load(id);
    //     });

    //     console.log("SmartFlow test view mounted");
    // }

    initSmartFlow() {

        const container = this.ref("body").querySelector("#sf-root");

        if (!container) {
            console.error("SmartFlow container not found");
            return;
        }

        this.smartflow = new SmartFlowComponent(container, {
            apiClient: this.api(),   // ✅ این باید با پرانتز باشد
            dimensions: ['cost_center', 'project'],
            greedyFlow: true,
            debug: true
        });

        const btn = this.ref("body").querySelector("#sf-load-btn");

        if (btn) {
            btn.addEventListener("click", () => {
                const input = this.ref("body").querySelector("#sf-voucher-id");
                const id = input?.value?.trim();

                if (!id) {
                    console.warn("Voucher ID is empty");
                    return;
                }

                this.smartflow.load(id);
            });
        }

        console.log("✅ SmartFlow mounted with ApiClient");
    }

}

export default SmartFlowTestView;

// کلید باید با TabConfig یکی باشد
viewRegistry.register("accounting", SmartFlowTestView);
