/**
 * AragShopErpView — پنل ERP فروشگاه عرقیات
 * طراحی مدرن، رنگارنگ، کارتی
 */

const TOKEN_KEY = 'acc_token';

const SHIP_STEPS = [
    { key: 'pending',           label: 'در انتظار',     icon: '⏳' },
    { key: 'preparing',         label: 'آماده‌سازی',    icon: '📦' },
    { key: 'packed',            label: 'بسته‌بندی',     icon: '🗃' },
    { key: 'picked_up',         label: 'تحویل پیک',    icon: '🚚' },
    { key: 'in_transit',        label: 'در راه',        icon: '🛣' },
    { key: 'out_for_delivery',  label: 'توزیع',         icon: '📍' },
    { key: 'delivered',         label: 'تحویل شد',      icon: '✅' },
];
const SHIP_NEXT = {
    pending: 'preparing', preparing: 'packed', packed: 'picked_up',
    picked_up: 'in_transit', in_transit: 'out_for_delivery',
    out_for_delivery: 'delivered',
};
const SHIP_DONE = new Set(['delivered', 'cancelled', 'returned', 'failed']);

const CRM_BADGE = {
    converted:   'erp-badge--green',
    negotiating: 'erp-badge--amber',
    new_lead:    'erp-badge--blue',
    contacted:   'erp-badge--teal',
    on_hold:     'erp-badge--gray',
    lost:        'erp-badge--red',
};

const AVATAR_COLORS = ['erp-avatar--blue', 'erp-avatar--green', 'erp-avatar--purple', 'erp-avatar--amber'];

const NAV = [
    { key: 'dashboard',  label: 'داشبورد',     icon: '📊' },
    { key: 'finance',    label: 'مالی گراف',   icon: '💰' },
    { key: 'shipping',   label: 'حمل‌ونقل',     icon: '🚚' },
    { key: 'crm',        label: 'CRM مشتریان', icon: '👥' },
    { key: 'accounting', label: 'حسابداری',     icon: '📑' },
    { key: 'inventory',  label: 'انبار',        icon: '🏭' },
    { key: 'chat',       label: 'چت فروشگاه',   icon: '💬' },
];

export default class AragShopErpView {
    constructor() {
        this.root        = null;
        this.tab         = 'dashboard';
        this.token       = sessionStorage.getItem(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY) || '';
        this.role        = null;
        this.stats       = {};
        this.portal      = {};
        this.pending     = [];
        this.config      = {};
        this.crmLeads    = [];
        this.crmSummary  = {};
        this.selectedLead = null;
        this.shipments   = [];
        this.pendingOrders = [];
        this.invStock    = [];
        this.invVouchers = [];
        this.finance     = {};
        this.expenses    = [];
        this.financeMonthly = [];
        this.mizajStats  = {};
    }

    render(root) {
        this.root = root;
        if (!this.token) { this._paintLogin(); return; }
        this._paintLoading();
        this._load();
    }

    /* ─── Loading / Auth ────────────────────────────────────── */
    _paintLoading() {
        this.root.innerHTML = `
        <div class="erp-loading">
            <div class="erp-loading__spinner"></div>
            <p>در حال بارگذاری پنل ERP…</p>
        </div>`;
    }

    _paintLogin() {
        const site = this._siteUrl();
        this.root.innerHTML = `
        <div class="erp-login-wrap">
            <div class="erp-login-box">
                <div class="erp-login-box__head">
                    <div class="erp-login-box__logo">🏪</div>
                    <h2>ERP فروشگاه عرقیات</h2>
                    <p>پنل مدیریت حسابداری · CRM · حمل‌ونقل · انبار</p>
                </div>
                <div class="erp-login-box__body">
                    <form id="erp-login-form" class="erp-login-box__form">
                        <div class="erp-field">
                            <label>نام کاربری</label>
                            <input class="erp-input" name="username" required placeholder="arag_accountant" autocomplete="username">
                        </div>
                        <div class="erp-field">
                            <label>رمز عبور</label>
                            <input class="erp-input" name="password" type="password" required autocomplete="current-password">
                        </div>
                        <button class="erp-btn erp-btn--primary" type="submit" style="width:100%;justify-content:center;padding:11px;">
                            ورود به پنل ERP
                        </button>
                        <div id="erp-login-msg" hidden></div>
                    </form>
                    <div class="erp-login-hint" style="margin-top:14px">
                        arag_accountant / Demo@2026
                    </div>
                    <div class="erp-login-box__links">
                        <a href="${site}">پورتال ACC</a> · <a href="${site}shop.php">فروشگاه</a>
                    </div>
                </div>
            </div>
        </div>`;
        this.root.querySelector('#erp-login-form').addEventListener('submit', e => this._doLogin(e));
    }

