/**
 * ServiceWorkspace — پوسته یکپارچه: عملیات میدانی + پاداش
 */
import ServiceRewardWorkspace from './ServiceRewardWorkspace.js';
import ServicePortalOperations from './ServicePortalOperations.js';
import ServiceSupplierWorkspace from './ServiceSupplierWorkspace.js';
import ServiceTalentAdmin from './ServiceTalentAdmin.js';
import ServiceMarketerWorkspace from './ServiceMarketerWorkspace.js';

export default class ServiceWorkspace {
    constructor({
        root, request, dashboard, actorType, siteUrl, onRefresh,
        apiBase, canOperations, serviceRole, initialTab, customerPhone, isSupplier, isMarketer,
    }) {
        this.root = root;
        this.request = request;
        this.dashboard = dashboard;
        this.actorType = actorType || 'customer';
        this.isSupplier = !!isSupplier || actorType === 'supplier';
        this.isMarketer = !!isMarketer || actorType === 'marketer';
        this.customerPhone = customerPhone || dashboard?.account?.phone || '';
        this.siteUrl = siteUrl || '/acc-engine/';
        this.onRefresh = onRefresh || (async () => this.dashboard);
        this.apiBase = apiBase;
        this.canOperations = !!canOperations;
        this.serviceRole = serviceRole || '';
        this._tab = initialTab || (this.isMarketer ? 'marketer' : (canOperations ? 'operations' : (this.isSupplier ? 'supplier' : 'profile')));
        this._rewardWs = null;
        this._supplierWs = null;
        this._marketerWs = null;
        this._ops = null;
        this._profileSubTab = 'cases';
        this._profileSteps = null;
        this._profileCache = null;
        this._talentAdmin = null;
    }

    async init() {
        this.root.innerHTML = this._shellHtml();
        this._bindTabs();
        await this._renderTab();
    }

    _shellHtml() {
        const opsTab = this.canOperations
            ? `<button class="svc-ws-tab ${this._tab === 'operations' ? 'svc-ws-tab--active' : ''}" data-tab="operations">🔧 عملیات میدانی</button>`
            : '';
        const profileTab = this.actorType === 'customer'
            ? `<button class="svc-ws-tab ${this._tab === 'profile' ? 'svc-ws-tab--active' : ''}" data-tab="profile">📁 پرونده من</button>`
            : '';
        const supplierTab = this.isSupplier
            ? `<button class="svc-ws-tab ${this._tab === 'supplier' ? 'svc-ws-tab--active' : ''}" data-tab="supplier">📦 کاتالوگ و سفارشات</button>`
            : '';
        const marketerTab = this.isMarketer
            ? `<button class="svc-ws-tab ${this._tab === 'marketer' ? 'svc-ws-tab--active' : ''}" data-tab="marketer">📣 پنل بازاریابی</button>`
            : '';
        const rewardActive = this._tab === 'rewards'
            || (!this.canOperations && !this.isMarketer && this._tab !== 'profile' && this._tab !== 'supplier' && this._tab !== 'talent');

        const canTalentReview = this.canOperations
            && (this.serviceRole === 'senior' || this.serviceRole === 'admin' || this.serviceRole === 'manager');
        const talentTab = canTalentReview
            ? `<button class="svc-ws-tab ${this._tab === 'talent' ? 'svc-ws-tab--active' : ''}" data-tab="talent">🌐 جذب کارشناس</button>`
            : '';

        return `<div class="svc-unified" dir="rtl">
            <div class="svc-ws-tabs svc-ws-tabs--main" data-ref="mainTabs">
                ${opsTab}
                ${profileTab}
                ${supplierTab}
                ${talentTab}
                ${marketerTab}
                <button class="svc-ws-tab ${rewardActive ? 'svc-ws-tab--active' : ''}" data-tab="rewards">🎁 پاداش HVAC</button>
            </div>
            <div class="svc-ws-panel svc-ws-panel--main" data-ref="mainPanel"></div>
            ${this.actorType === 'customer' ? `
            <div class="svc-chat-hint">
                💬 برای ثبت درخواست یا پیگیری، از دکمه <strong>پشتیبانی آنلاین</strong> پایین صفحه استفاده کنید.
            </div>` : ''}
        </div>`;
    }

