<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/Forum/Create.vue
//  Location: resources/js/Pages/Member/Forum/Create.vue
//
//  Create a new Ask Members 4 Opinion post.
//
//  Fields:
//    - Hub selector (Finance / Marketing / Sales)
//    - Title (10–200 chars)
//    - Body (30+ chars — markdown supported)
//    - Language (EN / AR)
//    - Visibility (all members / hub only)
//    - Nickname toggle (default ON — privacy first)
//    - Tags (optional, max 5)
//
//  Rules:
//    - Submits via Inertia router.post to member.forum.store
//    - Validation errors shown inline below each field
//    - Both themes, bilingual inline, RTL safe
// ══════════════════════════════════════════════════════════════════

import { ref, computed }      from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import { useAuthStore }       from '@/Stores/useAuthStore';
import AppLayout              from '@/Layouts/AppLayout.vue';

const props = defineProps({
    allHubs: { type: Array, default: () => [] },
    errors:  { type: Object, default: () => ({}) },
});

const authStore = useAuthStore();
const locale    = computed(() => authStore.locale);

// ── Form state ────────────────────────────────────────────────────
const form = ref({
    hub_id:             props.allHubs[0]?.id ?? null,
    title:              '',
    body:               '',
    language:           locale.value === 'ar' ? 'ar' : 'en',
    visibility:         'all',
    posted_as_nickname: true,
    tags:               [],
});

const tagInput   = ref('');
const isPosting  = ref(false);

// ── Tag management ────────────────────────────────────────────────
function addTag() {
    const t = tagInput.value.trim();
    if (t && form.value.tags.length < 5 && !form.value.tags.includes(t)) {
        form.value.tags.push(t);
    }
    tagInput.value = '';
}

function removeTag(tag) {
    form.value.tags = form.value.tags.filter(t => t !== tag);
}

function handleTagKeydown(e) {
    if (e.key === 'Enter' || e.key === ',') {
        e.preventDefault();
        addTag();
    }
}

// ── Submit ────────────────────────────────────────────────────────
function submit() {
    if (isPosting.value) return;
    isPosting.value = true;

    router.post(route('member.forum.store'), form.value, {
        onError:  () => { isPosting.value = false; },
        onFinish: () => { isPosting.value = false; },
    });
}

// ── Char count ────────────────────────────────────────────────────
const titleLen = computed(() => form.value.title.length);
const bodyLen  = computed(() => form.value.body.length);

// ── Hub helpers ───────────────────────────────────────────────────
function hubName(hub) {
    return locale.value === 'ar' ? hub.name_ar : hub.name_en;
}
</script>

