<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/Cases/Show.vue
//  Location: resources/js/Pages/Member/Cases/Show.vue
//
//  The full case reading experience. Structure:
//    1. Case header  — topic pill, difficulty, title, meta
//    2. The Situation
//    3. Case Data (numbers/tables) — if present
//    4. Challenge Questions — think before you reveal
//    5. Reveal Solution button → unlocks sections 6 & 7
//    6. Solution & Best Practice
//    7. The Bigger Lesson + Skills Taught
//    8. Mark as Complete CTA
//
//  MOBILE  (<768px): Single column, full width
//  DESKTOP (≥768px): Max-width article layout, centered
//
//  Rules:
//    - reveal() and complete() call backend via fetch (no page reload)
//    - Both locale content fields sent from backend — Vue picks correct one
//    - All CSS uses var(--color-*) tokens — no hardcoded hex
//    - Both themes automatic
//    - marked.js renders markdown tables, bold, lists inside content
// ══════════════════════════════════════════════════════════════════

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

// ── Configure marked ──────────────────────────────────────────────
marked.setOptions({
    breaks: true,
    gfm:    true,
});

// ── Props — from MemberCaseService + MemberSolutionService ────────
const props = defineProps({
    case:          { type: Object, required: true },
    progress:      { type: Object, required: true },
    solutions:     { type: Array,  default: () => [] },
    my_solution_id:{ type: Number, default: null },
    my_case_rating:{ type: Number, default: null, validator: () => true },
});

// ── Stores ────────────────────────────────────────────────────────
const authStore = useAuthStore();

// ── Locale helpers ────────────────────────────────────────────────
const locale = computed(() => authStore.locale);
const isDark  = computed(() => authStore.theme === 'dark');

// ── Local state — case reading ────────────────────────────────────
const solutionRevealed = ref(props.progress.solution_revealed);
const caseStatus       = ref(props.progress.status);
const isRevealing      = ref(false);
const isCompleting     = ref(false);

// ── Local state — InPractice solution rating ──────────────────────
const myCaseRating     = ref(props.my_case_rating ?? props.progress.case_rating ?? null);
const isRatingCase     = ref(false);

// ── Local state — member solutions ───────────────────────────────
const safeSolutions      = Array.isArray(props.solutions) ? props.solutions : [];
const solutionsList      = ref(safeSolutions);
const showOtherSolutions = ref(false);
const myWrittenSolution  = ref(
    props.my_solution_id
        ? safeSolutions.find(s => s.id === props.my_solution_id) ?? null
        : null
);
const showSolutionForm   = ref(false);
const solutionContent    = ref(myWrittenSolution.value?.content ?? '');
const isSubmittingSolution = ref(false);
const solutionError      = ref('');
const editingMode        = ref(false);

// ── Sync local state when Inertia reuses this page (case → case) ──
function syncFromProps() {
    solutionRevealed.value = !!props.progress.solution_revealed;
    caseStatus.value       = props.progress.status ?? 'started';
    myCaseRating.value     = props.my_case_rating ?? props.progress.case_rating ?? null;
    isRevealing.value      = false;
    isCompleting.value     = false;

    const safe = Array.isArray(props.solutions) ? props.solutions : [];
    solutionsList.value = safe;
    myWrittenSolution.value = props.my_solution_id
        ? safe.find(s => s.id === props.my_solution_id) ?? null
        : null;

    if (!editingMode.value) {
        solutionContent.value = myWrittenSolution.value?.content ?? '';
    }
}

watch(() => props.case.id, syncFromProps);
watch(() => props.progress, syncFromProps, { deep: true });

// Delete confirmation state
const deleteTarget       = ref(null); // { solution, ratingsCount }
const isDeleting         = ref(false);

// ── Bilingual content helpers ─────────────────────────────────────
const title = computed(() =>
    locale.value === 'ar' && props.case.title_ar
        ? props.case.title_ar : props.case.title_en
);

const subtitle = computed(() =>
    locale.value === 'ar' && props.case.subtitle_ar
        ? props.case.subtitle_ar : props.case.subtitle_en
);

const situation = computed(() =>
    locale.value === 'ar' && props.case.situation_ar
        ? props.case.situation_ar : props.case.situation_en
);

const challengeQuestions = computed(() =>
    locale.value === 'ar' && props.case.challenge_questions_ar?.length
        ? props.case.challenge_questions_ar
        : props.case.challenge_questions_en
);

const solution = computed(() =>
    locale.value === 'ar' && props.case.solution_ar
        ? props.case.solution_ar : props.case.solution_en
);

const biggerLesson = computed(() =>
    locale.value === 'ar' && props.case.bigger_lesson_ar
        ? props.case.bigger_lesson_ar : props.case.bigger_lesson_en
);

const skillsTaught = computed(() =>
    locale.value === 'ar' && props.case.skills_taught_ar?.length
        ? props.case.skills_taught_ar
        : props.case.skills_taught_en
);

const topicName = computed(() =>
    locale.value === 'ar' && props.case.topic_name_ar
        ? props.case.topic_name_ar : props.case.topic_name_en
);

// ── Markdown pre-processor ────────────────────────────────────────
// Fixes two common seeder issues so tables always render correctly:
//
// Problem 1 — No blank line before a table block.
//   marked requires an empty line before the first | row.
//   Fix: inject a blank line whenever a | line follows a non-| non-blank line.
//
// Problem 2 — No separator row (| --- | --- |) after the header row.
//   Without it marked treats every row as plain text.
//   Fix: after the first | row in each table block, if the next | row is NOT
//   a separator, inject one automatically using the column count.
//
function prepareMarkdown(text) {
    if (!text) return '';

    const lines = text.split('\n');
    const out   = [];

    for (let i = 0; i < lines.length; i++) {
        const line     = lines[i];
        const isTable  = line.trimStart().startsWith('|');
        const prevLine = out.length > 0 ? out[out.length - 1] : '';
        const prevIsTable  = prevLine.trimStart().startsWith('|');
        const prevIsBlank  = prevLine.trim() === '';

        // Fix 1: inject blank line before start of a table block
        if (isTable && !prevIsTable && !prevIsBlank) {
            out.push('');
        }

        out.push(line);

        // Fix 2: if this is the first row of a table block, check next line
        if (isTable && !prevIsTable) {
            const nextLine = lines[i + 1] ?? '';
            const nextIsTable = nextLine.trimStart().startsWith('|');
            const nextIsSep   = /^\s*\|[\s\-:|]+\|/.test(nextLine);

            if (nextIsTable && !nextIsSep) {
                // Count columns from this header row
                const cols = (line.match(/\|/g) ?? []).length - 1;
                const sep  = '| ' + Array(cols).fill('---').join(' | ') + ' |';
                out.push(sep);
            }
        }
    }

    return out.join('\n');
}

// ── Markdown renderers ────────────────────────────────────────────
const situationHtml    = computed(() => marked.parse(prepareMarkdown(situation.value    ?? '')));
const solutionHtml     = computed(() => marked.parse(prepareMarkdown(solution.value     ?? '')));
const biggerLessonHtml = computed(() => marked.parse(prepareMarkdown(biggerLesson.value ?? '')));