    _bindTabs() {
        this.root.querySelector('[data-ref="mainTabs"]')?.querySelectorAll('[data-tab]').forEach(btn => {
            btn.addEventListener('click', async () => {
                const tab = btn.dataset.tab;
                if (tab === this._tab) return;
                this._tab = tab;
                this.root.querySelectorAll('[data-ref="mainTabs"] .svc-ws-tab').forEach(b =>
                    b.classList.toggle('svc-ws-tab--active', b.dataset.tab === tab));
                await this._renderTab();
            });
        });
    }

    async _renderTab() {
        const panel = this.root.querySelector('[data-ref="mainPanel"]');
        if (!panel) return;

        if (this._tab === 'marketer' && this.isMarketer) {
            if (this._ops) { this._ops.destroy(); this._ops = null; }
            panel.innerHTML = '<div data-ref="marketerRoot"></div>';
            const mRoot = panel.querySelector('[data-ref="marketerRoot"]');
            this._marketerWs = new ServiceMarketerWorkspace({
                root: mRoot,
                request: this.request,
                dashboard: this.dashboard,
                siteUrl: this.siteUrl,
                onRefresh: this.onRefresh,
            });
            await this._marketerWs.init();
            return;
        }

        if (this._tab === 'operations' && this.canOperations) {
            if (this._ops) {
                this._ops.destroy();
                this._ops = null;
            }
            panel.innerHTML = '<div class="svc-ops-panel" data-ref="opsRoot"></div>';
            const opsRoot = panel.querySelector('[data-ref="opsRoot"]');
            this._ops = new ServicePortalOperations({ root: opsRoot, apiBase: this.apiBase });
            await this._ops.init();
            return;
        }

        if (this._tab === 'profile' && this.actorType === 'customer') {
            if (this._ops) { this._ops.destroy(); this._ops = null; }
            if (this._supplierWs) { this._supplierWs.destroy(); this._supplierWs = null; }
            await this._renderCustomerProfile(panel);
            return;
        }

        if (this._tab === 'supplier' && this.isSupplier) {
            if (this._ops) { this._ops.destroy(); this._ops = null; }
            if (this._rewardWs) { this._rewardWs = null; }
            panel.innerHTML = '<div data-ref="supplierRoot"></div>';
            const supplierRoot = panel.querySelector('[data-ref="supplierRoot"]');
            this._supplierWs = new ServiceSupplierWorkspace({
                root: supplierRoot,
                request: this.request,
                siteUrl: this.siteUrl,
            });
            await this._supplierWs.init();
            return;
        }

        if (this._ops) {
            this._ops.destroy();
            this._ops = null;
        }
        if (this._supplierWs) {
            this._supplierWs.destroy();
            this._supplierWs = null;
        }

        if (this._tab === 'talent') {
            if (this._ops) { this._ops.destroy(); this._ops = null; }
            if (this._rewardWs) { this._rewardWs = null; }
            if (this._talentAdmin) { this._talentAdmin.destroy(); this._talentAdmin = null; }
            panel.innerHTML = '<div data-ref="talentRoot"></div>';
            const talentRoot = panel.querySelector('[data-ref="talentRoot"]');
            this._talentAdmin = new ServiceTalentAdmin({
                root: talentRoot,
                request: this.request,
            });
            await this._talentAdmin.init();
            return;
        }

        panel.innerHTML = '<div data-ref="rewardRoot"></div>';
        const rewardRoot = panel.querySelector('[data-ref="rewardRoot"]');
        this._rewardWs = new ServiceRewardWorkspace({
            root: rewardRoot,
            request: this.request,
            dashboard: this.dashboard,
            actorType: this.actorType,
            siteUrl: this.siteUrl,
            onRefresh: this.onRefresh,
        });
        await this._rewardWs.init();
    }

