<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/ShareKnowledge/CreatePost.vue
//  Location: resources/js/Pages/Member/ShareKnowledge/CreatePost.vue
//
//  Share a thought or social media post with the community.
//
//  Fields:
//    - Hub selector
//    - Title
//    - Body (markdown supported)
//    - Source URL (optional — goes through /go?url= warning)
//    - Source label (optional — LinkedIn / WhatsApp / Article / Other)
//    - Language toggle
//    - Visibility (all / hub only)
//    - Nickname toggle
//    - Tags (optional, max 5)
//
//  Same engine as Forum/Create.vue — different labels + source fields.
//  No best answer concept — this is sharing, not asking.
// ══════════════════════════════════════════════════════════════════

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:               '',
    source_url:         '',
    source_label:       '',
    language:           locale.value === 'ar' ? 'ar' : 'en',
    visibility:         'all',
    posted_as_nickname: true,
    tags:               [],
});

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

const sourceLabels = ['LinkedIn', 'WhatsApp', 'Article', 'Twitter / X', 'Other'];

// ── Tags ──────────────────────────────────────────────────────────
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.share.post.store'), form.value, {
        onError:  () => { isPosting.value = false; },
        onFinish: () => { isPosting.value = false; },
    });
}

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

<template>
    <AppLayout :title="locale === 'ar' ? 'شارك المعرفة' : 'Share Knowledge'">
        <Head :title="locale === 'ar' ? 'شارك فكرة أو منشور' : 'Share a Post or Thought'" />

        <div class="cp-page">
            <div class="cp-card">

                <!-- Header -->
                <div class="cp-header">
                    <Link :href="route('member.share.index')" class="cp-back">
                        <i class="ti ti-arrow-left"></i>
                    </Link>
                    <div>
                        <h1 class="cp-title">
                            {{ locale === 'ar' ? 'شارك فكرة أو منشور' : 'Share a Post or Thought' }}
                        </h1>
                        <p class="cp-sub">
                            {{ locale === 'ar'
                                ? 'شارك رأيك، أو منشور مفيد من سوشيال ميديا، مع المجموعة'
                                : 'Share your insight or a useful post with the community' }}
                        </p>
                    </div>
                </div>

                <!-- Hub selector -->
                <div class="cp-field">
                    <label class="cp-label">{{ locale === 'ar' ? 'المجموعة' : 'Hub' }}</label>
                    <div class="cp-hub-row">
                        <button
                            v-for="hub in allHubs"
                            :key="hub.id"
                            type="button"
                            class="cp-hub-btn"
                            :class="{ 'cp-hub-btn--active': form.hub_id === hub.id }"
                            :style="form.hub_id === hub.id ? `--hub-color: ${hub.color}` : ''"
                            @click="form.hub_id = hub.id"
                        >
                            {{ hubName(hub) }}
                        </button>
                    </div>
                    <span v-if="errors.hub_id" class="cp-error">{{ errors.hub_id }}</span>
                </div>

                <!-- Title -->
                <div class="cp-field">
                    <label class="cp-label">
                        {{ locale === 'ar' ? 'العنوان' : 'Title' }}
                        <span class="cp-required">*</span>
                    </label>
                    <input
                        v-model="form.title"
                        type="text"
                        class="cp-input"
                        :placeholder="locale === 'ar' ? 'عنوان قصير وواضح...' : 'A short, clear title...'"
                        maxlength="200"
                    />
                    <span v-if="errors.title" class="cp-error">{{ errors.title }}</span>
                </div>

                <!-- Body -->
                <div class="cp-field">
                    <label class="cp-label">
                        {{ locale === 'ar' ? 'المحتوى' : 'Content' }}
                        <span class="cp-required">*</span>
                    </label>
                    <textarea
                        v-model="form.body"
                        class="cp-textarea"
                        rows="6"
                        :placeholder="locale === 'ar'
                            ? 'اكتب ما تريد مشاركته... يمكنك لصق منشور كامل من LinkedIn أو WhatsApp'
                            : 'Write what you want to share... you can paste a full post from LinkedIn or WhatsApp'"
                    ></textarea>
                    <span v-if="errors.body" class="cp-error">{{ errors.body }}</span>
                </div>

                <!-- Source URL (optional) -->
                <div class="cp-field">
                    <label class="cp-label">
                        {{ locale === 'ar' ? 'رابط المصدر (اختياري)' : 'Source Link (optional)' }}
                    </label>
                    <p class="cp-hint">
                        {{ locale === 'ar'
                            ? 'إذا كان المنشور من موقع خارجي، ضع رابطه هنا. سيتم تحذير الأعضاء قبل مغادرة InPractice.'
                            : 'If this post is from an external site, add the link. Members will see a warning before leaving InPractice.' }}
                    </p>
                    <input
                        v-model="form.source_url"
                        type="url"
                        class="cp-input"
                        :placeholder="locale === 'ar' ? 'https://...' : 'https://...'"
                    />
                    <span v-if="errors.source_url" class="cp-error">{{ errors.source_url }}</span>
                </div>

                <!-- Source label -->
                <div v-if="form.source_url" class="cp-field">
                    <label class="cp-label">
                        {{ locale === 'ar' ? 'مصدر المنشور' : 'Where is this from?' }}
                    </label>
                    <div class="cp-source-labels">
                        <button
                            v-for="lbl in sourceLabels"
                            :key="lbl"
                            type="button"
                            class="cp-src-btn"
                            :class="{ 'cp-src-btn--active': form.source_label === lbl }"
                            @click="form.source_label = lbl"
                        >
                            {{ lbl }}
                        </button>
                    </div>
                </div>

                <!-- Language + Visibility row -->
                <div class="cp-row">
                    <div class="cp-field cp-field--half">
                        <label class="cp-label">{{ locale === 'ar' ? 'لغة المنشور' : 'Language' }}</label>
                        <div class="cp-toggle-row">
                            <button
                                type="button"
                                class="cp-toggle-btn"
                                :class="{ 'cp-toggle-btn--active': form.language === 'en' }"
                                @click="form.language = 'en'"
                            >English</button>
                            <button
                                type="button"
                                class="cp-toggle-btn"
                                :class="{ 'cp-toggle-btn--active': form.language === 'ar' }"
                                @click="form.language = 'ar'"
                            >العربية</button>
                        </div>
                    </div>

                    <div class="cp-field cp-field--half">
                        <label class="cp-label">{{ locale === 'ar' ? 'الظهور' : 'Visibility' }}</label>
                        <div class="cp-toggle-row">
                            <button
                                type="button"
                                class="cp-toggle-btn"
                                :class="{ 'cp-toggle-btn--active': form.visibility === 'all' }"
                                @click="form.visibility = 'all'"
                            >{{ locale === 'ar' ? 'الجميع' : 'All' }}</button>
                            <button
                                type="button"
                                class="cp-toggle-btn"
                                :class="{ 'cp-toggle-btn--active': form.visibility === 'hub' }"
                                @click="form.visibility = 'hub'"
                            >{{ locale === 'ar' ? 'المجموعة فقط' : 'Hub only' }}</button>
                        </div>
                    </div>
                </div>

                <!-- Nickname toggle -->
                <div class="cp-field">
                    <div class="cp-check-row" @click="form.posted_as_nickname = !form.posted_as_nickname">
                        <div class="cp-checkbox" :class="{ 'cp-checkbox--checked': form.posted_as_nickname }">
                            <i v-if="form.posted_as_nickname" class="ti ti-check"></i>
                        </div>
                        <div>
                            <div class="cp-check-label">
                                {{ locale === 'ar' ? 'نشر باسم مستعار' : 'Post under nickname' }}
                            </div>
                            <div class="cp-check-sub">
                                {{ locale === 'ar' ? 'اسمك الحقيقي لن يظهر للآخرين' : 'Your real name will not be visible to others' }}
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tags -->
                <div class="cp-field">
                    <label class="cp-label">
                        {{ locale === 'ar' ? 'وسوم (اختياري، حتى 5)' : 'Tags (optional, max 5)' }}
                    </label>
                    <div class="cp-tags-input">
                        <span
                            v-for="tag in form.tags"
                            :key="tag"
                            class="cp-tag"
                        >
                            {{ tag }}
                            <button type="button" @click="removeTag(tag)">×</button>
                        </span>
                        <input
                            v-if="form.tags.length < 5"
                            v-model="tagInput"
                            type="text"
                            :placeholder="locale === 'ar' ? 'أضف وسمًا...' : 'Add a tag...'"
                            @keydown="handleTagKeydown"
                        />
                    </div>
                </div>

                <!-- Submit -->
                <div class="cp-actions">
                    <Link :href="route('member.share.index')" class="cp-btn-cancel">
                        {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                    </Link>
                    <button
                        type="button"
                        class="cp-btn-submit"
                        :disabled="isPosting || !form.title || !form.body"
                        @click="submit"
                    >
                        <i v-if="isPosting" class="ti ti-loader cp-spin"></i>
                        <i v-else class="ti ti-share"></i>
                        {{ locale === 'ar' ? 'شارك الآن' : 'Share Now' }}
                    </button>
                </div>

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

<style scoped>
.cp-page {
    padding: 16px;
    display: flex;
    justify-content: center;
}
.cp-card {
    width: 100%;
    max-width: 720px;
    background: var(--color-surface);
    border-radius: 16px;
    border: 1.5px solid var(--color-border);
    padding: 24px;
    display: flex;
    flex-direction: column;
    gap: 20px;
}
.cp-header { display: flex; align-items: flex-start; gap: 14px; }
.cp-back {
    display: flex; align-items: center; justify-content: center;
    width: 36px; height: 36px; border-radius: 10px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    text-decoration: none; flex-shrink: 0;
    transition: all 0.15s;
}
.cp-back:hover { border-color: var(--color-primary); color: var(--color-primary); }
.cp-title { font-size: 18px; font-weight: 700; color: var(--color-text); margin-bottom: 4px; }
.cp-sub   { font-size: 13px; color: var(--color-text-muted); line-height: 1.4; }

.cp-field { display: flex; flex-direction: column; gap: 6px; }
.cp-field--half { flex: 1; }
.cp-row { display: flex; gap: 16px; flex-wrap: wrap; }

.cp-label  { font-size: 13px; font-weight: 600; color: var(--color-text); }
.cp-hint   { font-size: 12px; color: var(--color-text-muted); line-height: 1.5; margin: 0; }
.cp-required { color: #e53e3e; }
.cp-error  { font-size: 12px; color: #e53e3e; }

.cp-input, .cp-textarea {
    padding: 10px 14px;
    border-radius: 10px;
    border: 1.5px solid var(--color-border);
    background: var(--color-bg);
    color: var(--color-text);
    font-size: 14px;
    outline: none;
    transition: border-color 0.15s;
    width: 100%;
    box-sizing: border-box;
}
.cp-input:focus, .cp-textarea:focus { border-color: var(--color-primary); }
.cp-textarea { resize: vertical; font-family: inherit; line-height: 1.6; }

.cp-hub-row { display: flex; gap: 8px; flex-wrap: wrap; }
.cp-hub-btn {
    padding: 8px 16px; border-radius: 20px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.15s;
}
.cp-hub-btn--active {
    border-color: var(--hub-color, var(--color-primary));
    color: var(--hub-color, var(--color-primary));
    background: rgba(29,158,117,0.08);
}

.cp-source-labels { display: flex; gap: 8px; flex-wrap: wrap; }
.cp-src-btn {
    padding: 6px 14px; border-radius: 20px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.15s;
}
.cp-src-btn--active {
    border-color: #378ADD; color: #378ADD;
    background: rgba(55,138,221,0.08);
}

.cp-toggle-row { display: flex; gap: 0; border-radius: 10px; overflow: hidden; border: 1.5px solid var(--color-border); }
.cp-toggle-btn {
    flex: 1; padding: 8px 12px; border: none;
    background: transparent; color: var(--color-text-muted);
    font-size: 13px; font-weight: 500; cursor: pointer; transition: all 0.15s;
}
.cp-toggle-btn--active { background: var(--color-primary); color: #fff; }

.cp-check-row {
    display: flex; align-items: flex-start; gap: 12px;
    cursor: pointer; padding: 12px 14px;
    border-radius: 10px; border: 1.5px solid var(--color-border);
    background: var(--color-bg);
}
.cp-checkbox {
    width: 20px; height: 20px; border-radius: 6px;
    border: 2px solid var(--color-border);
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0; transition: all 0.15s; font-size: 12px;
}
.cp-checkbox--checked { background: var(--color-primary); border-color: var(--color-primary); color: #fff; }
.cp-check-label { font-size: 13px; font-weight: 600; color: var(--color-text); }
.cp-check-sub   { font-size: 12px; color: var(--color-text-muted); }

.cp-tags-input {
    display: flex; flex-wrap: wrap; gap: 6px; align-items: center;
    padding: 8px 12px; border-radius: 10px;
    border: 1.5px solid var(--color-border); background: var(--color-bg);
    min-height: 42px;
}
.cp-tag {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 3px 10px; border-radius: 20px;
    background: rgba(29,158,117,0.12); color: var(--color-primary);
    font-size: 12px; font-weight: 500;
}
.cp-tag button { background: none; border: none; cursor: pointer; color: inherit; font-size: 14px; padding: 0; line-height: 1; }
.cp-tags-input input {
    border: none; background: transparent; outline: none;
    font-size: 13px; color: var(--color-text); min-width: 100px; flex: 1;
}

.cp-actions { display: flex; gap: 12px; justify-content: flex-end; padding-top: 4px; }
.cp-btn-cancel {
    padding: 10px 20px; border-radius: 10px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    font-size: 13px; font-weight: 600; text-decoration: none;
    display: inline-flex; align-items: center;
}
.cp-btn-submit {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 10px 24px; border-radius: 10px;
    background: var(--color-primary); color: #fff;
    font-size: 13px; font-weight: 700; border: none; cursor: pointer;
    transition: opacity 0.15s;
}
.cp-btn-submit:disabled { opacity: 0.6; cursor: not-allowed; }
@keyframes spin { to { transform: rotate(360deg); } }
.cp-spin { animation: spin 0.8s linear infinite; }

@media (min-width: 768px) {
    .cp-page { padding: 28px; }
    .cp-card { padding: 32px; }
}
</style>