// ── Difficulty label + class ──────────────────────────────────────
function difficultyLabel(level) {
    const map = {
        beginner:     locale.value === 'ar' ? 'مبتدئ'  : 'Beginner',
        intermediate: locale.value === 'ar' ? 'متوسط'  : 'Intermediate',
        advanced:     locale.value === 'ar' ? 'متقدم'  : 'Advanced',
    };
    return map[level] ?? level;
}

function difficultyClass(level) {
    return {
        beginner:     'badge--beginner',
        intermediate: 'badge--intermediate',
        advanced:     'badge--advanced',
    }[level] ?? '';
}

// ── Case data table helper ────────────────────────────────────────
const hasCaseData = computed(() =>
    props.case.case_data && Object.keys(props.case.case_data).length > 0
);

// ── Smart value renderer for case_data entries ────────────────────
// Returns { type: 'table' | 'plain', content }
function parseDataValue(value) {
    // Array of objects → build a clean HTML table
    if (Array.isArray(value)) {
        const items = value.filter(v => v && typeof v === 'object');
        if (!items.length) return { type: 'plain', content: String(value) };
        const keys = Object.keys(items[0]);
        let html = '<table class="dv-inner-table"><thead><tr>';
        keys.forEach(k => { html += `<th>${k.replace(/_/g, ' ')}</th>`; });
        html += '</tr></thead><tbody>';
        items.forEach(row => {
            html += '<tr>';
            keys.forEach(k => { html += `<td>${row[k] ?? ''}</td>`; });
            html += '</tr>';
        });
        html += '</tbody></table>';
        return { type: 'table', content: html };
    }
    // String containing pipe characters → treat as markdown table
    if (typeof value === 'string' && value.includes('|')) {
        return { type: 'table', content: marked.parse(prepareMarkdown(value)) };
    }
    // Plain string or number
    return { type: 'plain', content: value };
}

// ── Reveal solution — Inertia PATCH (CSRF + session handled by router) ──
function revealSolution() {
    if (solutionRevealed.value || isRevealing.value) return;
    isRevealing.value = true;

    router.patch(
        route('member.cases.reveal', props.case.id, false),
        {},
        {
            preserveScroll: true,
            onSuccess: () => {
                const progress = usePage().props.progress;
                solutionRevealed.value = !!progress?.solution_revealed;
            },
            onFinish: () => {
                isRevealing.value = false;
            },
        },
    );
}

// ── Mark complete — PATCH via fetch, no page reload ───────────────
async function markComplete() {
    if (caseStatus.value === 'completed' || isCompleting.value) return;
    isCompleting.value = true;

    try {
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
        const res = await fetch(route('member.cases.complete', props.case.id), {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'Accept':       'application/json',
            },
        });

        if (res.ok) {
            caseStatus.value = 'completed';
        }
    } catch (e) {
        // silent
    } finally {
        isCompleting.value = false;
    }
}

// ── Rate the InPractice solution ──────────────────────────────────
async function rateCase(rating) {
    if (isRatingCase.value) return;
    isRatingCase.value = true;
    const prev = myCaseRating.value;
    myCaseRating.value = rating; // optimistic

    try {
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
        const res = await fetch(route('member.cases.rate', props.case.id), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: JSON.stringify({ rating }),
        });
        if (!res.ok) myCaseRating.value = prev;
    } catch (e) {
        myCaseRating.value = prev;
    } finally {
        isRatingCase.value = false;
    }
}

// ── Submit / update member solution ──────────────────────────────
async function submitSolution() {
    if (isSubmittingSolution.value) return;
    solutionError.value = '';

    if (solutionContent.value.trim().length < 50) {
        solutionError.value = locale.value === 'ar'
            ? 'الحل يجب أن يكون 50 حرفاً على الأقل'
            : 'Your solution must be at least 50 characters.';
        return;
    }

    isSubmittingSolution.value = true;
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';

    try {
        let url, method;
        if (editingMode.value && myWrittenSolution.value) {
            url    = route('member.cases.solutions.update', [props.case.id, myWrittenSolution.value.id]);
            method = 'PATCH';
        } else {
            url    = route('member.cases.solutions.store', props.case.id);
            method = 'POST';
        }

        const res = await fetch(url, {
            method,
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: JSON.stringify({ content: solutionContent.value }),
        });

        if (res.ok) {
            const data = await res.json();
            if (editingMode.value) {
                const idx = solutionsList.value.findIndex(s => s.id === data.solution.id);
                if (idx !== -1) solutionsList.value[idx] = data.solution;
            } else {
                solutionsList.value.unshift(data.solution);
            }
            myWrittenSolution.value = data.solution;
            showSolutionForm.value  = false;
            editingMode.value       = false;
        } else {
            const err = await res.json();
            solutionError.value = err.errors?.content?.[0] ?? (locale.value === 'ar' ? 'حدث خطأ' : 'Something went wrong.');
        }
    } catch (e) {
        solutionError.value = locale.value === 'ar' ? 'حدث خطأ' : 'Something went wrong.';
    } finally {
        isSubmittingSolution.value = false;
    }
}

function startEdit() {
    solutionContent.value  = myWrittenSolution.value?.content ?? '';
    editingMode.value       = true;
    showSolutionForm.value  = true;
}

function cancelForm() {
    showSolutionForm.value = false;
    editingMode.value      = false;
    solutionError.value    = '';
    if (!editingMode.value) solutionContent.value = '';
}

// ── Delete solution — two step: check count → confirm ────────────
async function confirmDelete(solution) {
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
    const res = await fetch(
        route('member.cases.solutions.rating-count', [props.case.id, solution.id]),
        { headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken } }
    );
    const data = await res.json();
    deleteTarget.value = { solution, ratingsCount: data.ratings_count };
}

async function executeDelete() {
    if (isDeleting.value || !deleteTarget.value) return;
    isDeleting.value = true;

    try {
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
        const res = await fetch(
            route('member.cases.solutions.destroy', [props.case.id, deleteTarget.value.solution.id]),
            { method: 'DELETE', headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrfToken } }
        );

        if (res.ok) {
            solutionsList.value    = solutionsList.value.filter(s => s.id !== deleteTarget.value.solution.id);
            myWrittenSolution.value = null;
            solutionContent.value  = '';
            deleteTarget.value     = null;
        }
    } finally {
        isDeleting.value = false;
    }
}

// ── Rate a member solution ────────────────────────────────────────
async function rateSolution(solution, rating) {
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
    const res = await fetch(
        route('member.cases.solutions.rate', [props.case.id, solution.id]),
        {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: JSON.stringify({ rating }),
        }
    );

    if (res.ok) {
        const data = await res.json();
        const idx = solutionsList.value.findIndex(s => s.id === solution.id);
        if (idx !== -1) {
            solutionsList.value[idx].avg_rating    = data.avg_rating;
            solutionsList.value[idx].ratings_count = data.ratings_count;
            solutionsList.value[idx].my_rating     = data.my_rating;
            if (data.badge) solutionsList.value[idx].author.badge = data.badge;
        }
    }
}