    async _renderCustomerProfile(panel) {
        const phone = this.customerPhone;
        panel.innerHTML = '<div class="acc-loading">⏳ بارگذاری پرونده...</div>';
        if (!phone) {
            panel.innerHTML = '<div class="acc-empty">شماره موبایل یافت نشد — دوباره وارد شوید.</div>';
            return;
        }
        try {
            if (!this._profileCache) {
                const apiBase = (this.apiBase || '/acc-engine/api.php/acc/v1').replace(/\/$/, '');
                const [devRes, casesRes] = await Promise.all([
                    fetch(`${apiBase}/service/customer/devices?phone=${encodeURIComponent(phone)}`),
                    fetch(`${apiBase}/service/visitor/cases?phone=${encodeURIComponent(phone)}`),
                ]);
                this._profileCache = {
                    devices: (await devRes.json())?.data ?? [],
                    cases: (await casesRes.json())?.data ?? [],
                };
            }
            this._profilePanel = panel;
            this._renderProfileShell();
        } catch (e) {
            panel.innerHTML = `<div class="acc-error">❌ ${this._esc(e.message)}</div>`;
        }
    }

    _renderProfileShell() {
        const panel = this._profilePanel;
        if (!panel || !this._profileCache) return;

        const { cases, devices } = this._profileCache;
        const stepsTab = this._profileSteps
            ? `<button class="svc-ws-tab svc-profile-tab ${this._profileSubTab === 'steps' ? 'svc-ws-tab--active' : ''}" data-ptab="steps">⏱ مراحل ${this._esc(this._profileSteps.code)} — ${this._esc(this._profileSteps.title)}</button>`
            : '';

        panel.innerHTML = `
        <div class="svc-profile-wrap">
            <div class="svc-ws-tabs svc-profile-tabs" data-ref="profileTabs">
                <button class="svc-ws-tab svc-profile-tab ${this._profileSubTab === 'cases' ? 'svc-ws-tab--active' : ''}" data-ptab="cases">📋 پرونده‌های خدمات (${cases.length})</button>
                <button class="svc-ws-tab svc-profile-tab ${this._profileSubTab === 'devices' ? 'svc-ws-tab--active' : ''}" data-ptab="devices">❄️ دستگاه‌های ثبت‌شده (${devices.length})</button>
                ${stepsTab}
            </div>
            <div class="svc-profile-content" data-ref="profileContent"></div>
        </div>`;

        panel.querySelector('[data-ref="profileTabs"]')?.querySelectorAll('[data-ptab]').forEach(btn => {
            btn.addEventListener('click', () => {
                const tab = btn.dataset.ptab;
                if (tab === this._profileSubTab) return;
                this._profileSubTab = tab;
                this._renderProfileShell();
            });
        });

        const content = panel.querySelector('[data-ref="profileContent"]');
        if (this._profileSubTab === 'cases') {
            this._renderProfileCases(content, cases);
        } else if (this._profileSubTab === 'devices') {
            this._renderProfileDevices(content, devices);
        } else if (this._profileSubTab === 'steps' && this._profileSteps) {
            this._renderProfileSteps(content);
        }
    }

    _renderProfileCases(content, cases) {
        if (!cases.length) {
            content.innerHTML = '<div class="acc-empty">درخواستی ثبت نشده — از ویجت پشتیبانی شروع کنید.</div>';
            return;
        }
        const focus = sessionStorage.getItem('svc_demo_focus_code') || '';
        if (focus) sessionStorage.removeItem('svc_demo_focus_code');
        content.innerHTML = `<div class="svc-cases-grid">${cases.map(c => `
            <div class="svc-case-card${focus && c.tracking_code === focus ? ' svc-case-card--focus' : ''}">
                <div class="svc-case-head">
                    <span class="svc-case-code">${this._esc(c.tracking_code)}</span>
                    <span class="svc-case-type">${this._esc(c.service_type_label || c.service_type)}</span>
                </div>
                <div class="svc-case-meta">${this._esc(c.site_label || '—')} · ${this._esc(c.status_label || c.status)}</div>
                <button class="acc-btn acc-btn--sm svc-case-track"
                    data-code="${this._esc(c.tracking_code)}"
                    data-title="${this._esc(c.service_type_label || c.service_type)}">📋 مشاهده مراحل</button>
            </div>`).join('')}</div>`;

        content.querySelectorAll('.svc-case-track').forEach(btn => {
            btn.addEventListener('click', () => {
                this._profileSteps = { code: btn.dataset.code, title: btn.dataset.title };
                this._profileSubTab = 'steps';
                this._renderProfileShell();
            });
        });
        if (focus) {
            const focusBtn = content.querySelector(`.svc-case-card--focus .svc-case-track`);
            if (focusBtn) focusBtn.click();
        }
    }