<template>
    <AppLayout :title="locale === 'ar' ? 'اطرح سؤالاً' : 'Ask a Question'">
        <Head :title="locale === 'ar' ? 'اطرح سؤالاً' : 'Ask a Question'" />

        <div class="create-page">

            <!-- Header -->
            <div class="create-header">
                <Link :href="route('member.forum.index')" class="back-link">
                    <i class="ti ti-arrow-left" aria-hidden="true"></i>
                    {{ locale === 'ar' ? 'العودة' : 'Back' }}
                </Link>
                <h1 class="create-title">
                    {{ locale === 'ar' ? 'اطرح سؤالاً على الأعضاء' : 'Ask Members 4 Opinion' }}
                </h1>
                <p class="create-sub">
                    {{ locale === 'ar'
                        ? 'صف المشكلة التي تواجهها في العمل — احصل على آراء حقيقية من محترفين حقيقيين'
                        : 'Describe a real work problem — get genuine advice from professionals who have been there.' }}
                </p>
            </div>

            <!-- Form card -->
            <div class="form-card">

                <!-- Hub selector -->
                <div class="field">
                    <label class="field-label">
                        {{ locale === 'ar' ? 'الهاب' : 'Hub' }}
                        <span class="required">*</span>
                    </label>
                    <div class="hub-selector">
                        <button
                            v-for="hub in allHubs"
                            :key="hub.id"
                            type="button"
                            class="hub-option"
                            :class="{ 'hub-option--active': form.hub_id === hub.id }"
                            :style="`--hub-color:${hub.color}`"
                            @click="form.hub_id = hub.id">
                            <i :class="`ti ti-${hub.icon ?? 'chart-bar'}`" aria-hidden="true"></i>
                            {{ hubName(hub) }}
                        </button>
                    </div>
                    <p v-if="errors.hub_id" class="field-error">{{ errors.hub_id }}</p>
                </div>

                <!-- Title -->
                <div class="field">
                    <label class="field-label">
                        {{ locale === 'ar' ? 'عنوان السؤال' : 'Question Title' }}
                        <span class="required">*</span>
                    </label>
                    <input
                        v-model="form.title"
                        class="field-input"
                        type="text"
                        :placeholder="locale === 'ar'
                            ? 'مثال: كيف أتعامل مع عميل رئيسي يتأخر في الدفع؟'
                            : 'e.g. How do I handle a major client who keeps delaying payment?'"
                        maxlength="200"
                    />
                    <div class="field-foot">
                        <p v-if="errors.title" class="field-error">{{ errors.title }}</p>
                        <span class="char-count" :class="{ 'char-count--warn': titleLen > 180 }">
                            {{ titleLen }}/200
                        </span>
                    </div>
                </div>

                <!-- Body -->
                <div class="field">
                    <label class="field-label">
                        {{ locale === 'ar' ? 'تفاصيل المشكلة' : 'Problem Details' }}
                        <span class="required">*</span>
                    </label>
                    <p class="field-hint">
                        {{ locale === 'ar'
                            ? 'اشرح السياق، ما جربته، وما تحتاج مساعدة فيه.'
                            : 'Explain the context, what you have tried, and exactly where you are stuck.' }}
                    </p>
                    <textarea
                        v-model="form.body"
                        class="field-textarea"
                        :placeholder="locale === 'ar'
                            ? 'اكتب التفاصيل هنا...'
                            : 'Write the details here...'"
                        rows="8"
                    ></textarea>
                    <div class="field-foot">
                        <p v-if="errors.body" class="field-error">{{ errors.body }}</p>
                        <span class="char-count" :class="{ 'char-count--ok': bodyLen >= 30 }">
                            {{ bodyLen }} {{ locale === 'ar' ? 'حرف' : 'chars' }}
                            <span v-if="bodyLen < 30" class="char-min">
                                ({{ locale === 'ar' ? 'الحد الأدنى 30' : 'min 30' }})
                            </span>
                        </span>
                    </div>
                </div>

                <!-- Tags -->
                <div class="field">
                    <label class="field-label">
                        {{ locale === 'ar' ? 'الوسوم (اختياري)' : 'Tags (optional)' }}
                    </label>
                    <p class="field-hint">
                        {{ locale === 'ar' ? 'أضف وسوماً تصف الموضوع — مثال: ميزانية، عميل، فريق' : 'Add tags to help others find your post — e.g. budget, client, team' }}
                    </p>
                    <div class="tag-input-wrap">
                        <div class="tag-chips">
                            <span v-for="tag in form.tags" :key="tag" class="tag-chip">
                                {{ tag }}
                                <button type="button" class="tag-remove" @click="removeTag(tag)">×</button>
                            </span>
                        </div>
                        <input
                            v-if="form.tags.length < 5"
                            v-model="tagInput"
                            class="tag-input"
                            type="text"
                            :placeholder="locale === 'ar' ? 'اكتب وسماً واضغط Enter...' : 'Type a tag and press Enter...'"
                            @keydown="handleTagKeydown"
                            @blur="addTag"
                        />
                    </div>
                </div>

                <!-- Options row -->
                <div class="options-row">

                    <!-- Language -->
                    <div class="option-field">
                        <label class="field-label">{{ locale === 'ar' ? 'لغة المنشور' : 'Post Language' }}</label>
                        <div class="toggle-group">
                            <button type="button"
                                    class="toggle-btn"
                                    :class="{ 'toggle-btn--active': form.language === 'en' }"
                                    @click="form.language = 'en'">EN</button>
                            <button type="button"
                                    class="toggle-btn"
                                    :class="{ 'toggle-btn--active': form.language === 'ar' }"
                                    @click="form.language = 'ar'">AR</button>
                        </div>
                    </div>

                    <!-- Visibility -->
                    <div class="option-field">
                        <label class="field-label">{{ locale === 'ar' ? 'من يرى المنشور؟' : 'Visibility' }}</label>
                        <div class="toggle-group">
                            <button type="button"
                                    class="toggle-btn"
                                    :class="{ 'toggle-btn--active': form.visibility === 'all' }"
                                    @click="form.visibility = 'all'">
                                <i class="ti ti-world" aria-hidden="true"></i>
                                {{ locale === 'ar' ? 'الجميع' : 'All Members' }}
                            </button>
                            <button type="button"
                                    class="toggle-btn"
                                    :class="{ 'toggle-btn--active': form.visibility === 'hub' }"
                                    @click="form.visibility = 'hub'">
                                <i class="ti ti-lock" aria-hidden="true"></i>
                                {{ locale === 'ar' ? 'هابي فقط' : 'Hub Only' }}
                            </button>
                        </div>
                    </div>

                    <!-- Nickname toggle -->
                    <div class="option-field">
                        <label class="field-label">{{ locale === 'ar' ? 'الخصوصية' : 'Privacy' }}</label>
                        <label class="nick-toggle">
                            <input type="checkbox" v-model="form.posted_as_nickname" />
                            <span>
                                {{ form.posted_as_nickname
                                    ? (locale === 'ar' ? 'النشر بالاسم المستعار ✓' : 'Posting as nickname ✓')
                                    : (locale === 'ar' ? 'النشر بالاسم الحقيقي' : 'Posting as real name') }}
                            </span>
                        </label>
                    </div>

                </div>

                <!-- Submit row -->
                <div class="submit-row">
                    <Link :href="route('member.forum.index')" class="cancel-link">
                        {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                    </Link>
                    <button type="button"
                            class="post-btn"
                            :disabled="isPosting"
                            @click="submit">
                        <i class="ti ti-send" aria-hidden="true"></i>
                        {{ isPosting
                            ? (locale === 'ar' ? 'جارٍ النشر...' : 'Posting...')
                            : (locale === 'ar' ? 'انشر السؤال' : 'Post Question') }}
                    </button>
                </div>

            </div>

        </div>
    </AppLayout>
</template>

<style scoped>
.create-page {
    display: flex; flex-direction: column; gap: 12px;
    padding: 12px 12px 80px;
    max-width: 1250px; margin: 0 auto; width: 100%;
}

/* ── Header ──────────────────────────────────────────────────── */
.back-link {
    display: inline-flex; align-items: center; gap: 4px;
    font-size: 11px; color: var(--color-text-muted); text-decoration: none;
    margin-bottom: 4px; transition: color var(--transition-fast);
}
.back-link:hover { color: var(--color-primary); }
.create-header { display: flex; flex-direction: column; gap: 4px; }
.create-title {
    font-size: 18px; font-weight: 800; color: var(--color-text-primary); margin: 0;
}
.create-sub { font-size: 12px; color: var(--color-text-muted); margin: 0; line-height: 1.5; }

/* ── Form card ───────────────────────────────────────────────── */
.form-card {
    background: var(--color-surface);
    border: 0.5px solid var(--color-border);
    border-radius: var(--radius-lg); padding: 18px 16px;
    display: flex; flex-direction: column; gap: 16px;
}

/* ── Fields ──────────────────────────────────────────────────── */
.field { display: flex; flex-direction: column; gap: 6px; }
.field-label {
    font-size: 11px; font-weight: 700; color: var(--color-text-secondary);
    text-transform: uppercase; letter-spacing: 0.05em;
}
.required { color: #dc2626; margin-left: 2px; }
.field-hint { font-size: 11px; color: var(--color-text-muted); margin: 0; line-height: 1.5; }
.field-foot { display: flex; justify-content: space-between; align-items: center; }
.field-error { font-size: 11px; color: #dc2626; margin: 0; }

.field-input, .field-textarea {
    width: 100%; padding: 9px 12px; font-size: 13px;
    background: var(--color-surface-alt); border: 1px solid var(--color-border);
    border-radius: var(--radius-sm); color: var(--color-text-primary);
    outline: none; transition: border-color var(--transition-fast); font-family: inherit;
}
.field-input:focus, .field-textarea:focus { border-color: var(--color-primary); }
.field-textarea { resize: vertical; line-height: 1.6; }

.char-count { font-size: 10px; color: var(--color-text-muted); }
.char-count--warn { color: #f59e0b; }
.char-count--ok   { color: var(--color-primary); }
.char-min { color: var(--color-text-muted); }

/* ── Hub selector ────────────────────────────────────────────── */
.hub-selector { display: flex; gap: 8px; flex-wrap: wrap; }
.hub-option {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 7px 14px; font-size: 12px; font-weight: 700;
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md); cursor: pointer; color: var(--color-text-secondary);
    transition: all var(--transition-fast);
}
.hub-option--active {
    background: color-mix(in srgb, var(--hub-color) 12%, transparent);
    border-color: var(--hub-color);
    color: var(--hub-color);
}

/* ── Tags ────────────────────────────────────────────────────── */
.tag-input-wrap {
    display: flex; flex-wrap: wrap; gap: 6px; align-items: center;
    padding: 8px 10px;
    background: var(--color-surface-alt); border: 1px solid var(--color-border);
    border-radius: var(--radius-sm); cursor: text;
}
.tag-chips { display: flex; flex-wrap: wrap; gap: 5px; }
.tag-chip {
    display: inline-flex; align-items: center; gap: 3px;
    font-size: 11px; font-weight: 600;
    background: var(--color-primary-soft); color: var(--color-primary);
    padding: 2px 8px; border-radius: var(--radius-pill);
}
.tag-remove {
    background: none; border: none; cursor: pointer;
    color: var(--color-primary); font-size: 13px; line-height: 1; padding: 0;
}
.tag-input {
    flex: 1; min-width: 120px; border: none; background: transparent;
    font-size: 12px; color: var(--color-text-primary); outline: none; font-family: inherit;
}

/* ── Options row ─────────────────────────────────────────────── */
.options-row {
    display: flex; flex-direction: column; gap: 12px;
    padding: 14px 0; border-top: 1px solid var(--color-border-light);
}
.option-field { display: flex; flex-direction: column; gap: 6px; }
.toggle-group { display: flex; gap: 6px; flex-wrap: wrap; }
.toggle-btn {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 5px 12px; font-size: 11px; font-weight: 600;
    background: var(--color-surface-alt); border: 1px solid var(--color-border);
    border-radius: var(--radius-sm); cursor: pointer; color: var(--color-text-secondary);
    transition: all var(--transition-fast);
}
.toggle-btn--active {
    background: var(--color-primary); border-color: var(--color-primary); color: #fff;
}
.nick-toggle {
    display: flex; align-items: center; gap: 6px;
    font-size: 12px; color: var(--color-text-secondary); cursor: pointer;
}

/* ── Submit ──────────────────────────────────────────────────── */
.submit-row {
    display: flex; align-items: center; justify-content: flex-end; gap: 10px;
    padding-top: 8px; border-top: 1px solid var(--color-border-light);
}
[dir="rtl"] .submit-row { justify-content: flex-start; }
.cancel-link {
    font-size: 12px; color: var(--color-text-muted); text-decoration: none;
    transition: color var(--transition-fast);
}
.cancel-link:hover { color: var(--color-text-secondary); }
.post-btn {
    display: inline-flex; align-items: center; gap: 6px;
    background: var(--color-primary); color: #fff;
    font-size: 13px; font-weight: 700; padding: 9px 18px; border: none;
    border-radius: var(--radius-md); cursor: pointer; transition: background var(--transition-fast);
}
.post-btn:hover:not(:disabled) { background: var(--color-primary-light); }
.post-btn:disabled { opacity: 0.55; cursor: not-allowed; }

/* ── Desktop ─────────────────────────────────────────────────── */
@media (min-width: 768px) {
    .create-page { padding: 24px 0; }
    .options-row { flex-direction: row; flex-wrap: wrap; gap: 20px; }
    .option-field { min-width: 180px; }
    .create-title { font-size: 22px; }
}
</style>