// ── Achievement badge labels ──────────────────────────────────────
function badgeNameEn(key) {
    const map = { top_contributor: 'Top Contributor', sharp_mind: 'Sharp Mind', rising_voice: 'Rising Voice' };
    return map[key] ?? key;
}
function badgeNameAr(key) {
    const map = { top_contributor: 'أفضل مساهم', sharp_mind: 'عقل حاد', rising_voice: 'صوت صاعد' };
    return map[key] ?? key;
}

// ── Other solutions (not mine) ────────────────────────────────────
const otherSolutions = computed(() =>
    solutionsList.value.filter(s => !s.is_mine)
);
</script>

<template>
    <AppLayout :title="title">
        <Head :title="title" />

        <div class="case-page">
            <!-- ── Back link ──────────────────────────────────── -->
            <div class="back-row">
                <Link :href="route('member.cases.index')" class="back-link">
                    <i :class="locale === 'ar' ? 'ti ti-arrow-right' : 'ti ti-arrow-left'"
                       aria-hidden="true"></i>
                    {{ locale === 'ar' ? 'مكتبة الحالات' : 'Case Library' }}
                </Link>

                <!-- Completion badge — shown once complete -->
                <span v-if="caseStatus === 'completed'" class="complete-badge">
                    <i class="ti ti-check" aria-hidden="true"></i>
                    {{ locale === 'ar' ? 'مكتمل' : 'Completed' }}
                </span>
            </div>

            <!-- ── Article ────────────────────────────────────── -->
            <article class="case-article">

                <!-- ① CASE HEADER ───────────────────────────── -->
                <header class="case-header">
                    <!-- Pills row -->
                    <div class="case-header__pills">
                        <span class="topic-pill">
                            {{ topicName }}
                        </span>
                        <span class="diff-badge" :class="difficultyClass(props.case.difficulty)">
                            {{ difficultyLabel(props.case.difficulty) }}
                        </span>
                        <span class="layer-badge">
                            {{ props.case.layer === 'sector_specific'
                                ? (locale === 'ar' ? 'قطاع محدد' : 'Sector Specific')
                                : (locale === 'ar' ? 'عام' : 'Generic') }}
                        </span>
                        <span v-if="props.case.sectors?.length" class="sector-pill">
                            <i class="ti ti-building" aria-hidden="true"></i>
                            {{ locale === 'ar' ? props.case.sectors[0].name_ar : props.case.sectors[0].name_en }}
                        </span>
                    </div>

                    <!-- Title -->
                    <h1 class="case-title">{{ title }}</h1>

                    <!-- Subtitle -->
                    <p v-if="subtitle" class="case-subtitle">{{ subtitle }}</p>

                    <!-- Meta row -->
                    <div class="case-meta">
                        <span>
                            <i class="ti ti-clock" aria-hidden="true"></i>
                            {{ props.case.read_time_minutes }}
                            {{ locale === 'ar' ? 'دقائق للقراءة' : 'min read' }}
                        </span>
                        <span v-if="caseStatus === 'started'" class="meta-in-progress">
                            <i class="ti ti-book-2" aria-hidden="true"></i>
                            {{ locale === 'ar' ? 'قيد القراءة' : 'In Progress' }}
                        </span>
                    </div>
                </header>

                <!-- ② THE SITUATION ───────────────────────── -->
                <section class="case-section">
                    <h2 class="section-heading">
                        <span class="section-heading__num">01</span>
                        {{ locale === 'ar' ? 'الموقف' : 'The Situation' }}
                    </h2>
                    <div class="case-prose md-content" v-html="situationHtml"></div>
                </section>

                <!-- ③ CASE DATA (numbers/tables) ─────────── -->
                <section v-if="hasCaseData" class="case-section">
                    <h2 class="section-heading">
                        <span class="section-heading__num">02</span>
                        {{ locale === 'ar' ? 'الأرقام' : 'The Numbers' }}
                    </h2>
                    <div class="case-data-table">
                        <template v-for="(value, key) in props.case.case_data" :key="key">

                            <!-- Plain value: two-column row -->
                            <div v-if="parseDataValue(value).type === 'plain'" class="data-row">
                                <div class="data-key">{{ key }}</div>
                                <div class="data-val">{{ parseDataValue(value).content }}</div>
                            </div>

                            <!-- Table value: label above, full-width table below -->
                            <div v-else class="data-row data-row--table">
                                <div class="data-key data-key--label">{{ key }}</div>
                                <div class="data-val--table md-content"
                                     v-html="parseDataValue(value).content"></div>
                            </div>

                        </template>
                    </div>
                </section>

                <!-- ④ CHALLENGE QUESTIONS ─────────────────── -->
                <section class="case-section">
                    <h2 class="section-heading">
                        <span class="section-heading__num">{{ hasCaseData ? '03' : '02' }}</span>
                        {{ locale === 'ar' ? 'فكر قبل أن تقرأ الحل' : 'Think Before You Read the Solution' }}
                    </h2>
                    <div class="challenge-box">
                        <ol class="challenge-list">
                            <li
                                v-for="(q, index) in challengeQuestions"
                                :key="index"
                                class="challenge-item">
                                {{ q }}
                            </li>
                        </ol>
                    </div>
                </section>

                <!-- ⑤ REVEAL SOLUTION GATE ─────────────────── -->
                <div v-if="!solutionRevealed" class="reveal-gate">
                    <div class="reveal-gate__inner">
                        <i class="ti ti-lock" aria-hidden="true"></i>
                        <p class="reveal-gate__text">
                            {{ locale === 'ar'
                                ? 'تأكد من أنك فكرت في الأسئلة أعلاه قبل الكشف عن الحل'
                                : 'Make sure you have thought through the questions above before revealing the solution.' }}
                        </p>
                        <button
                            type="button"
                            class="reveal-btn"
                            :disabled="isRevealing"
                            @click="revealSolution">
                            <i class="ti ti-eye" aria-hidden="true"></i>
                            {{ isRevealing
                                ? (locale === 'ar' ? 'جاري...' : 'Loading...')
                                : (locale === 'ar' ? 'اكشف الحل وأفضل الممارسات' : 'Reveal Solution & Best Practice') }}
                        </button>
                    </div>
                </div>

                <!-- ⑥ SOLUTION & BEST PRACTICE ─────────────── -->
                <section v-if="solutionRevealed" class="case-section case-section--solution">
                    <h2 class="section-heading section-heading--solution">
                        <span class="section-heading__num">{{ hasCaseData ? '04' : '03' }}</span>
                        {{ locale === 'ar' ? 'الحل وأفضل الممارسات' : 'Solution & Best Practice' }}
                    </h2>
                    <div class="case-prose solution-prose md-content" v-html="solutionHtml"></div>
                </section>

                <!-- ⑦ BIGGER LESSON + SKILLS ─────────────── -->
                <template v-if="solutionRevealed">
                    <section class="case-section">
                        <h2 class="section-heading">
                            <span class="section-heading__num">{{ hasCaseData ? '05' : '04' }}</span>
                            {{ locale === 'ar' ? 'الدرس الأكبر' : 'The Bigger Lesson' }}
                        </h2>
                        <div class="bigger-lesson-box md-content" v-html="biggerLessonHtml"></div>
                    </section>

                    <section class="case-section">
                        <h2 class="section-heading">
                            <span class="section-heading__num">{{ hasCaseData ? '06' : '05' }}</span>
                            {{ locale === 'ar' ? 'المهارات التي تعلمتها' : 'Skills This Case Teaches' }}
                        </h2>
                        <ul class="skills-list">
                            <li v-for="(skill, index) in skillsTaught" :key="index" class="skill-item">
                                <i class="ti ti-check" aria-hidden="true"></i>
                                {{ skill }}
                            </li>
                        </ul>
                    </section>
                </template>

                <!-- ⑧ MARK COMPLETE CTA ──────────────────── -->
                <div v-if="solutionRevealed" class="complete-cta">
                    <button
                        v-if="caseStatus !== 'completed'"
                        class="complete-btn"
                        :disabled="isCompleting"
                        @click="markComplete">
                        <i class="ti ti-circle-check" aria-hidden="true"></i>
                        {{ isCompleting
                            ? (locale === 'ar' ? 'جاري...' : 'Saving...')
                            : (locale === 'ar' ? 'تم — سجّل هذه الحالة' : 'Mark as Complete') }}
                    </button>

                    <div v-else class="completed-state">
                        <i class="ti ti-circle-check-filled" aria-hidden="true"></i>
                        <span>{{ locale === 'ar' ? 'أتممت هذه الحالة' : 'Case completed!' }}</span>
                        <Link :href="route('member.cases.index')" class="next-case-link">
                            {{ locale === 'ar' ? 'حالة أخرى ←' : '→ Next Case' }}
                        </Link>
                    </div>
                </div>

                <!-- ════════════════════════════════════════════
                     ⑨ RATE INPRACTICE SOLUTION
                ════════════════════════════════════════════════ -->
                <section v-if="solutionRevealed" class="case-section sol-rate-section">
                    <h2 class="section-heading">
                        <span class="section-heading__num">{{ hasCaseData ? '07' : '06' }}</span>
                        {{ locale === 'ar' ? 'قيّم حل InPractice' : 'Rate the InPractice Solution' }}
                    </h2>
                    <div class="rate-ip-box">
                        <p class="rate-ip-hint">
                            {{ locale === 'ar'
                                ? 'كيف تقيّم الحل الرسمي؟'
                                : 'How helpful was the official solution?' }}
                        </p>
                        <div class="star-row">
                            <button
                                v-for="star in 5"
                                :key="star"
                                class="star-btn"
                                :class="{ 'star-btn--active': myCaseRating >= star }"
                                :disabled="isRatingCase"
                                @click="rateCase(star)"
                                :aria-label="`Rate ${star} stars`">
                                ★
                            </button>
                            <span v-if="myCaseRating" class="star-label">
                                {{ myCaseRating }}/5
                            </span>
                        </div>
                    </div>
                </section>

                <!-- ════════════════════════════════════════════
                     ⑩ WRITE YOUR OWN SOLUTION
                ════════════════════════════════════════════════ -->
                <section v-if="solutionRevealed" class="case-section">
                    <h2 class="section-heading">
                        <span class="section-heading__num">{{ hasCaseData ? '08' : '07' }}</span>
                        {{ locale === 'ar' ? 'حلك أنت' : 'Your Solution' }}
                    </h2>

                    <!-- Already submitted — show it -->
                    <div v-if="myWrittenSolution && !showSolutionForm" class="my-solution-box">
                        <div class="my-sol-header">
                            <span class="my-sol-tag">
                                <i class="ti ti-user-check" aria-hidden="true"></i>
                                {{ locale === 'ar' ? 'حلك' : 'Your solution' }}
                            </span>
                            <span class="my-sol-meta">
                                {{ myWrittenSolution.created_at }}
                                <span v-if="myWrittenSolution.was_edited" class="edited-tag">
                                    · {{ locale === 'ar' ? 'معدّل' : 'edited' }}
                                </span>
                            </span>
                            <div class="my-sol-actions">
                                <button class="sol-action-btn" @click="startEdit">
                                    <i class="ti ti-pencil" aria-hidden="true"></i>
                                    {{ locale === 'ar' ? 'تعديل' : 'Edit' }}
                                </button>
                                <button class="sol-action-btn sol-action-btn--danger" @click="confirmDelete(myWrittenSolution)">
                                    <i class="ti ti-trash" aria-hidden="true"></i>
                                    {{ locale === 'ar' ? 'حذف' : 'Delete' }}
                                </button>
                            </div>
                        </div>
                        <div class="my-sol-content">{{ myWrittenSolution.content }}</div>
                        <!-- Rating received -->
                        <div v-if="myWrittenSolution.ratings_count > 0" class="my-sol-rating">
                            <i class="ti ti-star-filled" aria-hidden="true"></i>
                            {{ myWrittenSolution.avg_rating }}
                            <span class="rating-count">({{ myWrittenSolution.ratings_count }})</span>
                            <span v-if="myWrittenSolution.author?.badge" class="achievement-badge">
                                {{ myWrittenSolution.author.badge.icon }}
                                {{ locale === 'ar'
                                    ? badgeNameAr(myWrittenSolution.author.badge.key)
                                    : badgeNameEn(myWrittenSolution.author.badge.key) }}
                            </span>
                        </div>
                    </div>

                    <!-- Form — new or edit -->
                    <div v-if="!myWrittenSolution || showSolutionForm" class="solution-form-box">
                        <p v-if="!editingMode" class="sol-form-hint">
                            {{ locale === 'ar'
                                ? 'شارك حلك — الأعضاء سيقيّمونه'
                                : 'Share your approach — members will rate it.' }}
                        </p>
                        <textarea
                            v-model="solutionContent"
                            class="sol-textarea"
                            :placeholder="locale === 'ar'
                                ? 'اكتب حلك هنا (50 حرفاً على الأقل)...'
                                : 'Write your solution here (min 50 characters)...'"
                            rows="6"
                            maxlength="5000">
                        </textarea>
                        <div class="sol-form-footer">
                            <span class="sol-char-count"
                                  :class="{ 'sol-char-count--warn': solutionContent.length < 50 }">
                                {{ solutionContent.length }} / 5000
                            </span>
                            <p v-if="solutionError" class="sol-error">{{ solutionError }}</p>
                            <div class="sol-form-btns">
                                <button v-if="editingMode" class="sol-cancel-btn" @click="cancelForm">
                                    {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                                </button>
                                <button
                                    class="sol-submit-btn"
                                    :disabled="isSubmittingSolution || solutionContent.trim().length < 50"
                                    @click="submitSolution">
                                    <i class="ti ti-send" aria-hidden="true"></i>
                                    {{ isSubmittingSolution
                                        ? (locale === 'ar' ? 'جاري...' : 'Saving...')
                                        : editingMode
                                            ? (locale === 'ar' ? 'حفظ التعديل' : 'Save Changes')
                                            : (locale === 'ar' ? 'نشر حلك' : 'Post Your Solution') }}
                                </button>
                            </div>
                        </div>
                    </div>
                </section>

                <!-- ════════════════════════════════════════════
                     ⑪ MEMBER SOLUTIONS
                ════════════════════════════════════════════════ -->
                <section v-if="solutionRevealed" class="case-section">
                    <div class="mem-sol-header">
                        <h2 class="section-heading">
                            <span class="section-heading__num">{{ hasCaseData ? '09' : '08' }}</span>
                            {{ locale === 'ar' ? 'حلول الأعضاء' : 'Member Solutions' }}
                            <span class="sol-count-badge">{{ otherSolutions.length }}</span>
                        </h2>
                        <button
                            v-if="otherSolutions.length > 0"
                            class="toggle-solutions-btn"
                            @click="showOtherSolutions = !showOtherSolutions">
                            <i :class="showOtherSolutions ? 'ti ti-eye-off' : 'ti ti-eye'" aria-hidden="true"></i>
                            {{ showOtherSolutions
                                ? (locale === 'ar' ? 'إخفاء' : 'Hide')
                                : (locale === 'ar' ? 'اطّلع على حلول الآخرين' : 'See how others solved it') }}
                        </button>
                    </div>

                    <!-- Empty state -->
                    <div v-if="otherSolutions.length === 0" class="mem-sol-empty">
                        <i class="ti ti-writing" aria-hidden="true"></i>
                        <p>{{ locale === 'ar' ? 'لا توجد حلول أعضاء بعد. كن الأول!' : 'No member solutions yet. Be the first!' }}</p>
                    </div>

                    <!-- Solutions list — collapsed by default -->
                    <div v-if="showOtherSolutions && otherSolutions.length > 0" class="mem-sol-list">
                        <div
                            v-for="sol in otherSolutions"
                            :key="sol.id"
                            class="mem-sol-card">

                            <!-- Author row -->
                            <div class="mem-sol-author">
                                <div class="mem-sol-avatar">
                                    {{ sol.author.nickname.slice(0,2).toUpperCase() }}
                                </div>
                                <div class="mem-sol-author-info">
                                    <span class="mem-sol-nickname">{{ sol.author.nickname }}</span>
                                    <span class="mem-sol-profession">{{ sol.author.profession }}</span>
                                </div>
                                <!-- Achievement badge -->
                                <span v-if="sol.author.badge" class="achievement-badge achievement-badge--card">
                                    {{ sol.author.badge.icon }}
                                    {{ locale === 'ar'
                                        ? badgeNameAr(sol.author.badge.key)
                                        : badgeNameEn(sol.author.badge.key) }}
                                </span>
                                <span class="mem-sol-time">{{ sol.created_at }}</span>
                            </div>

                            <!-- Content -->
                            <div class="mem-sol-content">{{ sol.content }}</div>

                            <!-- Rating row -->
                            <div class="mem-sol-rate-row">
                                <div class="star-row star-row--sm">
                                    <button
                                        v-for="star in 5"
                                        :key="star"
                                        class="star-btn star-btn--sm"
                                        :class="{ 'star-btn--active': sol.my_rating >= star }"
                                        @click="rateSolution(sol, star)"
                                        :aria-label="`Rate ${star} stars`">
                                        ★
                                    </button>
                                </div>
                                <span v-if="sol.ratings_count > 0" class="sol-avg">
                                    {{ sol.avg_rating }}
                                    <span class="rating-count">({{ sol.ratings_count }})</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </section>

            </article>
        </div>

        <!-- ════════════════════════════════════════════════════
             DELETE CONFIRMATION MODAL
        ════════════════════════════════════════════════════════ -->
        <Transition name="modal">
            <div v-if="deleteTarget" class="modal-overlay" @click.self="deleteTarget = null">
                <div class="modal-box">
                    <div class="modal-icon">
                        <i class="ti ti-alert-triangle" aria-hidden="true"></i>
                    </div>
                    <h3 class="modal-title">
                        {{ locale === 'ar' ? 'حذف حلك؟' : 'Delete your solution?' }}
                    </h3>
                    <p class="modal-body">
                        <template v-if="deleteTarget.ratingsCount > 0">
                            {{ locale === 'ar'
                                ? `حلك حصل على ${deleteTarget.ratingsCount} تقييم. الحذف سيمسح جميع التقييمات نهائياً.`
                                : `Your solution has ${deleteTarget.ratingsCount} rating${deleteTarget.ratingsCount !== 1 ? 's' : ''}. Deleting it will permanently remove all ratings.` }}
                        </template>
                        <template v-else>
                            {{ locale === 'ar'
                                ? 'هل أنت متأكد من حذف حلك؟ لا يمكن التراجع.'
                                : 'Are you sure? This cannot be undone.' }}
                        </template>
                    </p>
                    <div class="modal-actions">
                        <button class="modal-cancel" @click="deleteTarget = null">
                            {{ locale === 'ar' ? 'إلغاء' : 'Cancel' }}
                        </button>
                        <button class="modal-confirm" :disabled="isDeleting" @click="executeDelete">
                            <i class="ti ti-trash" aria-hidden="true"></i>
                            {{ isDeleting
                                ? (locale === 'ar' ? 'جاري...' : 'Deleting...')
                                : (locale === 'ar' ? 'نعم، احذف' : 'Yes, Delete') }}
                        </button>
                    </div>
                </div>
            </div>
        </Transition>

    </AppLayout>
</template>

<style scoped>
/* ── Page wrapper ────────────────────────────────────────────── */
.case-page {
    padding: 14px 14px 24px;
    display: flex;
    flex-direction: column;
    gap: 0;
}

/* ── Back link row ───────────────────────────────────────────── */
.back-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 14px;
}