    async _doLogin(e) {
        e.preventDefault();
        const msg = this.root.querySelector('#erp-login-msg');
        const fd  = new FormData(e.target);
        if (msg) msg.hidden = true;
        try {
            const r = await fetch(this._api() + '/public/auth/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username: fd.get('username'), password: fd.get('password') }),
            });
            const res = await r.json();
            if (!r.ok || !res.success || !res.token) throw new Error(res.message || 'ورود ناموفق');
            this.token = res.token;
            sessionStorage.setItem(TOKEN_KEY, res.token);
            localStorage.setItem(TOKEN_KEY, res.token);
            this._paintLoading();
            await this._load();
        } catch (err) {
            if (msg) {
                msg.hidden = false;
                msg.className = 'erp-msg erp-msg--err';
                msg.textContent = err.message;
            }
        }
    }

    async _load() {
        try {
            const roleRes = await this._get('/arag/erp/me/role');
            this.role = roleRes;
            const dash = await this._get('/arag/erp/dashboard');
            this.stats  = dash.stats  || {};
            this.portal = dash.portal || {};
            await this._loadTab();
            this._paint();
        } catch (e) {
            if (e.message?.includes('403') || e.message?.includes('دسترسی') || e.message?.includes('401')) {
                this.token = '';
                sessionStorage.removeItem(TOKEN_KEY);
                this._paintLogin();
            } else {
                this._paintDenied(e.message);
            }
        }
    }

    async _loadTab() {
        if (this.tab === 'accounting') {
            const [pend, cfg] = await Promise.all([
                this._get('/arag/erp/accounting/pending'),
                this._get('/arag/erp/accounting/config'),
            ]);
            this.pending = pend.data || [];
            this.config  = cfg.config || {};
        }
        if (this.tab === 'crm') {
            const [leads, summary] = await Promise.all([
                this._get('/arag/erp/crm/leads'),
                this._get('/arag/erp/crm/summary'),
            ]);
            this.crmLeads   = leads.data || [];
            this.crmSummary = summary.data || {};
            if (this.selectedLead?.id) {
                try {
                    const d = await this._get(`/arag/erp/crm/leads/${this.selectedLead.id}`);
                    this.selectedLead = d.data || null;
                } catch { this.selectedLead = null; }
            }
        }
        if (this.tab === 'shipping') {
            const [ships, pend] = await Promise.all([
                this._get('/arag/erp/shipping/shipments'),
                this._get('/arag/erp/shipping/orders-pending'),
            ]);
            this.shipments     = ships.data || [];
            this.pendingOrders = pend.data  || [];
        }
        if (this.tab === 'inventory') {
            const [stock, vch] = await Promise.all([
                this._get('/arag/erp/inventory/stock'),
                this._get('/arag/erp/inventory/vouchers'),
            ]);
            this.invStock    = stock.data || [];
            this.invVouchers = vch.data   || [];
        }
        if (this.tab === 'finance') {
            const [fin, exp, mon, mz] = await Promise.all([
                this._get('/arag/erp/finance/summary'),
                this._get('/arag/erp/expenses'),
                this._get('/arag/erp/finance/monthly?months=6'),
                this._get('/arag/erp/mizaj/stats'),
            ]);
            this.finance = fin.data || {};
            this.expenses = exp.data || [];
            this.financeMonthly = mon.data || [];
            this.mizajStats = mz.data || {};
            this.expenseCategories = exp.categories || fin.categories || {};
        }
    }

    _paintDenied(msg = '') {
        const site = this._siteUrl();
        this.root.innerHTML = `
        <div class="erp-loading">
            <div style="font-size:3rem">🔒</div>
            <p style="font-size:1rem;color:#ef4444;font-weight:700">${this._esc(msg || 'دسترسی ندارید')}</p>
            <p style="color:#64748b">برای ورود مجدد کلیک کنید</p>
            <button class="erp-btn erp-btn--primary" id="erp-relogin">ورود مجدد</button>
            <a href="${site}" class="erp-btn">بازگشت به ERP</a>
        </div>`;
        this.root.querySelector('#erp-relogin')?.addEventListener('click', () => {
            sessionStorage.removeItem(TOKEN_KEY);
            localStorage.removeItem(TOKEN_KEY);
            this.token = '';
            this._paintLogin();
        });
    }

    /* ─── Main layout ───────────────────────────────────────── */
    _paint() {
        const site = this._siteUrl();
        this.root.innerHTML = `
        ${this._headerHtml(site)}
        <div class="erp-layout">
            ${this._sidebarHtml()}
            <main class="erp-main" id="erp-main-content">
                ${this._panelHtml()}
            </main>
        </div>`;
        this._bind();
        // اگر تب چت بود، panel را mount کن
        if (this.tab === 'chat') this._mountChatPanel();
    }

    _mountChatPanel() {
        const el = document.getElementById('shop-chat-panel-mount');
        if (!el || el.dataset.bound) return;
        el.dataset.bound = '1';
        import('/acc-engine/assets/js/shared/portal-chat-panel.js').then(({ PortalChatPanel }) => {
            const panel = new PortalChatPanel({
                container: el,
                source:    'shop',
                token:     this.token,
                apiBase:   '/acc-engine/api.php/acc/v1',
            });
            panel.mount();
            this._shopChatInstance = panel;
        });
    }

    _headerHtml(site) {
        const name = this.portal.office_name || 'فروشگاه عرقیات';
        const initials = 'ERP';
        return `
        <header class="erp-header">
            <div class="erp-header__brand">
                <div class="erp-header__logo">🏪</div>
                <div>
                    <div class="erp-header__title">ERP ${this._esc(name)}</div>
                    <div class="erp-header__subtitle">${this._esc(this.portal.ledger_tag || 'SHOP')} · ${this.role?.is_accountant ? 'حسابدار' : 'مشاهده'}</div>
                </div>
            </div>
            <div class="erp-header__actions">
                <a href="${site}shop.php" class="erp-header__btn">🛒 فروشگاه</a>
                <a href="${site}shop-accounting.php" class="erp-header__btn">📒 حسابداری</a>
                <a href="${site}shop-admin.php" class="erp-header__btn">⚙ مدیریت</a>
                <a href="${site}" class="erp-header__btn erp-header__btn--accent">🏢 پورتال ERP اصلی</a>
                <div class="erp-header__user">
                    <div class="erp-header__avatar">${initials}</div>
                    <span>حسابدار</span>
                </div>
            </div>
        </header>`;
    }

    _sidebarHtml() {
        const s = this.stats;
        const badges = {
            accounting: s.pending_accounting > 0 ? `<span class="erp-nav-badge">${s.pending_accounting}</span>` : '',
            crm:        s.crm_shop_leads    > 0 ? `<span class="erp-nav-badge erp-nav-badge--blue">${s.crm_shop_leads}</span>` : '',
            shipping:   s.ship_active       > 0 ? `<span class="erp-nav-badge erp-nav-badge--amber">${s.ship_active}</span>` : '',
        };
        return `
        <nav class="erp-sidebar">
            <div class="erp-sidebar__group-label">منو اصلی</div>
            ${NAV.map(n => `
            <button type="button" class="erp-nav-item ${this.tab === n.key ? 'erp-nav-item--active' : ''}" data-tab="${n.key}">
                <span class="erp-nav-item__icon">${n.icon}</span>
                ${this._esc(n.label)}
                ${badges[n.key] || ''}
            </button>`).join('')}
            <div class="erp-sidebar__group-label" style="margin-top:auto">پیوندها</div>
            <a class="erp-nav-item" href="${this._siteUrl()}" style="text-decoration:none">
                <span class="erp-nav-item__icon">🏢</span>ACC ERP اصلی
            </a>
        </nav>`;
    }

    _panelHtml() {
        switch (this.tab) {
            case 'dashboard':  return this._dashboardHtml();
            case 'finance':    return this._financeHtml();
            case 'accounting': return this._accountingHtml();
            case 'crm':        return this._crmHtml();
            case 'shipping':   return this._shippingHtml();
            case 'inventory':  return this._inventoryHtml();
            case 'chat':       return `<div id="shop-chat-panel-mount" style="height:calc(100vh - 140px);"></div>`;
            default:           return this._dashboardHtml();
        }
    }

    /* ─── Dashboard ─────────────────────────────────────────── */
    _dashboardHtml() {
        const s = this.stats;
        const site = this._siteUrl();
        const cards = [
            { label: 'سفارش امروز',    value: s.orders_today       || 0, icon: '🛒', color: 'blue',   sub: 'سفارش دریافتی' },
            { label: 'پرداخت‌شده',      value: s.orders_paid        || 0, icon: '✅', color: 'green',  sub: 'آماده پردازش' },
            { label: 'صف حسابداری',     value: s.pending_accounting || 0, icon: '📑', color: 'amber',  sub: 'منتظر صدور سند' },
            { label: 'لید CRM',         value: s.crm_shop_leads     || 0, icon: '👥', color: 'purple', sub: 'مشتری فروشگاه' },
            { label: 'محموله فعال',     value: s.ship_active        || 0, icon: '🚚', color: 'teal',   sub: 'در حال ارسال' },
            { label: 'SKU موجود',       value: s.inv_skus_in_stock  || 0, icon: '🏭', color: 'rose',   sub: 'کالای انبار' },
        ];

        return `
        <div class="erp-welcome">
            <div>
                <h2>خوش آمدید به ERP فروشگاه 👋</h2>
                <p>مدیریت کامل سفارش‌ها، حمل‌ونقل، CRM و حسابداری فروشگاه از این پنل</p>
            </div>
            <div class="erp-welcome__actions">
                <button class="erp-header__btn" data-tab="shipping">📦 ثبت محموله</button>
                <button class="erp-header__btn erp-header__btn--accent" data-tab="crm">👥 مشتریان</button>
            </div>
        </div>

        <div class="erp-flow">
            <span class="erp-flow__step erp-flow__step--blue">🛒 سفارش</span>
            <span class="erp-flow__arrow">←</span>
            <span class="erp-flow__step erp-flow__step--green">✅ پرداخت</span>
            <span class="erp-flow__arrow">←</span>
            <span class="erp-flow__step erp-flow__step--purple">👥 CRM</span>
            <span class="erp-flow__arrow">←</span>
            <span class="erp-flow__step erp-flow__step--teal">🚚 محموله</span>
            <span class="erp-flow__arrow">←</span>
            <span class="erp-flow__step erp-flow__step--amber">📑 سند</span>
            <span class="erp-flow__arrow">←</span>
            <span class="erp-flow__step erp-flow__step--blue">🏭 خروج انبار</span>
        </div>

        <div class="erp-stat-grid">
            ${cards.map(c => `
            <div class="erp-stat-card">
                <div class="erp-stat-card__icon erp-stat-card__icon--${c.color}">${c.icon}</div>
                <div>
                    <div class="erp-stat-card__label">${c.label}</div>
                    <div class="erp-stat-card__value">${c.value.toLocaleString('fa-IR')}</div>
                    <div class="erp-stat-card__sub">${c.sub}</div>
                </div>
            </div>`).join('')}
        </div>

        <div class="erp-card">
            <div class="erp-card__header">
                <div>
                    <div class="erp-card__title">
                        <span class="erp-card__title-icon" style="background:#dbeafe">📋</span>
                        آخرین سفارش‌ها
                    </div>
                </div>
                <button class="erp-btn erp-btn--sm" data-tab="accounting">مشاهده همه</button>
            </div>
            <div class="erp-card__body erp-table-wrap">
                <table class="erp-table">
                    <thead><tr><th>شماره</th><th>مشتری</th><th>مبلغ</th><th>پرداخت</th><th>وضعیت</th></tr></thead>
                    <tbody>
                        ${(this.stats._recent || []).length
                            ? this.stats._recent.map(o => `
                            <tr>
                                <td><strong>${this._esc(o.order_number)}</strong></td>
                                <td>${this._esc(o.billing_name)}</td>
                                <td>${this._fmt(o.subtotal)}</td>
                                <td>${this._payBadge(o.payment_status)}</td>
                                <td>${this._statusBadge(o.order_status)}</td>
                            </tr>`).join('')
                            : `<tr><td colspan="5" class="erp-table__empty">اطلاعات سفارش از داشبورد بارگذاری نشد — به تب حسابداری بروید</td></tr>`
                        }
                    </tbody>
                </table>
            </div>
        </div>`;
    }

    /* ─── Finance Graph ─────────────────────────────────────── */
    _financeHtml() {
        const f = this.finance;
        const rev = f.revenue || {};
        const exp = f.expenses || {};
        const profit = f.profit ?? 0;
        const margin = f.margin_pct ?? 0;
        const canPost = this.role?.is_accountant;
        const cats = this.expenseCategories || {};
        const maxBar = Math.max(rev.total || 1, exp.total || 1, 1);

        const flowHtml = `
        <div class="erp-flow">
            <div class="erp-flow__node erp-flow__node--in">
                <span>درآمد فروش</span>
                <strong>${this._fmt(rev.total)}</strong>
                <small>${rev.orders || 0} سفارش</small>
            </div>
            <div class="erp-flow__arrow">→</div>
            <div class="erp-flow__split">
                <div class="erp-flow__node erp-flow__node--out">
                    <span>هزینه‌ها</span>
                    <strong>${this._fmt(exp.total)}</strong>
                </div>
                <div class="erp-flow__node erp-flow__node--profit ${profit >= 0 ? 'erp-flow__node--green' : 'erp-flow__node--red'}">
                    <span>سود خالص</span>
                    <strong>${this._fmt(profit)}</strong>
                    <small>حاشیه ${margin}٪</small>
                </div>
            </div>
        </div>`;

        const catBars = (f.expense_nodes || []).map(n => {
            const pct = Math.round((n.amount / maxBar) * 100);
            return `
            <div class="erp-cat-bar">
                <div class="erp-cat-bar__label">${n.icon} ${this._esc(n.label)}</div>
                <div class="erp-cat-bar__track"><div class="erp-cat-bar__fill" style="width:${pct}%;background:${n.color}"></div></div>
                <div class="erp-cat-bar__amt">${this._fmt(n.amount)}</div>
            </div>`;
        }).join('') || '<p class="erp-table__empty">هنوز هزینه‌ای ثبت نشده</p>';

        const monthMax = Math.max(...(this.financeMonthly.map(m => Math.max(m.revenue, m.expense)) || [1]), 1);
        const monthChart = this.financeMonthly.map(m => {
            const rh = Math.round((m.revenue / monthMax) * 100);
            const eh = Math.round((m.expense / monthMax) * 100);
            return `
            <div class="erp-month-col">
                <div class="erp-month-bars">
                    <div class="erp-month-bar erp-month-bar--rev" style="height:${rh}px" title="درآمد"></div>
                    <div class="erp-month-bar erp-month-bar--exp" style="height:${eh}px" title="هزینه"></div>
                </div>
                <span>${this._esc(m.label)}</span>
            </div>`;
        }).join('');

        const expRows = this.expenses.length
            ? this.expenses.slice(0, 30).map(e => {
                const meta = cats[e.category] || { label: e.category, icon: '📋' };
                return `<tr>
                    <td>${meta.icon} ${this._esc(meta.label)}</td>
                    <td>${this._esc(e.title)}</td>
                    <td>${this._esc(e.expense_date)}</td>
                    <td>${this._fmt(e.amount)}</td>
                    <td>${canPost ? `<button class="erp-btn erp-btn--sm erp-btn--ghost" data-del-exp="${e.id}">🗑</button>` : '—'}</td>
                </tr>`;
            }).join('')
            : `<tr><td colspan="5" class="erp-table__empty">هزینه‌ای ثبت نشده</td></tr>`;

        const mz = this.mizajStats;
        const mzRows = (mz.by_type || []).map(r => `<tr><td>${this._esc(r.result_type)}</td><td>${r.cnt}</td></tr>`).join('')
            || `<tr><td colspan="2" class="erp-table__empty">—</td></tr>`;

        const catOpts = Object.entries(cats).map(([k, v]) =>
            `<option value="${k}">${v.icon} ${this._esc(v.label)}</option>`).join('');

        return `
        <div class="erp-page-header">
            <div>
                <h2>💰 مالی گراف — جریان پول</h2>
                <p>درآمد فروشگاه · هزینه‌های ثبت‌شده · سود خالص</p>
            </div>
            ${f.break_even_orders ? `<span class="erp-badge erp-badge--blue">سربه‌سر: ~${f.break_even_orders} سفارش/ماه</span>` : ''}
        </div>

        <div class="erp-card">${flowHtml}</div>

        <div class="erp-grid-2">
            <div class="erp-card">
                <div class="erp-card__header"><div class="erp-card__title">📊 هزینه بر اساس دسته</div></div>
                <div class="erp-card__body" style="padding:16px 20px">${catBars}</div>
            </div>
            <div class="erp-card">
                <div class="erp-card__header"><div class="erp-card__title">📈 ۶ ماه اخیر</div></div>
                <div class="erp-card__body"><div class="erp-month-chart">${monthChart || '—'}</div></div>
            </div>
        </div>

        ${canPost ? `
        <div class="erp-card">
            <div class="erp-card__header"><div class="erp-card__title">➕ ثبت هزینه جدید</div></div>
            <div class="erp-card__body">
                <form id="erp-exp-form" class="erp-inline-form">
                    <select name="category" required>${catOpts}</select>
                    <input name="title" placeholder="عنوان هزینه" required>
                    <input name="amount" type="number" placeholder="مبلغ (تومان)" required min="1">
                    <input name="expense_date" type="date" value="${new Date().toISOString().slice(0,10)}">
                    <input name="notes" placeholder="یادداشت (اختیاری)">
                    <button type="submit" class="erp-btn erp-btn--primary erp-btn--sm">ثبت</button>
                </form>
                <div id="erp-exp-msg" hidden></div>
            </div>
        </div>` : ''}

        <div class="erp-card">
            <div class="erp-card__header"><div class="erp-card__title">📋 لیست هزینه‌ها</div></div>
            <div class="erp-card__body erp-table-wrap">
                <table class="erp-table">
                    <thead><tr><th>دسته</th><th>عنوان</th><th>تاریخ</th><th>مبلغ</th><th></th></tr></thead>
                    <tbody>${expRows}</tbody>
                </table>
            </div>
        </div>

        <div class="erp-card">
            <div class="erp-card__header">
                <div class="erp-card__title">🌿 آمار تست مزاج (${mz.total || 0} نفر)</div>
                <a href="${this._siteUrl()}shop-mizaj.php" class="erp-btn erp-btn--sm">مشاهده تست</a>
            </div>
            <div class="erp-card__body erp-table-wrap">
                <table class="erp-table">
                    <thead><tr><th>مزاج</th><th>تعداد</th></tr></thead>
                    <tbody>${mzRows}</tbody>
                </table>
            </div>
        </div>`;
    }

    /* ─── Accounting ────────────────────────────────────────── */
    _accountingHtml() {
        const canPost = this.role?.is_accountant;
        const rows = this.pending.length
            ? this.pending.map(o => `
            <tr>
                <td><strong>${this._esc(o.order_number)}</strong></td>
                <td>${this._esc(o.billing_name || '')}</td>
                <td>${this._fmt(o.subtotal)}</td>
                <td>${this._payBadge(o.payment_status)}</td>
                <td>${canPost ? `<button class="erp-btn erp-btn--sm erp-btn--primary" data-post="${o.id}">📑 صدور سند</button>` : '—'}</td>
            </tr>`).join('')
            : `<tr><td colspan="5" class="erp-table__empty">✅ صف خالی است — همه اسناد صادر شده</td></tr>`;

        return `
        <div class="erp-page-header">
            <div>
                <h2>📑 حسابداری فروشگاه</h2>
                <p>صدور سند SHOP_SALE پس از پرداخت هر سفارش</p>
            </div>
        </div>

        <div class="erp-card">
            <div class="erp-card__header">
                <div class="erp-card__title">
                    <span class="erp-card__title-icon" style="background:#fef3c7">⏳</span>
                    صف صدور سند
                </div>
                ${this.pending.length ? `<span class="erp-badge erp-badge--amber">${this.pending.length} سفارش در انتظار</span>` : '<span class="erp-badge erp-badge--green">✅ صف خالی</span>'}
            </div>
            <div class="erp-card__body erp-table-wrap">
                <table class="erp-table">
                    <thead><tr><th>شماره سفارش</th><th>مشتری</th><th>مبلغ</th><th>پرداخت</th><th>عملیات</th></tr></thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        </div>

        <div class="erp-card">
            <div class="erp-card__header">
                <div class="erp-card__title">
                    <span class="erp-card__title-icon" style="background:#dcfce7">⚙</span>
                    تنظیمات اتوماسیون
                </div>
                ${canPost ? '<button class="erp-btn erp-btn--primary erp-btn--sm" id="erp-save-config">💾 ذخیره</button>' : ''}
            </div>
            <div class="erp-card__body">
                <div class="erp-toggle-list" style="padding:16px 20px">
                    <label class="erp-toggle">
                        <input type="checkbox" id="erp-auto-ship" ${this.config.auto_ship ? 'checked' : ''}>
                        🚚 ایجاد خودکار محموله پس از پرداخت
                    </label>
                    <label class="erp-toggle">
                        <input type="checkbox" id="erp-auto-crm" ${this.config.auto_crm ? 'checked' : ''}>
                        👥 ثبت خودکار لید CRM برای هر سفارش
                    </label>
                    <label class="erp-toggle">
                        <input type="checkbox" id="erp-auto-stock" ${this.config.auto_issue_stock !== false ? 'checked' : ''}>
                        🏭 خروج انبار هنگام تحویل محموله
                    </label>
                    <label class="erp-toggle">
                        <input type="checkbox" id="erp-check-stock" ${this.config.check_stock !== false ? 'checked' : ''}>
                        ⚠ بررسی موجودی انبار قبل از ثبت سفارش
                    </label>
                </div>
            </div>
        </div>`;
    }

    /* ─── CRM ───────────────────────────────────────────────── */
    _crmHtml() {
        const s   = this.crmSummary;
        const site = this._siteUrl();

        const summaryCards = [
            { label: 'کل مشتریان', value: s.total_leads    || 0, icon: '👥', color: 'blue' },
            { label: 'تبدیل‌شده',   value: s.converted      || 0, icon: '✅', color: 'green' },
            { label: 'فعالیت‌ها',   value: s.activity_count || 0, icon: '💬', color: 'purple' },
        ];

        const rows = this.crmLeads.length
            ? this.crmLeads.map((l, i) => {
                const av  = AVATAR_COLORS[i % AVATAR_COLORS.length];
                const ini = (l.name || 'ع').charAt(0);
                const active = this.selectedLead?.id === l.id;
                return `
                <tr class="erp-lead-row ${active ? 'erp-lead-row--active' : ''}" data-lead="${l.id}">
                    <td>
                        <div style="display:flex;align-items:center;gap:10px">
                            <span class="erp-avatar ${av}">${ini}</span>
                            <div>
                                <div style="font-weight:600;font-size:0.85rem">${this._esc(l.name)}</div>
                                <div style="font-size:0.7rem;color:#64748b" dir="ltr">${this._esc(l.phone || '')}</div>
                            </div>
                        </div>
                    </td>
                    <td>${this._crmBadge(l.status, l.status_label)}</td>
                    <td><span style="font-size:0.78rem;color:#475569">${this._esc(l.order_number || (l.arag_order_id ? '#'+l.arag_order_id : '—'))}</span></td>
                    <td><strong style="color:#0f172a">${l.order_total ? this._fmt(l.order_total) : '—'}</strong></td>
                    <td>
                        <span class="erp-badge erp-badge--blue">${(l.activity_count||0).toLocaleString('fa-IR')} فعالیت</span>
                    </td>
                </tr>`;
            }).join('')
            : `<tr><td colspan="5" class="erp-table__empty">👥 لیدی در CRM ثبت نشده</td></tr>`;

        const detail = this.selectedLead
            ? this._crmDetailHtml(this.selectedLead)
            : `<div class="erp-detail__empty">
                <span class="erp-detail__empty-icon">👆</span>
                روی یک مشتری کلیک کنید تا جزئیات CRM از ERP اصلی نمایش داده شود
               </div>`;

        return `
        <div class="erp-page-header">
            <div>
                <h2>👥 CRM مشتریان فروشگاه</h2>
                <p>اطلاعات مستقیم از جدول CRM اصلی — lead_channel: shop</p>
            </div>
            <div class="erp-page-header__actions">
                <a href="${site}#crm" class="erp-btn erp-btn--primary" target="_blank">🔗 CRM کامل در ERP</a>
            </div>
        </div>

        <div class="erp-stat-grid" style="grid-template-columns:repeat(3,1fr);margin-bottom:20px">
            ${summaryCards.map(c => `
            <div class="erp-stat-card">
                <div class="erp-stat-card__icon erp-stat-card__icon--${c.color}">${c.icon}</div>
                <div>
                    <div class="erp-stat-card__label">${c.label}</div>
                    <div class="erp-stat-card__value">${c.value.toLocaleString('fa-IR')}</div>
                </div>
            </div>`).join('')}
        </div>

        <div class="erp-split">
            <div class="erp-card">
                <div class="erp-card__header">
                    <div class="erp-card__title">
                        <span class="erp-card__title-icon" style="background:#dbeafe">📋</span>
                        لیست مشتریان
                    </div>
                </div>
                <div class="erp-card__body erp-table-wrap">
                    <table class="erp-table erp-table--clickable">
                        <thead><tr><th>مشتری</th><th>وضعیت</th><th>سفارش</th><th>مبلغ</th><th>فعالیت</th></tr></thead>
                        <tbody>${rows}</tbody>
                    </table>
                </div>
            </div>
            <div class="erp-split__side">${detail}</div>
        </div>`;
    }

    _crmDetailHtml(l) {
        const site = this._siteUrl();
        const acts = (l.activities || []).length
            ? l.activities.map(a => `
            <li>
                <span class="erp-timeline__date">${this._esc((a.activity_date || '').slice(0, 16))}</span>
                <strong>${this._esc(a.subject || a.type || 'فعالیت')}</strong>
                <p>${this._esc(a.body || '')}</p>
            </li>`).join('')
            : `<li class="erp-timeline__empty">فعالیتی ثبت نشده</li>`;

        return `
        <div class="erp-detail">
            <div class="erp-detail__head">
                <h4>${this._esc(l.name)}</h4>
                <p>${this._esc(l.phone || '')} · ${this._crmBadge(l.status, l.status_label)}</p>
            </div>
            <div class="erp-detail__body">
                <div class="erp-dl">
                    <div class="erp-dl__row"><span class="erp-dl__label">آدرس</span><span class="erp-dl__value">${this._esc([l.billing_address, l.billing_city].filter(Boolean).join(' — ') || l.address || '—')}</span></div>
                    <div class="erp-dl__row"><span class="erp-dl__label">سفارش</span><span class="erp-dl__value">${this._esc(l.order_number || '—')}</span></div>
                    <div class="erp-dl__row"><span class="erp-dl__label">مبلغ</span><span class="erp-dl__value">${l.order_total ? this._fmt(l.order_total) : '—'}</span></div>
                    <div class="erp-dl__row"><span class="erp-dl__label">امتیاز</span><span class="erp-dl__value">${l.score != null ? l.score : '—'}</span></div>
                </div>
                ${l.notes ? `<div style="background:#fef3c7;border-right:3px solid #f59e0b;padding:10px 12px;border-radius:8px;font-size:0.78rem;color:#78350f;margin-bottom:14px"><strong>یادداشت ERP</strong><br>${this._esc(l.notes)}</div>` : ''}
                <div style="font-weight:700;font-size:0.78rem;color:#374151;margin-bottom:8px">💬 تاریخچه فعالیت‌ها</div>
                <ul class="erp-timeline">${acts}</ul>
                <a href="${this._esc(l.portal_url || site + '#crm')}" class="erp-btn erp-btn--ghost erp-btn--sm" target="_blank" style="margin-top:12px;width:100%;justify-content:center">🔗 باز در CRM پورتال</a>
            </div>
        </div>`;
    }

    /* ─── Shipping ──────────────────────────────────────────── */
    _shippingHtml() {
        const pendingOpts = this.pendingOrders.length
            ? this.pendingOrders.map(o => `<option value="${o.id}">${this._esc(o.order_number)} — ${this._esc(o.billing_name)} (${this._fmt(o.subtotal)})</option>`).join('')
            : '<option value="">— هیچ سفارش بدون محموله‌ای وجود ندارد —</option>';

        const rows = this.shipments.length
            ? this.shipments.map(s => {
                const nxt  = SHIP_NEXT[s.status];
                const done = SHIP_DONE.has(s.status);
                const si   = SHIP_STEPS.find(x => x.key === s.status);
                return `
                <tr>
                    <td><strong>${this._esc(s.shipment_no)}</strong></td>
                    <td>${this._esc(s.recipient_name || '')}</td>
                    <td><span style="font-size:0.78rem;color:#475569">${this._esc(s.order_number || s.ref_no || '')}</span></td>
                    <td>
                        <span class="erp-badge ${done ? 'erp-badge--green' : 'erp-badge--amber'}">
                            ${si ? si.icon : ''} ${this._esc(s.status_label || s.status)}
                        </span>
                    </td>
                    <td>${this._esc(s.method_name || '—')}</td>
                    <td>
                        <input class="erp-track-input" type="text" placeholder="کد رهگیری" value="${this._esc(s.tracking_code || '')}" data-track="${s.id}">
                    </td>
                    <td style="white-space:nowrap">
                        <button class="erp-btn erp-btn--ghost erp-btn--xs" data-save-track="${s.id}" style="margin-left:4px">💾</button>
                        ${nxt
                            ? `<button class="erp-btn erp-btn--primary erp-btn--xs" data-ship="${s.id}" data-next="${nxt}">${this._shipStepLabel(nxt)} →</button>`
                            : (done ? '<span class="erp-badge erp-badge--green">✅ تحویل شد</span>' : '')
                        }
                    </td>
                </tr>`;
            }).join('')
            : `<tr><td colspan="7" class="erp-table__empty">📦 محموله‌ای ثبت نشده</td></tr>`;

        return `
        <div class="erp-page-header">
            <div>
                <h2>🚚 مدیریت حمل‌ونقل</h2>
                <p>ثبت، پیگیری و به‌روزرسانی وضعیت ارسال سفارش‌ها</p>
            </div>
        </div>

        <div class="erp-card" style="margin-bottom:20px">
            <div class="erp-card__header">
                <div class="erp-card__title">
                    <span class="erp-card__title-icon" style="background:#dcfce7">➕</span>
                    ثبت محموله جدید
                </div>
                ${this.pendingOrders.length
                    ? `<span class="erp-badge erp-badge--amber">⏳ ${this.pendingOrders.length} سفارش در انتظار</span>`
                    : '<span class="erp-badge erp-badge--green">✅ همه سفارش‌ها محموله دارند</span>'}
            </div>
            <div class="erp-card__body">
                <form id="erp-ship-form" class="erp-form">
                    <div class="erp-form-grid">
                        <div class="erp-field">
                            <label>📋 سفارش در انتظار محموله</label>
                            <select class="erp-select" name="order_id" ${!this.pendingOrders.length ? 'disabled' : ''}>
                                ${pendingOpts}
                            </select>
                        </div>
                        <div class="erp-field">
                            <label>📍 کد رهگیری (اختیاری)</label>
                            <input class="erp-input" name="tracking_code" type="text" placeholder="مثلاً TPX-123456" dir="ltr">
                        </div>
                        <div class="erp-field erp-field--full">
                            <label>📝 یادداشت انبار / پیک</label>
                            <input class="erp-input" name="notes" type="text" placeholder="توضیح برای تیم ارسال">
                        </div>
                    </div>
                    <div class="erp-form__actions">
                        <button class="erp-btn erp-btn--success" type="submit" ${!this.pendingOrders.length ? 'disabled' : ''}>
                            🚚 ثبت محموله
                        </button>
                        <div id="erp-ship-msg" hidden></div>
                    </div>
                </form>
            </div>
        </div>

        <div class="erp-card">
            <div class="erp-card__header">
                <div class="erp-card__title">
                    <span class="erp-card__title-icon" style="background:#ccfbf1">📋</span>
                    محموله‌های ثبت‌شده
                </div>
                <span class="erp-badge erp-badge--blue">${this.shipments.length} محموله</span>
            </div>
            <div class="erp-card__body erp-table-wrap">
                <table class="erp-table">
                    <thead>
                        <tr>
                            <th>شماره</th><th>گیرنده</th><th>سفارش</th><th>وضعیت</th>
                            <th>روش</th><th>کد رهگیری</th><th>عملیات</th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        </div>`;
    }

    _shipStepLabel(key) {
        return SHIP_STEPS.find(s => s.key === key)?.label || key;
    }

    /* ─── Inventory ─────────────────────────────────────────── */
    _inventoryHtml() {
        const stockRows = this.invStock.length
            ? this.invStock.map(s => `
            <tr>
                <td><code style="font-size:0.75rem;background:#f1f5f9;padding:2px 6px;border-radius:4px">${this._esc(s.code)}</code></td>
                <td>${this._esc(s.name)}</td>
                <td><strong style="color:#0f172a">${(+s.qty||0).toLocaleString('fa-IR')}</strong></td>
                <td>${(+s.avg_cost||0).toLocaleString('fa-IR')} تومان</td>
            </tr>`).join('')
            : `<tr><td colspan="4" class="erp-table__empty">🏭 موجودی ثبت نشده</td></tr>`;

        const vchRows = this.invVouchers.length
            ? this.invVouchers.map(v => `
            <tr>
                <td><strong>${this._esc(v.voucher_no)}</strong></td>
                <td>${this._esc(v.order_number || v.ref_no || '')}</td>
                <td>${this._esc(v.billing_name || '')}</td>
                <td><span class="erp-badge erp-badge--green">✅ ${this._esc(v.status)}</span></td>
            </tr>`).join('')
            : `<tr><td colspan="4" class="erp-table__empty">📄 سند خروجی ثبت نشده</td></tr>`;

        return `
        <div class="erp-page-header">
            <div>
                <h2>🏭 انبار مرکزی</h2>
                <p>موجودی کالا و اسناد خروج فروشگاه (WH-ARAG)</p>
            </div>
        </div>

        <div class="erp-card" style="margin-bottom:20px">
            <div class="erp-card__header">
                <div class="erp-card__title">
                    <span class="erp-card__title-icon" style="background:#ccfbf1">📦</span>
                    موجودی انبار
                </div>
                <span class="erp-badge erp-badge--teal">${this.invStock.length} SKU</span>
            </div>
            <div class="erp-card__body erp-table-wrap">
                <table class="erp-table">
                    <thead><tr><th>کد</th><th>محصول</th><th>موجودی</th><th>بهای تمام‌شده</th></tr></thead>
                    <tbody>${stockRows}</tbody>
                </table>
            </div>
        </div>

        <div class="erp-card">
            <div class="erp-card__header">
                <div class="erp-card__title">
                    <span class="erp-card__title-icon" style="background:#dcfce7">📑</span>
                    اسناد خروج (sale_issue)
                </div>
            </div>
            <div class="erp-card__body erp-table-wrap">
                <table class="erp-table">
                    <thead><tr><th>سند</th><th>سفارش</th><th>مشتری</th><th>وضعیت</th></tr></thead>
                    <tbody>${vchRows}</tbody>
                </table>
            </div>
        </div>`;
    }

    /* ─── Bind events ───────────────────────────────────────── */
    _bind() {
        this.root.querySelectorAll('[data-tab]').forEach(btn => {
            btn.addEventListener('click', async () => {
                this.tab = btn.dataset.tab;
                if (this.tab !== 'crm') this.selectedLead = null;
                await this._loadTab();
                this._paint();
            });
        });

        this.root.querySelectorAll('[data-post]').forEach(btn => {
            btn.addEventListener('click', async () => {
                btn.disabled = true;
                try {
                    await this._post(`/arag/erp/accounting/post/${btn.dataset.post}`, {});
                    await this._loadTab();
                    this._paint();
                } catch (e) { alert(e.message); btn.disabled = false; }
            });
        });

        this.root.querySelectorAll('[data-ship]').forEach(btn => {
            btn.addEventListener('click', async () => {
                btn.disabled = true;
                try {
                    await this._post(`/arag/erp/shipping/${btn.dataset.ship}/advance`, { status: btn.dataset.next });
                    await this._loadTab();
                    this._paint();
                } catch (e) { alert(e.message); btn.disabled = false; }
            });
        });

        this.root.querySelectorAll('[data-save-track]').forEach(btn => {
            btn.addEventListener('click', async () => {
                const id  = btn.dataset.saveTrack;
                const inp = this.root.querySelector(`[data-track="${id}"]`);
                try {
                    await this._post(`/arag/erp/shipping/${id}/patch`, { tracking_code: inp?.value?.trim() || '' });
                    btn.textContent = '✅';
                    setTimeout(() => { btn.textContent = '💾'; }, 1500);
                } catch (e) { alert(e.message); }
            });
        });

        this.root.querySelector('#erp-ship-form')?.addEventListener('submit', async e => {
            e.preventDefault();
            const msg      = this.root.querySelector('#erp-ship-msg');
            const fd       = new FormData(e.target);
            const order_id = +(fd.get('order_id') || 0);
            if (!order_id) return;
            const btn = e.target.querySelector('[type="submit"]');
            btn.disabled = true;
            try {
                const res = await this._post('/arag/erp/shipping/create', {
                    order_id,
                    tracking_code: fd.get('tracking_code')?.trim() || '',
                    notes: fd.get('notes')?.trim() || '',
                });
                if (msg) {
                    msg.hidden = false;
                    msg.className = 'erp-msg erp-msg--ok';
                    msg.textContent = res.message || `✅ محموله ${res.shipment_no || ''} ثبت شد`;
                }
                await this._loadTab();
                this._paint();
            } catch (err) {
                if (msg) { msg.hidden = false; msg.className = 'erp-msg erp-msg--err'; msg.textContent = err.message; }
                btn.disabled = false;
            }
        });

        this.root.querySelectorAll('[data-lead]').forEach(row => {
            row.addEventListener('click', async () => {
                const id = +row.dataset.lead;
                try {
                    const d = await this._get(`/arag/erp/crm/leads/${id}`);
                    this.selectedLead = d.data || null;
                    this._paint();
                } catch (e) { alert(e.message); }
            });
        });

        this.root.querySelector('#erp-save-config')?.addEventListener('click', async () => {
            await this._put('/arag/erp/accounting/config', {
                ...this.config,
                auto_ship:       !!this.root.querySelector('#erp-auto-ship')?.checked,
                auto_crm:        !!this.root.querySelector('#erp-auto-crm')?.checked,
                auto_issue_stock: !!this.root.querySelector('#erp-auto-stock')?.checked,
                check_stock:     !!this.root.querySelector('#erp-check-stock')?.checked,
            });
            alert('✅ تنظیمات ذخیره شد');
        });

        this.root.querySelector('#erp-exp-form')?.addEventListener('submit', async e => {
            e.preventDefault();
            const msg = this.root.querySelector('#erp-exp-msg');
            const fd = new FormData(e.target);
            try {
                await this._post('/arag/erp/expenses', {
                    category: fd.get('category'),
                    title: fd.get('title'),
                    amount: +(fd.get('amount') || 0),
                    expense_date: fd.get('expense_date'),
                    notes: fd.get('notes') || '',
                });
                if (msg) { msg.hidden = false; msg.className = 'erp-msg erp-msg--ok'; msg.textContent = 'هزینه ثبت شد'; }
                e.target.reset();
                await this._loadTab();
                this._paint();
            } catch (err) {
                if (msg) { msg.hidden = false; msg.className = 'erp-msg erp-msg--err'; msg.textContent = err.message; }
            }
        });

        this.root.querySelectorAll('[data-del-exp]').forEach(btn => {
            btn.addEventListener('click', async () => {
                if (!confirm('حذف این هزینه؟')) return;
                try {
                    await fetch(this._api() + `/arag/erp/expenses/${btn.dataset.delExp}`, {
                        method: 'DELETE',
                        headers: { Authorization: `Bearer ${this.token}` },
                    });
                    await this._loadTab();
                    this._paint();
                } catch (e) { alert(e.message); }
            });
        });
    }

    /* ─── Helpers ───────────────────────────────────────────── */
    _payBadge(status) {
        const map = {
            paid: ['green', '✅ پرداخت شد'], cod: ['amber', '💵 COD'], pending: ['gray', '⏳ در انتظار'],
            failed: ['red', '❌ ناموفق'],
        };
        const [c, l] = map[status] || ['gray', status];
        return `<span class="erp-badge erp-badge--${c}">${l}</span>`;
    }
    _statusBadge(status) {
        const map = {
            completed: ['green', '✅ تکمیل'], processing: ['blue', '⚙ در پردازش'],
            pending: ['amber', '⏳ در انتظار'], cancelled: ['red', '❌ لغو'],
        };
        const [c, l] = map[status] || ['gray', status];
        return `<span class="erp-badge erp-badge--${c}">${l}</span>`;
    }
    _crmBadge(status, label) {
        return `<span class="erp-badge ${CRM_BADGE[status] || 'erp-badge--gray'}">${this._esc(label || status)}</span>`;
    }

    _fmt(n)   { return (+n || 0).toLocaleString('fa-IR') + ' تومان'; }
    _esc(s)   { return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
    _api()    { return (window.ACC_SHOP_CFG?.api || '/acc-engine/api.php/acc/v1').replace(/\/$/,''); }
    _siteUrl(){ const b = window.ACC_SHOP_CFG?.baseUrl || '/acc-engine/'; return b.endsWith('/') ? b : b+'/'; }

    async _get(path) {
        const r = await fetch(this._api() + path, { headers: this._headers() });
        const j = await r.json();
        if (!r.ok) throw new Error(j.message || 'خطا');
        return j;
    }
    async _post(path, body) {
        const r = await fetch(this._api() + path, { method:'POST', headers: this._headers(), body: JSON.stringify(body) });
        const j = await r.json();
        if (!r.ok) throw new Error(j.message || 'خطا');
        return j;
    }
    async _put(path, body) {
        const r = await fetch(this._api() + path, { method:'PUT', headers: this._headers(), body: JSON.stringify(body) });
        const j = await r.json();
        if (!r.ok) throw new Error(j.message || 'خطا');
        return j;
    }
    _headers() {
        const h = { 'Content-Type': 'application/json' };
        if (this.token) h.Authorization = 'Bearer ' + this.token;
        return h;
    }
}
