@props([
    'col' => 12,
    'lang',
    'id' => null,
    'label' => null,
    'name' => null,
    'max' => 255,
    'value' => null,
    'required' => false
])

@php
    $textName = app()->getLocale() == 'en'
        ? $lang->name .' ' . $label
        : $label . ' ب' . $lang->name;

    $textareaId = $id ? $id . '_' . $lang->code : $name . '_' . $lang->code;
@endphp

<div class="row">
    <div class="col-md-{{ $col }} mb-3">

        <label class="form-label">
            {{ $textName }}
            <span class="text-danger">
                {{ $required && $lang->code === 'en' ? '*' : '' }}
            </span>
        </label>

        <textarea
            name="{{ $name }}[{{ $lang->code }}]"
            id="{{ $textareaId }}"
            class="form-control trans-input btn-square"
            data-lang="{{ $lang->code }}"
            rows="3"
            maxlength="{{ $max ?? 255 }}"
            placeholder="{{ __('dashboard.enter_your', ['attribute'=>  $textName]) }}"
            data-max="{{ $max ?? 255 }}"
        >{{ old($name . '.' . $lang->code, $value ? $value?->getTranslation($name, $lang->code, false) : '') }}</textarea>

        {{-- Counter --}}
        <div class="char-counter mt-1 text-end" style="font-size: 0.85rem; color: #6c757d;">
            <span class="char-count" data-textarea-id="{{ $textareaId }}">0</span>
            / <span class="char-max">{{ $max ?? 255 }}</span>
        </div>

        <div class="invalid-feedback"></div>

        @foreach($errors->get($name . '.' . $lang->code) as $message)
            <span class="text-danger"><small class="errorTxt">{{ $message }}</small></span>
        @endforeach
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const textareas = document.querySelectorAll('.trans-input');

    textareas.forEach(textarea => {
        const textareaId = textarea.id;
        const charCount = document.querySelector(`[data-textarea-id="${textareaId}"]`);

        if (charCount) {
            // تحديث العداد عند التحميل
            charCount.textContent = textarea.value.length;

            // تحديث العداد عند الكتابة أو التغيير
            textarea.addEventListener('input', () => charCount.textContent = textarea.value.length);
            textarea.addEventListener('change', () => charCount.textContent = textarea.value.length);
        }
    });
});
</script>