.back-link {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 11px; font-weight: 600;
    color: var(--color-text-muted);
    text-decoration: none;
    transition: color var(--transition-fast);
}

.back-link:hover { color: var(--color-primary); }
.back-link i { font-size: 13px; }

.complete-badge {
    display: inline-flex; align-items: center; gap: 4px;
    font-size: 10px; font-weight: 700;
    background: #dcfce7; color: #166534;
    padding: 3px 9px;
    border-radius: var(--radius-pill);
}

[data-theme="dark"] .complete-badge { background: #052e16; color: #86efac; }

/* ── Article ─────────────────────────────────────────────────── */
.case-article {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* ── Case header ─────────────────────────────────────────────── */
.case-header {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.case-header__pills {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    align-items: center;
}

.case-title {
    font-size: 20px; font-weight: 800;
    color: var(--color-text-primary);
    margin: 0; line-height: 1.3;
}

.case-subtitle {
    font-size: 13px;
    color: var(--color-text-muted);
    margin: 0; line-height: 1.5;
}

.case-meta {
    display: flex; gap: 12px; align-items: center;
    font-size: 11px; color: var(--color-text-muted);
}

.case-meta i { font-size: 12px; margin-right: 3px; }
[dir="rtl"] .case-meta i { margin-right: 0; margin-left: 3px; }

.meta-in-progress {
    color: var(--color-primary);
    font-weight: 600;
}

/* ── Pills / badges ──────────────────────────────────────────── */
.topic-pill {
    font-size: 10px; font-weight: 700;
    background: rgba(29,158,117,0.10);
    color: var(--color-primary);
    padding: 3px 8px;
    border-radius: var(--radius-pill);
    letter-spacing: 0.04em;
    text-transform: uppercase;
}

.diff-badge {
    font-size: 10px; font-weight: 700;
    padding: 3px 8px;
    border-radius: var(--radius-pill);
    letter-spacing: 0.04em;
}

.badge--beginner     { background: #dcfce7; color: #166534; }
.badge--intermediate { background: #fef9c3; color: #854d0e; }
.badge--advanced     { background: #fee2e2; color: #991b1b; }

[data-theme="dark"] .badge--beginner     { background: #052e16; color: #86efac; }
[data-theme="dark"] .badge--intermediate { background: #1c1400; color: #fde047; }
[data-theme="dark"] .badge--advanced     { background: #2d0000; color: #fca5a5; }

.layer-badge {
    font-size: 10px; font-weight: 600;
    background: var(--color-surface-alt);
    color: var(--color-text-muted);
    padding: 3px 8px;
    border-radius: var(--radius-pill);
}

.sector-pill {
    display: inline-flex; align-items: center; gap: 3px;
    font-size: 10px; font-weight: 600;
    background: var(--color-surface-alt);
    color: var(--color-text-muted);
    padding: 3px 8px;
    border-radius: var(--radius-pill);
}

/* ── Section ─────────────────────────────────────────────────── */
.case-section {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.case-section--solution {
    background: rgba(29, 158, 117, 0.04);
    border: 1px solid rgba(29, 158, 117, 0.15);
    border-radius: var(--radius-md);
    padding: 16px;
}

[data-theme="dark"] .case-section--solution {
    background: rgba(29, 158, 117, 0.06);
    border-color: rgba(29, 158, 117, 0.20);
}

/* ── Section heading ─────────────────────────────────────────── */
.section-heading {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px; font-weight: 700;
    color: var(--color-text-primary);
    margin: 0;
}

.section-heading--solution { color: var(--color-primary); }

.section-heading__num {
    font-size: 9px; font-weight: 800;
    color: var(--color-primary);
    background: rgba(29, 158, 117, 0.12);
    border-radius: var(--radius-sm);
    padding: 2px 5px;
    letter-spacing: 0.05em;
}

/* ── Prose content ───────────────────────────────────────────── */
.case-prose {
    font-size: 13px;
    color: var(--color-text-secondary);
    line-height: 1.75;
}

.solution-prose { color: var(--color-text-primary); }

/* ── Markdown content — tables, bold, lists ──────────────────── */
.md-content {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    max-width: 100%;
}

.md-content :deep(p) {
    margin: 0 0 10px;
    line-height: 1.75;
}

.md-content :deep(p:last-child) { margin-bottom: 0; }

.md-content :deep(strong) {
    font-weight: 700;
    color: var(--color-text-primary);
}

.md-content :deep(ul),
.md-content :deep(ol) {
    margin: 8px 0;
    padding-left: 20px;
    display: flex;
    flex-direction: column;
    gap: 5px;
}

[dir="rtl"] .md-content :deep(ul),
[dir="rtl"] .md-content :deep(ol) {
    padding-left: 0;
    padding-right: 20px;
}

.md-content :deep(li) {
    font-size: 13px;
    color: var(--color-text-secondary);
    line-height: 1.6;
}

/* ── Markdown tables ─────────────────────────────────────────── */
.md-content :deep(table) {
    display: block;          /* enables horizontal scroll on the element itself */
    width: 100%;
    min-width: 500px;
    border-collapse: collapse;
    font-size: 12px;
    margin: 0;
    border-radius: var(--radius-md);
    border: 0.5px solid var(--color-border);
    overflow-x: auto;        /* scroll on the table directly as a fallback */
    -webkit-overflow-scrolling: touch;
}

.md-content :deep(thead) {
    background: var(--color-surface-alt);
}

.md-content :deep(th) {
    padding: 9px 12px;
    font-size: 11px;
    font-weight: 700;
    color: var(--color-text-secondary);
    text-align: left;
    border-bottom: 1px solid var(--color-border);
    white-space: nowrap;
}

[dir="rtl"] .md-content :deep(th) { text-align: right; }

.md-content :deep(td) {
    padding: 8px 12px;
    font-size: 12px;
    color: var(--color-text-primary);
    border-bottom: 0.5px solid var(--color-border-light);
    vertical-align: top;
    font-variant-numeric: tabular-nums;
}

.md-content :deep(tr:last-child td) { border-bottom: none; }

.md-content :deep(tr:nth-child(even)) {
    background: rgba(0,0,0,0.015);
}

[data-theme="dark"] .md-content :deep(tr:nth-child(even)) {
    background: rgba(255,255,255,0.02);
}

/* ── Case data table ─────────────────────────────────────────── */
.case-data-table {
    border-radius: var(--radius-md);
    border: 0.5px solid var(--color-border);
    overflow: hidden;
}

/* Plain two-column row */
.data-row {
    display: flex;
    border-bottom: 0.5px solid var(--color-border-light);
}

.data-row:last-child { border-bottom: none; }

.data-key {
    flex: 0 0 42%;
    padding: 9px 12px;
    font-size: 12px;
    font-weight: 600;
    color: var(--color-text-secondary);
    background: var(--color-surface-alt);
    border-right: 0.5px solid var(--color-border-light);
    vertical-align: top;
}

[dir="rtl"] .data-key {
    border-right: none;
    border-left: 0.5px solid var(--color-border-light);
}

.data-val {
    flex: 1;
    padding: 9px 12px;
    font-size: 12px;
    color: var(--color-text-primary);
    font-variant-numeric: tabular-nums;
}

/* Table row: key becomes a top label, table takes full width */
.data-row--table {
    flex-direction: column;
}

.data-key--label {
    flex: none;
    width: 100%;
    border-right: none;
    border-left: none;
    border-bottom: 0.5px solid var(--color-border-light);
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.04em;
}

/* Full-width table container */
.data-val--table {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

/* Tables rendered from markdown inside data-val--table */
.data-val--table :deep(table) {
    width: 100%;
    min-width: 420px;
    border-collapse: collapse;
    font-size: 12px;
    margin: 0;
}

.data-val--table :deep(thead) {
    background: var(--color-surface-alt);
}

.data-val--table :deep(th) {
    padding: 8px 12px;
    font-size: 11px;
    font-weight: 700;
    color: var(--color-text-secondary);
    text-align: left;
    border-bottom: 1px solid var(--color-border);
    white-space: nowrap;
}

[dir="rtl"] .data-val--table :deep(th) { text-align: right; }

.data-val--table :deep(td) {
    padding: 8px 12px;
    font-size: 12px;
    color: var(--color-text-primary);
    border-bottom: 0.5px solid var(--color-border-light);
    vertical-align: top;
    font-variant-numeric: tabular-nums;
}

.data-val--table :deep(tr:last-child td) { border-bottom: none; }

.data-val--table :deep(tr:nth-child(even)) {
    background: rgba(0,0,0,0.015);
}

[data-theme="dark"] .data-val--table :deep(tr:nth-child(even)) {
    background: rgba(255,255,255,0.02);
}

/* Tables rendered from array-of-objects */
.data-val--table :deep(.dv-inner-table) {
    width: 100%;
    min-width: 420px;
    border-collapse: collapse;
    font-size: 12px;
    margin: 0;
}

.data-val--table :deep(.dv-inner-table th) {
    padding: 8px 12px;
    font-size: 11px;
    font-weight: 700;
    color: var(--color-text-secondary);
    background: var(--color-surface-alt);
    text-align: left;
    border-bottom: 1px solid var(--color-border);
    white-space: nowrap;
    text-transform: capitalize;
}

[dir="rtl"] .data-val--table :deep(.dv-inner-table th) { text-align: right; }

.data-val--table :deep(.dv-inner-table td) {
    padding: 8px 12px;
    font-size: 12px;
    color: var(--color-text-primary);
    border-bottom: 0.5px solid var(--color-border-light);
    vertical-align: top;
    font-variant-numeric: tabular-nums;
}

.data-val--table :deep(.dv-inner-table tr:last-child td) { border-bottom: none; }

.data-val--table :deep(.dv-inner-table tr:nth-child(even)) {
    background: rgba(0,0,0,0.015);
}

[data-theme="dark"] .data-val--table :deep(.dv-inner-table tr:nth-child(even)) {
    background: rgba(255,255,255,0.02);
}

/* ── Challenge box ───────────────────────────────────────────── */
.challenge-box {
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 14px 16px;
}

.challenge-list {
    margin: 0; padding: 0 0 0 18px;
    display: flex; flex-direction: column; gap: 8px;
}

[dir="rtl"] .challenge-list { padding: 0 18px 0 0; }

.challenge-item {
    font-size: 13px;
    color: var(--color-text-secondary);
    line-height: 1.6;
}

/* ── Reveal gate ─────────────────────────────────────────────── */
.reveal-gate {
    border: 1.5px dashed var(--color-border);
    border-radius: var(--radius-md);
    padding: 24px 16px;
}

.reveal-gate__inner {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    text-align: center;
}

.reveal-gate__inner > i {
    font-size: 28px;
    color: var(--color-text-muted);
}

.reveal-gate__text {
    font-size: 12px;
    color: var(--color-text-muted);
    line-height: 1.5;
    max-width: 320px;
}

.reveal-btn {
    display: inline-flex; align-items: center; gap: 7px;
    background: var(--color-primary);
    color: #fff;
    border: none;
    border-radius: var(--radius-md);
    padding: 10px 20px;
    font-size: 13px; font-weight: 600;
    cursor: pointer;
    transition: background var(--transition-fast);
    box-shadow: var(--shadow-button);
}

.reveal-btn:hover:not(:disabled) { background: var(--color-primary-light); }
.reveal-btn:disabled { opacity: 0.7; cursor: not-allowed; }

/* ── Bigger lesson ───────────────────────────────────────────── */
.bigger-lesson-box {
    background: var(--color-surface-alt);
    border-left: 3px solid var(--color-primary);
    border-radius: 0 var(--radius-md) var(--radius-md) 0;
    padding: 12px 14px;
    font-size: 13px;
    color: var(--color-text-secondary);
    line-height: 1.6;
    font-style: italic;
}

[dir="rtl"] .bigger-lesson-box {
    border-left: none;
    border-right: 3px solid var(--color-primary);
    border-radius: var(--radius-md) 0 0 var(--radius-md);
}

/* ── Skills list ─────────────────────────────────────────────── */
.skills-list {
    list-style: none;
    margin: 0; padding: 0;
    display: flex; flex-direction: column; gap: 6px;
}

.skill-item {
    display: flex; align-items: flex-start; gap: 8px;
    font-size: 12px;
    color: var(--color-text-secondary);
    line-height: 1.5;
}

.skill-item i {
    color: var(--color-primary);
    font-size: 13px;
    margin-top: 1px;
    flex-shrink: 0;
}

/* ── Complete CTA ────────────────────────────────────────────── */
.complete-cta {
    padding: 16px 0 8px;
    display: flex;
    justify-content: center;
}

.complete-btn {
    display: inline-flex; align-items: center; gap: 8px;
    background: var(--color-primary);
    color: #fff;
    border: none;
    border-radius: var(--radius-md);
    padding: 12px 24px;
    font-size: 14px; font-weight: 700;
    cursor: pointer;
    transition: background var(--transition-fast);
    box-shadow: var(--shadow-button);
    width: 100%;
    justify-content: center;
}

.complete-btn:hover:not(:disabled) { background: var(--color-primary-light); }
.complete-btn:disabled { opacity: 0.7; cursor: not-allowed; }

.completed-state {
    display: flex; align-items: center; justify-content: center;
    gap: 8px;
    font-size: 14px; font-weight: 700;
    color: var(--color-primary);
    width: 100%;
    padding: 10px;
}

.completed-state i { font-size: 20px; }

.next-case-link {
    font-size: 12px; font-weight: 600;
    color: var(--color-text-muted);
    text-decoration: none;
    margin-left: 8px;
    transition: color var(--transition-fast);
}

[dir="rtl"] .next-case-link { margin-left: 0; margin-right: 8px; }

.next-case-link:hover { color: var(--color-primary); }

/* ══════════════════════════════════════════════════════════════
   DESKTOP BREAKPOINT ≥768px
════════════════════════════════════════════════════════════════ */
@media (min-width: 768px) {
    .case-page {
        padding: 24px 32px 32px;
        max-width: none;
    }

    .case-title { font-size: 26px; }

    .case-prose { font-size: 14px; }

    .complete-btn {
        width: auto;
        min-width: 240px;
        padding: 13px 32px;
    }

    .md-content :deep(table) {
        font-size: 13px;
    }

    .md-content :deep(th),
    .md-content :deep(td) {
        padding: 10px 14px;
    }
}

/* ── Rate InPractice solution ─────────────────────────────────── */
.sol-rate-section { margin-top: 4px; }

.rate-ip-box {
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 14px 16px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.rate-ip-hint {
    font-size: 12px;
    color: var(--color-text-muted);
    margin: 0;
}

/* ── Star rows ────────────────────────────────────────────────── */
.star-row {
    display: flex;
    align-items: center;
    gap: 4px;
}

.star-row--sm { gap: 2px; }

.star-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 2px;
    font-size: 22px;
    color: #d1d5db;
    transition: color var(--transition-fast), transform var(--transition-fast);
    line-height: 1;
}

.star-btn--sm { font-size: 16px; }

.star-btn--active { color: #F5A623; }
.star-btn:hover:not(:disabled) { color: #F5A623; transform: scale(1.15); }
.star-btn:disabled { cursor: default; }

.star-label {
    font-size: 12px;
    font-weight: 700;
    color: var(--color-text-muted);
    margin-left: 6px;
}

[dir="rtl"] .star-label { margin-left: 0; margin-right: 6px; }

/* ── My solution box ─────────────────────────────────────────── */
.my-solution-box {
    background: var(--color-surface-alt);
    border: 1.5px solid var(--color-primary);
    border-radius: var(--radius-md);
    padding: 14px 16px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.my-sol-header {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.my-sol-tag {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 10px;
    font-weight: 700;
    color: var(--color-primary);
    background: rgba(29,158,117,0.10);
    padding: 3px 8px;
    border-radius: var(--radius-pill);
}

.my-sol-meta {
    font-size: 11px;
    color: var(--color-text-muted);
    flex: 1;
}

.edited-tag {
    font-style: italic;
    color: var(--color-text-muted);
}

.my-sol-actions {
    display: flex;
    gap: 6px;
}

.sol-action-btn {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    font-weight: 600;
    padding: 4px 10px;
    border-radius: var(--radius-sm);
    border: 1px solid var(--color-border);
    background: var(--color-surface);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: all var(--transition-fast);
}

.sol-action-btn:hover { background: var(--color-primary-soft); color: var(--color-primary); border-color: var(--color-primary); }
.sol-action-btn--danger:hover { background: rgba(220,38,38,0.08); color: #dc2626; border-color: #dc2626; }

.my-sol-content {
    font-size: 13px;
    color: var(--color-text-primary);
    line-height: 1.7;
    white-space: pre-wrap;
}

.my-sol-rating {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #F5A623;
    font-weight: 700;
}

.rating-count {
    color: var(--color-text-muted);
    font-weight: 400;
    font-size: 11px;
}

/* ── Achievement badge ───────────────────────────────────────── */
.achievement-badge {
    display: inline-flex;
    align-items: center;
    gap: 3px;
    font-size: 10px;
    font-weight: 700;
    background: rgba(245,166,35,0.12);
    color: #b45309;
    border: 1px solid rgba(245,166,35,0.30);
    padding: 2px 8px;
    border-radius: var(--radius-pill);
}

[data-theme="dark"] .achievement-badge {
    background: rgba(245,166,35,0.10);
    color: #fcd34d;
    border-color: rgba(245,166,35,0.20);
}

.achievement-badge--card { margin-left: auto; }
[dir="rtl"] .achievement-badge--card { margin-left: 0; margin-right: auto; }

/* ── Solution form ───────────────────────────────────────────── */
.solution-form-box {
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 14px 16px;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.sol-form-hint {
    font-size: 12px;
    color: var(--color-text-muted);
    margin: 0;
}

.sol-textarea {
    width: 100%;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-sm);
    padding: 10px 12px;
    font-size: 13px;
    color: var(--color-text-primary);
    line-height: 1.6;
    resize: vertical;
    min-height: 120px;
    font-family: inherit;
    transition: border-color var(--transition-fast);
    box-sizing: border-box;
}

.sol-textarea:focus {
    outline: none;
    border-color: var(--color-primary);
}

.sol-form-footer {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.sol-char-count {
    font-size: 10px;
    color: var(--color-text-muted);
    text-align: right;
}

[dir="rtl"] .sol-char-count { text-align: left; }

.sol-char-count--warn { color: var(--color-danger); }

.sol-error {
    font-size: 12px;
    color: var(--color-danger);
    margin: 0;
}

.sol-form-btns {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
}

[dir="rtl"] .sol-form-btns { justify-content: flex-start; }

.sol-cancel-btn {
    padding: 8px 16px;
    font-size: 13px;
    font-weight: 600;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-sm);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: all var(--transition-fast);
}

.sol-cancel-btn:hover { background: var(--color-surface-alt); }

.sol-submit-btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 18px;
    font-size: 13px;
    font-weight: 700;
    background: var(--color-primary);
    color: #fff;
    border: none;
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: background var(--transition-fast);
}

.sol-submit-btn:hover:not(:disabled) { background: var(--color-primary-light); }
.sol-submit-btn:disabled { opacity: 0.55; cursor: not-allowed; }

/* ── Member solutions list ───────────────────────────────────── */
.mem-sol-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 10px;
}

.sol-count-badge {
    font-size: 10px;
    font-weight: 700;
    background: var(--color-primary-soft);
    color: var(--color-primary);
    padding: 1px 7px;
    border-radius: var(--radius-pill);
    margin-left: 4px;
}

[dir="rtl"] .sol-count-badge { margin-left: 0; margin-right: 4px; }

.toggle-solutions-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
    font-weight: 600;
    color: var(--color-primary);
    background: var(--color-primary-soft);
    border: none;
    border-radius: var(--radius-sm);
    padding: 6px 12px;
    cursor: pointer;
    transition: background var(--transition-fast);
}

.toggle-solutions-btn:hover { background: rgba(29,158,117,0.15); }

.mem-sol-empty {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 16px;
    background: var(--color-surface-alt);
    border-radius: var(--radius-md);
    font-size: 13px;
    color: var(--color-text-muted);
}

.mem-sol-empty i { font-size: 20px; }

.mem-sol-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.mem-sol-card {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 14px 16px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    transition: border-color var(--transition-fast);
}

.mem-sol-card:hover { border-color: var(--color-primary); }

.mem-sol-author {
    display: flex;
    align-items: center;
    gap: 8px;
}

.mem-sol-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: var(--color-primary);
    color: #fff;
    font-size: 10px;
    font-weight: 800;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.mem-sol-author-info {
    display: flex;
    flex-direction: column;
    gap: 1px;
    flex: 1;
    min-width: 0;
}

.mem-sol-nickname {
    font-size: 12px;
    font-weight: 700;
    color: var(--color-text-primary);
}

.mem-sol-profession {
    font-size: 10px;
    color: var(--color-text-muted);
}

.mem-sol-time {
    font-size: 10px;
    color: var(--color-text-muted);
    flex-shrink: 0;
}

.mem-sol-content {
    font-size: 13px;
    color: var(--color-text-secondary);
    line-height: 1.7;
    white-space: pre-wrap;
}

.mem-sol-rate-row {
    display: flex;
    align-items: center;
    gap: 8px;
    padding-top: 4px;
    border-top: 1px solid var(--color-border-light);
}

.sol-avg {
    font-size: 12px;
    font-weight: 700;
    color: #F5A623;
}

/* ── Delete confirmation modal ───────────────────────────────── */
.modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.55);
    z-index: var(--z-modal);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.modal-box {
    background: var(--color-surface);
    border-radius: var(--radius-lg);
    padding: 24px 20px;
    max-width: 360px;
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 12px;
    box-shadow: var(--shadow-float);
}

.modal-icon {
    width: 44px;
    height: 44px;
    background: rgba(220,38,38,0.10);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    color: #dc2626;
    margin: 0 auto;
}

.modal-title {
    font-size: 16px;
    font-weight: 700;
    color: var(--color-text-primary);
    text-align: center;
    margin: 0;
}

.modal-body {
    font-size: 13px;
    color: var(--color-text-secondary);
    text-align: center;
    line-height: 1.6;
    margin: 0;
}

.modal-actions {
    display: flex;
    gap: 8px;
    margin-top: 4px;
}

.modal-cancel {
    flex: 1;
    padding: 10px;
    font-size: 13px;
    font-weight: 600;
    background: var(--color-surface-alt);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-sm);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: all var(--transition-fast);
}

.modal-cancel:hover { background: var(--color-border); }

.modal-confirm {
    flex: 1;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 10px;
    font-size: 13px;
    font-weight: 700;
    background: #dc2626;
    color: #fff;
    border: none;
    border-radius: var(--radius-sm);
    cursor: pointer;
    transition: background var(--transition-fast);
}

.modal-confirm:hover:not(:disabled) { background: #b91c1c; }
.modal-confirm:disabled { opacity: 0.6; cursor: not-allowed; }

/* Modal transition */
.modal-enter-active, .modal-leave-active { transition: opacity 0.2s ease; }
.modal-enter-from, .modal-leave-to { opacity: 0; }
</style>