import { madarApi, unwrap } from './madar-api.js';

const limits = window.MADAR_TEXT_LIMITS || {};
const unlimited = limits.unlimited === true;
const maxWords = unlimited ? null : (limits.max_words ?? 500);
const warningRatio = limits.warning_ratio ?? 0.85;
const RING_CIRC = 2 * Math.PI * 52;

const $ = (id) => document.getElementById(id);

const input = $('ta-input');
const countEl = $('ta-word-count');
const countWrap = $('ta-word-counter');
const submitBtn = $('ta-submit');
const humanizeBtn = $('ta-humanize-only');
const upgradeBtn = $('ta-upgrade-cta');
const results = $('ta-results');
const empty = $('ta-empty');
const loading = $('ta-loading');
const errorEl = $('ta-error');
const toast = $('ta-toast');

let lastPayload = null;
let activeTab = 'original';

export function countWords(text) {
    const normalized = text.trim().replace(/\s+/g, ' ');
    if (!normalized) return 0;
    const m = normalized.match(/[\p{Script=Arabic}\p{L}\p{N}][\p{Script=Arabic}\p{L}\p{N}'-]*/gu);
    return m ? m.length : 0;
}

function showToast(msg = 'تم نسخ النص بنجاح') {
    if (!toast) return;
    toast.textContent = msg;
    toast.classList.remove('hidden');
    toast.classList.add('ta-toast--show');
    setTimeout(() => {
        toast.classList.remove('ta-toast--show');
        toast.classList.add('hidden');
    }, 2400);
}

function setRing(circleEl, valueEl, percent) {
    if (!circleEl) return;
    const p = Math.max(0, Math.min(100, percent ?? 0));
    circleEl.style.strokeDasharray = `${RING_CIRC}`;
    circleEl.style.strokeDashoffset = `${RING_CIRC * (1 - p / 100)}`;
    if (valueEl) valueEl.textContent = percent != null ? `${p}%` : '—';
}

function setBar(barEl, valueEl, percent) {
    const p = Math.max(0, Math.min(100, percent ?? 0));
    if (barEl) barEl.style.width = `${p}%`;
    if (valueEl) valueEl.textContent = percent != null ? `${p}%` : '—';
}

function escapeHtml(s) {
    return String(s)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

function paneText(original, humanized, locked) {
    const h = locked ? humanized : humanized;
    return { original: escapeHtml(original), humanized: escapeHtml(h) };
}

function fillPanes(originalText, humanDisplay, locked) {
    const ids = [
        'ta-pane-original',
        'ta-pane-humanized',
        'ta-pane-original-desktop',
        'ta-pane-humanized-desktop',
        'ta-compare-before',
        'ta-compare-after',
    ];
    const map = {
        'ta-pane-original': originalText,
        'ta-pane-original-desktop': originalText,
        'ta-compare-before': originalText,
        'ta-pane-humanized': humanDisplay,
        'ta-pane-humanized-desktop': humanDisplay,
        'ta-compare-after': humanDisplay,
    };
    ids.forEach((id) => {
        const el = $(id);
        if (!el) return;
        const t = map[id] || '';
        el.textContent = t || '—';
        if (locked && id.includes('humanized')) {
            el.classList.add('ta-text-pane--locked');
        } else {
            el.classList.remove('ta-text-pane--locked');
        }
    });
}

function setTab(tab) {
    activeTab = tab;
    document.querySelectorAll('.ta-tab').forEach((btn) => {
        btn.classList.toggle('ta-tab--active', btn.dataset.tab === tab);
    });
    const panes = {
        original: $('ta-pane-original'),
        humanized: $('ta-pane-humanized'),
        compare: $('ta-pane-compare'),
    };
    Object.entries(panes).forEach(([key, el]) => {
        if (!el) return;
        el.classList.toggle('hidden', key !== tab);
    });
}

function updateCounter() {
    const words = countWords(input?.value || '');
    if (unlimited) {
        countEl.textContent = `${words} كلمة · غير محدود`;
        countWrap?.classList.remove('text-amber-400', 'text-red-400');
        countWrap?.classList.add('text-zinc-500');
        const disabled = words < 5;
        submitBtn.disabled = disabled;
        if (humanizeBtn) humanizeBtn.disabled = disabled;
        upgradeBtn?.classList.add('hidden');
        return;
    }

    countEl.textContent = `${words} / ${maxWords} كلمة`;
    const over = words > maxWords;
    const warn = !over && words >= Math.floor(maxWords * warningRatio);

    countWrap?.classList.toggle('text-red-400', over);
    countWrap?.classList.toggle('text-amber-400', warn && !over);
    countWrap?.classList.toggle('text-zinc-500', !over && !warn);

    const disabled = over || words < 5;
    submitBtn.disabled = disabled;
    if (humanizeBtn) humanizeBtn.disabled = disabled;
    upgradeBtn?.classList.toggle('hidden', !over);
}

function showError(msg) {
    if (!errorEl) return;
    errorEl.textContent = msg;
    errorEl.classList.remove('hidden');
}

function clearError() {
    errorEl?.classList.add('hidden');
    if (errorEl) errorEl.textContent = '';
}

function setLoading(on) {
    loading?.classList.toggle('hidden', !on);
    empty?.classList.toggle('hidden', on || !!lastPayload);
    if (on) results?.classList.add('hidden');
}

function renderResult(p) {
    lastPayload = p;
    clearError();
    results?.classList.remove('hidden');
    empty?.classList.add('hidden');

    const note = $('ta-scores-note');
    if (note) note.textContent = p.scores_note || 'مؤشرات أسلوبية تقديرية وليست حكماً قطعياً';

    setRing($('ta-ring-human'), $('ta-human-score'), p.human_score);
    setRing($('ta-ring-ai'), $('ta-ai-score'), p.ai_probability_score);
    setBar($('ta-read-bar'), $('ta-read-score'), p.readability_score);

    const tone = $('ta-tone');
    if (tone) tone.textContent = p.tone || '—';

    const analysis = $('ta-analysis');
    if (analysis) analysis.textContent = p.analysis || '';

    const weak = $('ta-weak');
    if (weak) {
        const items = p.weak_points || [];
        weak.innerHTML = items.length
            ? items.map((w) => `<li class="ta-weak-item">${escapeHtml(w)}</li>`).join('')
            : '<li class="text-zinc-500">لا توجد نقاط ضعف بارزة</li>';
    }

    const humanDisplay = p.humanized_locked ? (p.humanized_preview || '') : (p.humanized_text || '');
    fillPanes(input?.value || '', humanDisplay, p.humanized_locked);

    const upgradeBox = $('ta-humanized-upgrade');
    const copyUpgrade = $('ta-copy-upgrade');
    if (p.humanized_locked) {
        upgradeBox?.classList.remove('hidden');
        if (upgradeBox) {
            const pricing = window.MADAR_PRICING_URL || '/pricing';
            upgradeBox.innerHTML = `${escapeHtml(p.copy_upgrade_message || 'النص المحسّن أطول من حد خطتك.')} <a href="${pricing}" class="font-bold underline">ترقية الخطة</a>`;
        }
        copyUpgrade?.classList.remove('hidden');
    } else {
        upgradeBox?.classList.add('hidden');
        copyUpgrade?.classList.add('hidden');
    }

    const recs = $('ta-recs');
    if (recs) {
        const items = p.recommendations || [];
        recs.innerHTML = items.length
            ? items.map((r) => `<li>${escapeHtml(r)}</li>`).join('')
            : '<li>—</li>';
    }

    const saveBtn = $('ta-save');
    if (saveBtn && p.id) {
        saveBtn.disabled = true;
        saveBtn.textContent = `تم الحفظ #${p.id}`;
    }
}

async function analyze() {
    const text = input?.value?.trim() || '';
    const words = countWords(text);
    if (words < 5) {
        showError('أدخل فقرة أو أكثر (5 كلمات على الأقل).');
        return;
    }
    if (!unlimited && words > maxWords) {
        showError(limits.upgrade_message || 'تجاوزت حد الكلمات في خطتك.');
        return;
    }

    clearError();
    setLoading(true);
    submitBtn.disabled = true;
    if (humanizeBtn) humanizeBtn.disabled = true;

    try {
        const { data } = await madarApi.post('/tools/text-analysis', {
            text,
            mode: 'analyze_and_humanize',
        });
        renderResult(unwrap(data));
        setTab('humanized');
    } catch (err) {
        const msg = err.response?.data?.message || err.madarMessage || 'تعذر تحليل النص. حاول مرة أخرى.';
        showError(msg);
        if (err.response?.data?.data?.code === 'text_word_limit_exceeded') {
            upgradeBtn?.classList.remove('hidden');
        }
    } finally {
        setLoading(false);
        updateCounter();
    }
}

input?.addEventListener('input', () => {
    updateCounter();
    if (!lastPayload) empty?.classList.remove('hidden');
});

updateCounter();

$('ta-paste')?.addEventListener('click', async () => {
    try {
        const t = await navigator.clipboard.readText();
        if (input) input.value = t;
        updateCounter();
    } catch {
        showError('تعذر اللصق من الحافظة.');
    }
});

$('ta-clear')?.addEventListener('click', () => {
    if (input) input.value = '';
    lastPayload = null;
    results?.classList.add('hidden');
    empty?.classList.remove('hidden');
    clearError();
    updateCounter();
});

$('ta-copy-original')?.addEventListener('click', () => {
    const t = input?.value || '';
    if (!t.trim()) return;
    navigator.clipboard.writeText(t);
    showToast('تم نسخ النص بنجاح');
});

submitBtn?.addEventListener('click', analyze);
humanizeBtn?.addEventListener('click', analyze);
$('ta-retry')?.addEventListener('click', analyze);

$('ta-copy')?.addEventListener('click', () => {
    if (!lastPayload) return;
    if (!lastPayload.can_copy_full || lastPayload.humanized_locked) {
        $('ta-copy-upgrade')?.classList.remove('hidden');
        showError(lastPayload.copy_upgrade_message || 'ترقية الخطة للنسخ الكامل.');
        return;
    }
    navigator.clipboard.writeText(lastPayload.humanized_text || '');
    showToast('تم نسخ النص بنجاح');
});

$('ta-replace')?.addEventListener('click', () => {
    if (!lastPayload) return;
    if (!lastPayload.can_copy_full || lastPayload.humanized_locked) {
        $('ta-copy-upgrade')?.classList.remove('hidden');
        return;
    }
    if (input) input.value = lastPayload.humanized_text || '';
    updateCounter();
    fillPanes(input.value, lastPayload.humanized_text || '', false);
    showToast('تم استبدال النص الأصلي');
});

document.querySelectorAll('.ta-tab').forEach((btn) => {
    btn.addEventListener('click', () => setTab(btn.dataset.tab || 'original'));
});

// Init rings
[$('ta-ring-human'), $('ta-ring-ai')].forEach((c) => {
    if (c) {
        c.style.strokeDasharray = `${RING_CIRC}`;
        c.style.strokeDashoffset = `${RING_CIRC}`;
    }
});
