import { Controller } from '@hotwired/stimulus';

/**
 * Slug Generator Stimulus Controller
 *
 * Watches the title input and auto-generates a URL-friendly slug.
 * Handles Turkish character transliteration and provides a lock toggle
 * to prevent further auto-updates.
 *
 * Targets:
 *   title    - The news title input field
 *   slug     - The slug input field
 *   lockBtn  - The lock/unlock toggle button
 */
export default class extends Controller {
    static targets = ['title', 'slug', 'lockBtn'];

    connect() {
        this._locked = false;
        this._lastAutoSlug = '';

        this._boundOnTitleInput = this._onTitleInput.bind(this);

        if (this.hasTitleTarget) {
            this.titleTarget.addEventListener('input', this._boundOnTitleInput);
        }

        // If slug already has a value on connect, record it so we know
        // whether the user has manually changed it.
        if (this.hasSlugTarget && this.slugTarget.value.trim()) {
            this._lastAutoSlug = this.slugTarget.value.trim();
        }

        this._updateLockButton();
    }

    disconnect() {
        if (this.hasTitleTarget) {
            this.titleTarget.removeEventListener('input', this._boundOnTitleInput);
        }
    }

    // ---------------------------------------------------------------
    // Actions (can be called via data-action)
    // ---------------------------------------------------------------

    /**
     * Toggle lock state. Wire this to the lock button:
     * data-action="slug-generator#toggleLock"
     */
    toggleLock() {
        this._locked = !this._locked;
        this._updateLockButton();
    }

    // ---------------------------------------------------------------
    // Internal
    // ---------------------------------------------------------------

    _onTitleInput() {
        if (this._locked) return;
        if (!this.hasSlugTarget) return;

        const currentSlug = this.slugTarget.value.trim();

        // Only auto-generate if the slug field is empty or still matches
        // the last value we auto-generated (user hasn't manually edited it).
        if (currentSlug !== '' && currentSlug !== this._lastAutoSlug) {
            return;
        }

        const title = this.hasTitleTarget ? this.titleTarget.value : '';
        const slug = this._generateSlug(title);

        this.slugTarget.value = slug;
        this._lastAutoSlug = slug;

        // Dispatch an input event so other controllers (e.g. seo-analyzer)
        // pick up the change.
        this.slugTarget.dispatchEvent(new Event('input', { bubbles: true }));
    }

    /**
     * Converts a string to a URL-friendly slug.
     * Handles Turkish characters, lowercases, strips specials,
     * collapses hyphens.
     */
    _generateSlug(text) {
        if (!text) return '';

        let slug = text;

        // Turkish character map
        const turkishMap = {
            '\u00E7': 'c',  // c with cedilla
            '\u00C7': 'c',  // C with cedilla
            '\u011F': 'g',  // g with breve
            '\u011E': 'g',  // G with breve
            '\u0131': 'i',  // dotless i
            '\u0130': 'i',  // I with dot above
            '\u00F6': 'o',  // o with diaeresis
            '\u00D6': 'o',  // O with diaeresis
            '\u015F': 's',  // s with cedilla
            '\u015E': 's',  // S with cedilla
            '\u00FC': 'u',  // u with diaeresis
            '\u00DC': 'u',  // U with diaeresis
        };

        // Replace Turkish characters
        slug = slug.replace(/[^\u0000-\u007F]/g, (char) => {
            return turkishMap[char] || char;
        });

        // Lowercase
        slug = slug.toLowerCase();

        // Replace spaces and underscores with hyphens
        slug = slug.replace(/[\s_]+/g, '-');

        // Remove all characters that are not alphanumeric or hyphens
        slug = slug.replace(/[^a-z0-9-]/g, '');

        // Collapse consecutive hyphens into one
        slug = slug.replace(/-+/g, '-');

        // Trim leading/trailing hyphens
        slug = slug.replace(/^-+|-+$/g, '');

        return slug;
    }

    _updateLockButton() {
        if (!this.hasLockBtnTarget) return;

        if (this._locked) {
            this.lockBtnTarget.innerHTML = '<i class="fas fa-lock"></i>';
            this.lockBtnTarget.title = 'Slug kilitli - degistirmek icin tiklayin';
            this.lockBtnTarget.classList.add('btn-warning');
            this.lockBtnTarget.classList.remove('btn-outline-secondary');
        } else {
            this.lockBtnTarget.innerHTML = '<i class="fas fa-lock-open"></i>';
            this.lockBtnTarget.title = 'Slug otomatik - kilitlemek icin tiklayin';
            this.lockBtnTarget.classList.remove('btn-warning');
            this.lockBtnTarget.classList.add('btn-outline-secondary');
        }
    }
}