    _renderProfileDevices(content, devices) {
        if (!devices.length) {
            content.innerHTML = '<div class="acc-empty">دستگاهی ثبت نشده — پس از اولین سرویس، دستگاه‌ها اینجا نمایش داده می‌شوند.</div>';
            return;
        }
        content.innerHTML = `<div class="svc-profile-grid">${devices.map(d => `
            <div class="svc-profile-card">
                <h4>❄️ ${this._esc(d.brand || '')} ${this._esc(d.model || '')}</h4>
                <div class="svc-profile-meta">${this._esc(d.device_type || '—')} · ${this._esc(d.site_label || d.install_location || '')}</div>
                <div class="svc-profile-meta">ساعت کار: <b>${d.operating_hours || 0}</b> · مبرد: ${this._esc(d.refrigerant || '—')}</div>
                ${(d.alerts || []).length ? `<div class="svc-profile-alerts">${d.alerts.map(a =>
                    `<div class="svc-alert">⚠️ ${this._esc(a.message || a)}</div>`
                ).join('')}</div>` : '<div style="color:#059669;font-size:12px;">✓ بدون هشدار مصرفی</div>'}
            </div>`).join('')}</div>`;
    }

    async _renderProfileSteps(content) {
        const { code, title } = this._profileSteps || {};
        if (!code) return;

        content.innerHTML = '<div class="acc-loading">⏳ بارگذاری مراحل...</div>';
        try {
            const apiBase = (this.apiBase || '/acc-engine/api.php/acc/v1').replace(/\/$/, '');
            const res = await fetch(`${apiBase}/service/visitor/track/${encodeURIComponent(code)}`);
            const json = await res.json();
            const d = json?.data;
            if (!d) throw new Error(json?.message || 'یافت نشد');

            const tl = (d.timeline || []).map(t => `
                <div class="svc-tl-item">
                    <div class="svc-tl-dot"></div>
                    <div>
                        <div class="svc-tl-label">${this._esc(t.label)}</div>
                        <div class="svc-tl-at">${this._esc((t.at || '').slice(0, 16))}${t.total ? ` · ${Number(t.total).toLocaleString('fa-IR')} ت` : ''}</div>
                    </div>
                </div>`).join('');

            content.innerHTML = `
            <div class="svc-case-detail-box">
                <div class="svc-steps-head">
                    <div>
                        <h4>⏱ مراحل ${this._esc(d.tracking_code || code)} — ${this._esc(d.service_type_label || title)}</h4>
                        <div class="svc-case-meta">${this._esc(d.site_label || '—')} · وضعیت: <b>${this._esc(d.status_label || d.status)}</b></div>
                    </div>
                    <button class="acc-btn acc-btn--sm acc-btn--secondary" data-back-cases>◀ بازگشت به لیست</button>
                </div>
                <div class="svc-timeline">${tl || '<div class="acc-empty">—</div>'}</div>
                ${d.payment?.pay_url ? `<a class="acc-btn" href="${this._esc(d.payment.pay_url)}" target="_blank" style="margin-top:12px;display:inline-block;">💳 پرداخت مانده ${Number(d.payment.balance || 0).toLocaleString('fa-IR')} ت</a>` : ''}
            </div>`;

            content.querySelector('[data-back-cases]')?.addEventListener('click', () => {
                this._profileSubTab = 'cases';
                this._renderProfileShell();
            });
        } catch (e) {
            content.innerHTML = `<div class="acc-error">❌ ${this._esc(e.message)}</div>`;
        }
    }

    _esc(t) {
        return String(t ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;');
    }

    destroy() {
        this._ops?.destroy?.();
        this._ops = null;
        this._supplierWs?.destroy?.();
        this._supplierWs = null;
    }
}
