'use client';

/**
 * 문서 상세 및 편집 페이지
 *
 * 문서의 내용을 확인하고 편집할 수 있는 페이지입니다.
 * - 조회 모드: Markdown 렌더링
 * - 편집 모드: Reflect 스타일 에디터 (TipTap 기반)
 */

import { useMemo, useRef, useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useSwipeable } from 'react-swipeable';
import dynamic from 'next/dynamic';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import SourceBadge from '@/components/SourceBadge';
import UnverifiedBanner from '@/components/trust/UnverifiedBanner';
import QnaRenderer from '@/components/QnaRenderer';
import BacklinksPanel from '@/components/BacklinksPanel';
import InlineReviewPanel from '@/components/review/InlineReviewPanel';
import RelatedDocsSidebar from '@/components/RelatedDocsSidebar';
import TableOfContents from '@/components/TableOfContents';
import GlobalHeader from '@/components/GlobalHeader';
import WikiLinkPreview from '@/components/WikiLinkPreview';
import ShadowIndicator from '@/components/ShadowIndicator';
import RevisionHistoryModal from '@/components/RevisionHistoryModal';
import RecordingConsentModal from '@/components/RecordingConsentModal';
import AudioRecorderButton from '@/components/AudioRecorderButton';
import ErrorReportButton from '@/components/ErrorReportButton';
import FloatingTermDetection from '@/components/FloatingTermDetection';
import DraftRecoveryModal from '@/components/DraftRecoveryModal';
import LeaveConfirmModal from '@/components/LeaveConfirmModal';
import { formatAuthorName } from '@/lib/constants';
import { useDocumentState, CATEGORY_OPTIONS } from './useDocumentState';
import { toast } from 'sonner';

const ReactMarkdown = dynamic(() => import('react-markdown'), { ssr: false });
const ReflectEditor = dynamic(() => import('@/components/ReflectEditor'), {
    ssr: false,
    loading: () => <div className="min-h-[400px] flex items-center justify-center"><div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-600"></div></div>
});

// Markdown 헤더에 ID를 부여하기 위한 커스텀 컴포넌트
// MarkdownComponents moved inside component to access state

/** 카카오 단톡 문서의 원본 대화 내용을 접이식으로 표시하는 컴포넌트 */
function KakaoRawSection({ rawText }: { rawText: string }) {
    const [isOpen, setIsOpen] = useState(false);
    return (
        <div className="mt-6 border border-gray-200 rounded-xl overflow-hidden">
            <button
                type="button"
                onClick={() => setIsOpen((prev) => !prev)}
                className="w-full flex items-center justify-between px-4 py-3 bg-gray-50 hover:bg-gray-100 transition-colors text-sm font-medium text-gray-600"
            >
                <span className="flex items-center gap-2">
                    <svg className="w-4 h-4 text-yellow-500" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M12 2C6.477 2 2 6.149 2 11.25c0 3.016 1.57 5.685 4 7.373V22l3.5-2.25c.814.165 1.645.25 2.5.25 5.523 0 10-4.149 10-9.25S17.523 2 12 2z"/>
                    </svg>
                    단톡방 원문 보기
                </span>
                <svg
                    className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                </svg>
            </button>
            {isOpen && (
                <div className="px-4 py-4 bg-white">
                    <pre className="whitespace-pre-wrap text-xs text-gray-600 font-sans leading-relaxed">{rawText}</pre>
                </div>
            )}
        </div>
    );
}

export default function DocumentClient({ id }: { id: string }) {
    const router = useRouter();
    const searchParams = useSearchParams();
    const fromTab = searchParams.get('from') as 'wiki' | 'my' | 'daily' | null;
    const docId = id;

    // (B) prevId / nextId 계산
    const [prevId, setPrevId] = useState<string | null>(null);
    const [nextId, setNextId] = useState<string | null>(null);

    useEffect(() => {
        if (!fromTab || typeof window === 'undefined') {
            setPrevId(null);
            setNextId(null);
            return;
        }
        try {
            const raw = sessionStorage.getItem(`insuwiki_card_list_${fromTab}`);
            if (!raw) { setPrevId(null); setNextId(null); return; }
            const ids: string[] = JSON.parse(raw);
            const idx = ids.indexOf(docId);
            if (idx === -1) { setPrevId(null); setNextId(null); return; }
            setPrevId(idx > 0 ? ids[idx - 1] : null);
            setNextId(idx < ids.length - 1 ? ids[idx + 1] : null);
        } catch {
            setPrevId(null);
            setNextId(null);
        }
    }, [docId, fromTab]);

    const goPrev = () => { if (prevId) router.push(`/docs/${prevId}${fromTab ? `?from=${fromTab}` : ''}`); };
    const goNext = () => { if (nextId) router.push(`/docs/${nextId}${fromTab ? `?from=${fromTab}` : ''}`); };

    // 모바일 스와이프 핸들러
    const swipeHandlers = useSwipeable({
        onSwipedLeft: () => nextId && goNext(),
        onSwipedRight: () => prevId && goPrev(),
        trackMouse: false,
        preventScrollOnSwipe: false,
        delta: 50,
    });

    const {
        // state
        document,
        isEditing,
        editContent,
        editTitle,
        editCategory,
        isSaving,
        loadingDoc,
        isTocOpen,
        isHistoryModalOpen,
        isUploading,
        isConsentModalOpen,
        revisions,
        shadowedDocId,
        // derived
        docType,
        isDaily,
        isDailyNote,
        isAdmin,
        headerVariant,
        buttonClass,
        // auth state
        user,
        userRole,
        loading,
        // lock state
        lockInfo,
        // setters needed by JSX
        setIsTocOpen,
        setIsHistoryModalOpen,
        setIsConsentModalOpen,
        setEditContent,
        setEditTitle,
        setEditCategory,
        // handlers
        handleEditClick,
        handleCancelClick,
        handleSave,
        handleVisibilityChange,
        handleDelete,
        handleRestore,
        handlePurge,
        handleFileUpload,
        handleRecordingComplete,
        handleDeleteAttachment,
        // auto-save
        autoSave,
        isLeaveConfirmOpen,
        isDraftRecoveryOpen,
        handleSaveAndLeave,
        handleDiscardAndLeave,
        handleContinueEditing,
        handleDraftRecover,
        handleDraftDiscard,
    } = useDocumentState(id);

    // 매 렌더마다 seenIds를 리셋 (react-markdown이 문서 순서대로 컴포넌트를 호출하므로 TOC와 동일하게 진행됨)
    const seenIdsRef = useRef(new Map<string, number>());
    seenIdsRef.current = new Map<string, number>();

    // Markdown Components Definition (Moved inside to access state)
    // TOC 컴포넌트와 동일한 ID 생성 로직을 사용하기 위해 cleanText 및 content 기반 ID 생성 적용
    const MarkdownComponents = useMemo(() => {
        const cleanText = (raw: string) => {
            return raw
                .replace(/\\/g, '') // 원화표시/백슬래시 제거
                .replace(/\[\[(.+?)\]\]/g, '$1') // [[위키링크]] -> 위키링크
                .replace(/\[(.+?)\]\(.+?\)/g, '$1') // [제목](링크) -> 제목
                .replace(/\*\*(.+?)\*\*/g, '$1') // **볼드** -> 볼드
                .replace(/\*(.+?)\*/g, '$1') // *이탤릭* -> 이탤릭
                .replace(/__(.+?)__/g, '$1') // __볼드__ -> 볼드
                .replace(/_(.+?)_/g, '$1') // _이탤릭_ -> 이탤릭
                .replace(/~~(.+?)~~/g, '$1') // ~~취소선~~ -> 취소선
                .trim();
        };

        const generateId = (level: number, node: any) => {
            if (!document?.content) return undefined;

            const lineIndex = (node?.position?.start?.line || 1) - 1;
            const lines = document.content.split('\n');
            const line = lines[lineIndex] || '';

            // 헤더 텍스트 추출 (### 제목 -> 제목)
            // TOC와 완벽하게 일치시키기 위해 원본 라인에서 파싱
            const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
            if (!headerMatch) return undefined;

            const text = cleanText(headerMatch[2]);
            const sanitized = text.toLowerCase().replace(/[^\wㄱ-ㅎㅏ-ㅣ가-힣]/g, '-');
            const base = `h-${level}-${sanitized}`;
            const count = seenIdsRef.current.get(base) || 0;
            seenIdsRef.current.set(base, count + 1);
            return count === 0 ? base : `${base}-${count}`;
        };

        return {
            h1: ({ children, node }: any) => {
                const id = generateId(1, node);
                return <h1 id={id} className="text-3xl font-bold mb-6 mt-8 pb-2 border-b border-gray-100 scroll-mt-10">{children}</h1>;
            },
            h2: ({ children, node }: any) => {
                const id = generateId(2, node);
                return <h2 id={id} className="text-2xl font-bold mb-4 mt-8 pb-1 border-b border-gray-50 scroll-mt-10">{children}</h2>;
            },
            h3: ({ children, node }: any) => {
                const id = generateId(3, node);
                return <h3 id={id} className="text-xl font-bold mb-3 mt-6 scroll-mt-10">{children}</h3>;
            },
            // WikiLink Preview support with Visibility Inheritance
            a: ({ href, children }: any) => {
                if (href?.startsWith('/docs/')) {
                    const docId = href.replace('/docs/', '');

                    // Determine target visibility:
                    // If current doc is Daily or Private, new links should default to Private (My)
                    const targetVisibility = (isDaily || document?.visibility === 'private') ? 'private' : 'public';
                    const isTargetPrivate = targetVisibility === 'private';

                    // Append visibility param if it's a new doc and we want it private
                    const finalHref = (docId.startsWith('new-') && isTargetPrivate)
                        ? `${href}?visibility=private`
                        : href;

                    return (
                        <WikiLinkPreview docId={docId} label={String(children)} visibility={isTargetPrivate ? 'private' : undefined}>
                            <Link
                                href={finalHref}
                                className="text-indigo-600 hover:text-indigo-800 underline decoration-indigo-300 hover:decoration-indigo-500 transition-colors"
                                prefetch={true}
                            >
                                {children}
                            </Link>
                        </WikiLinkPreview>
                    );
                }
                return (
                    <a
                        href={href}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-600 hover:text-blue-800 underline"
                    >
                        {children}
                    </a>
                );
            },
            u: ({ children }: any) => <span className="underline decoration-indigo-300 decoration-1 underline-offset-4">{children}</span>,
            li: ({ children, node, ...props }: any) => {
                // Generate content-based ID for TOC linking
                // Note: This relies on accessing the raw line from document content using source position
                if (!document?.content || !node?.position) return <li {...props}>{children}</li>;

                const lineIndex = (node.position.start.line || 1) - 1;
                const lines = document.content.split('\n');
                const line = lines[lineIndex] || '';

                // Extract text and indent from raw line to match TOC logic exactly
                const match = line.match(/^(\s*)([-*+]|\d+\.)\s+(.+)$/);
                if (!match) return <li {...props}>{children}</li>;

                const indent = match[1];
                const text = match[3].replace(/\\/g, '') // Clean text logic from TOC
                    .replace(/\[\[(.+?)\]\]/g, '$1')
                    .replace(/\[(.+?)\]\(.+?\)/g, '$1')
                    .replace(/\*\*(.+?)\*\*/g, '$1')
                    .replace(/\*(.+?)\*/g, '$1')
                    .replace(/__(.+?)__/g, '$1')
                    .replace(/_(.+?)_/g, '$1')
                    .replace(/~~(.+?)~~/g, '$1')
                    .trim();

                const level = Math.floor(indent.replace(/\t/g, '  ').length / 2) + 1;

                // Only generate ID if it matches TOC visibility (Level 1 & 2)
                if (level > 2) return <li {...props}>{children}</li>;

                const sanitized = text.toLowerCase().replace(/[^\wㄱ-ㅎㅏ-ㅣ가-힣]/g, '-');
                const base = `list-${level}-${sanitized}`;
                const count = seenIdsRef.current.get(base) || 0;
                seenIdsRef.current.set(base, count + 1);
                const id = count === 0 ? base : `${base}-${count}`;
                return <li id={id} className="scroll-mt-32" {...props}>{children}</li>;
            },
        };
    }, [isDaily, document?.visibility, document?.content]);

    // 4. Guest(미승인) 사용자 차단 (가입 직후)
    if (!loading && !loadingDoc && user && userRole === 'guest') {
        return (
            <div className="min-h-screen flex flex-col items-center justify-center p-4">
                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-8 max-w-md w-full text-center shadow-sm">
                    <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-yellow-100 mb-4">
                        <svg className="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z" />
                        </svg>
                    </div>
                    <h2 className="text-xl font-bold text-yellow-800 mb-2">가입 승인 대기 중</h2>
                    <p className="text-sm text-yellow-700 mb-6">
                        관리자 승인 후 문서를 열람할 수 있습니다.<br />
                        승인이 완료되면 자동으로 권한이 부여됩니다.
                    </p>
                    <div className="text-xs text-gray-500">
                        계정: {user.email}
                    </div>
                </div>
            </div>
        );
    }

    // 5. 비로그인 사용자 차단 (기존 로직)
    // 리다이렉트 대신 UI를 보여줌으로써 인앱 브라우저 호환성 확보
    if (!loading && !loadingDoc && !user) {
        return (
            <div className="min-h-screen flex flex-col items-center justify-center p-4">
                <div className="bg-white p-8 rounded-2xl shadow-lg border border-gray-100 max-w-md w-full text-center">
                    <div className="text-5xl mb-6">🔒</div>
                    <h2 className="text-2xl font-bold text-gray-900 mb-2">로그인이 필요합니다</h2>
                    <p className="text-gray-500 mb-8">
                        이 문서는 보험 전문가 전용 자료입니다.<br />
                        로그인 후 열람해 주세요.
                    </p>
                    <button
                        onClick={() => {
                            // 현재 URL을 저장하여 로그인 후 돌아올 수 있게 함
                            // 현재 URL을 저장하여 로그인 후 돌아올 수 있게 함
                            sessionStorage.setItem('redirectUrl', window.location.href);
                            const returnUrl = encodeURIComponent(window.location.href);
                            router.push(`/login?returnUrl=${returnUrl}`);
                        }}
                        className="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-6 rounded-xl transition-all shadow-md hover:shadow-lg active:scale-95"
                    >
                        로그인 하러 가기
                    </button>
                    <button
                        onClick={() => router.push(fromTab ? `/?tab=${fromTab}` : '/')}
                        className="mt-4 text-sm text-gray-400 hover:text-gray-600 underline"
                    >
                        메인으로 돌아가기
                    </button>
                </div>
            </div>
        );
    }

    if (loading || loadingDoc) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-600"></div>
            </div>
        );
    }

    // Loading State
    if (loadingDoc) {
        return (
            <div className="h-screen flex items-center justify-center bg-white">
                <div className="flex flex-col items-center gap-4">
                    <div className="w-10 h-10 border-4 border-indigo-100 border-t-indigo-600 rounded-full animate-spin"></div>
                    <p className="text-gray-500 font-medium">문서를 불러오는 중입니다...</p>
                </div>
            </div>
        );
    }

    if (!document) return null; // Should have redirected in useEffect if not found

    return (
        <div className={`h-[100dvh] max-h-[100dvh] overflow-hidden flex flex-col ${isDaily ? 'bg-emerald-50/20' : 'bg-white'}`}>
            {/* 공통 상단 헤더 */}
            <GlobalHeader
                variant={headerVariant}
                onTabChange={(tab) => {
                    router.push(`/?tab=${tab}`);
                }}
            />

            {/* 서브 네비게이션 — 2줄 구조 */}
            <nav className="sticky top-0 z-40 bg-white/80 backdrop-blur-md border-b border-gray-200 shadow-sm shrink-0">
                {/* 1줄: ← 목록으로 | 제목(h1/input) | Visibility 토글 */}
                <div className="max-w-5xl lg:max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-11 flex items-center gap-2 border-b border-gray-50">
                    <button
                        onClick={() => {
                            const tab = fromTab || (isDaily ? 'daily' : (document?.visibility === 'private' ? 'my' : 'wiki'));
                            router.push(`/?tab=${tab}`);
                        }}
                        className="text-gray-500 hover:text-gray-900 flex-shrink-0 text-sm whitespace-nowrap"
                    >
                        ← 목록으로
                    </button>
                    <div className="flex-1 min-w-0">
                        {!isEditing ? (
                            <h1 className="text-sm font-bold text-gray-900 truncate">
                                {document.title}
                            </h1>
                        ) : (
                            <input
                                type="text"
                                value={editTitle}
                                onChange={(e) => setEditTitle(e.target.value)}
                                className="w-full text-sm font-bold text-gray-900 bg-gray-50 border-none focus:ring-0 px-2 py-1 rounded truncate"
                                placeholder="제목 없음"
                            />
                        )}
                    </div>
                    {/* Visibility Toggle: 작성자 본인 + Daily 제외 */}
                    {user && document && user.uid === document.authorId && !isDaily && (
                        <div className="flex items-center bg-gray-100 rounded-lg p-0.5 shrink-0">
                            <button
                                onClick={() => handleVisibilityChange('public')}
                                className={`px-2 py-1 text-xs font-medium rounded-md transition-all flex items-center gap-1 ${(document.visibility === 'public' || !document.visibility)
                                    ? 'bg-white text-indigo-600 shadow-sm'
                                    : 'text-gray-500 hover:text-gray-700'
                                    }`}
                                title="공유(Public)"
                            >
                                <span>🌏</span><span className="hidden sm:inline text-[11px]">공유</span>
                            </button>
                            <button
                                onClick={() => handleVisibilityChange('private')}
                                className={`px-2 py-1 text-xs font-medium rounded-md transition-all flex items-center gap-1 ${document.visibility === 'private'
                                    ? 'bg-white text-amber-600 shadow-sm'
                                    : 'text-gray-500 hover:text-gray-700'
                                    }`}
                                title="비공개(Private)"
                            >
                                <span>🔒</span><span className="hidden sm:inline text-[11px]">비공개</span>
                            </button>
                        </div>
                    )}
                </div>

                {/* 2줄: 카테고리배지 + 공유 + 히스토리 */}
                <div className="max-w-5xl lg:max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-10 flex items-center justify-between gap-2">
                    {/* 왼쪽: 카테고리배지 + 공유 + 히스토리 */}
                    <div className="flex items-center gap-1 min-w-0">
                        {!isEditing && (
                            <>
                                {/* 카테고리 배지 */}
                                {!isDaily && document.category && document.category !== 'general' && (
                                    <span className={`text-[11px] px-2 py-0.5 rounded-full font-bold whitespace-nowrap shrink-0 ${document.category === 'medical' ? 'bg-indigo-100 text-indigo-600' :
                                        document.category === 'casualty' ? 'bg-blue-100 text-blue-600' :
                                            document.category === 'wealth' ? 'bg-amber-100 text-amber-600' :
                                                document.category === 'practice' ? 'bg-slate-200 text-slate-600' :
                                                    'bg-gray-100 text-gray-500'
                                        }`}>
                                        {document.category === 'medical' ? '🏥 의료' :
                                            document.category === 'casualty' ? '🚗 손해' :
                                                document.category === 'wealth' ? '💰 자산' :
                                                    document.category === 'practice' ? '⚖️ 실무' : ''}
                                    </span>
                                )}
                                {/* 편집 모드에서 카테고리 select */}
                            </>
                        )}
                        {isEditing && !isDaily && (
                            <select
                                value={editCategory}
                                onChange={(e) => setEditCategory(e.target.value as any)}
                                onMouseDown={(e) => e.stopPropagation()}
                                onClick={(e) => e.stopPropagation()}
                                className="text-xs px-2 py-1 rounded-lg border border-gray-200 bg-white focus:ring-2 focus:ring-indigo-200 focus:border-indigo-400 transition-all"
                            >
                                {CATEGORY_OPTIONS.map(opt => (
                                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                                ))}
                            </select>
                        )}

                        {/* Share 버튼 */}
                        {!isEditing && (
                            <button
                                onClick={async () => {
                                    const url = window.location.href;
                                    if (navigator.share && /mobile/i.test(navigator.userAgent)) {
                                        try { await navigator.share({ title: document.title, url }); }
                                        catch (e) { console.error('Share failed', e); }
                                    } else {
                                        try {
                                            await navigator.clipboard.writeText(url);
                                            toast.success('링크가 클립보드에 복사되었습니다.');
                                        } catch (e) { console.error('Copy failed', e); toast.error('링크 복사에 실패했습니다.'); }
                                    }
                                }}
                                className="p-1.5 text-gray-400 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
                                title="링크 공유"
                            >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
                                </svg>
                            </button>
                        )}

                        {/* 히스토리 버튼 */}
                        {!isEditing && !document.isDeleted && docType !== 'daily' && document.visibility !== 'private' && (
                            <button
                                onClick={() => setIsHistoryModalOpen(true)}
                                className="p-1.5 text-gray-400 hover:text-amber-600 hover:bg-amber-50 rounded-lg transition-colors"
                                title="변경 이력 (History)"
                            >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                            </button>
                        )}
                    </div>

                    {/* 오른쪽: 삭제·복원·편집 버튼 */}
                    <div className="flex items-center gap-1 shrink-0">
                        {isEditing ? (
                            <>
                                <button
                                    onClick={handleCancelClick}
                                    className="px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-md transition-colors"
                                >
                                    취소
                                </button>
                                <button
                                    onClick={() => handleSave()}
                                    disabled={isSaving}
                                    className={`px-3 py-1.5 text-sm font-bold text-white rounded-xl shadow-sm transition-all border active:scale-95 disabled:opacity-50 ${buttonClass}`}
                                >
                                    {isSaving ? '저장...' : '저장'}
                                </button>
                            </>
                        ) : (
                            <>
                                {/* 삭제 버튼 */}
                                {((document.visibility === 'private' && user?.uid === document.authorId) || isAdmin) && !document.isDeleted && (
                                    <button
                                        onClick={handleDelete}
                                        className="text-red-500 hover:text-red-700 hover:bg-red-50 p-1.5 rounded-lg transition-colors"
                                        title="문서 삭제"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                    </button>
                                )}
                                {/* 복원 버튼 */}
                                {((user?.uid === document.authorId) || isAdmin) && document.isDeleted && (
                                    <button
                                        onClick={handleRestore}
                                        className="text-white bg-emerald-500 hover:bg-emerald-600 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1 text-sm font-bold shadow-sm"
                                        title="문서 복원"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                        </svg>
                                        <span className="hidden sm:inline">복원</span>
                                    </button>
                                )}
                                {/* Purge 버튼 (관리자) */}
                                {isAdmin && document.isDeleted && (
                                    <button
                                        onClick={handlePurge}
                                        className="text-white bg-red-600 hover:bg-red-700 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1 text-sm font-bold shadow-sm"
                                        title="영구 삭제"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                        </svg>
                                        <span className="hidden sm:inline">영구삭제</span>
                                    </button>
                                )}
                                {/* 편집 버튼 */}
                                <button
                                    onClick={handleEditClick}
                                    className={`px-4 py-1.5 text-sm font-bold text-white rounded-xl shadow-sm transition-all border active:scale-95 ${buttonClass} ${lockInfo.isLocked && !lockInfo.mine ? 'opacity-50 cursor-not-allowed' : ''}`}
                                    disabled={lockInfo.isLocked && !lockInfo.mine}
                                    title={lockInfo.isLocked && !lockInfo.mine ? `${lockInfo.lockedByName}님이 편집 중` : ''}
                                >
                                    {lockInfo.isLocked && !lockInfo.mine ? `🔒 ${lockInfo.lockedByName}` : '편집'}
                                </button>
                            </>
                        )}
                    </div>
                </div>
            </nav>


            {/* 모바일 전용 목차 드롭다운 */}
            {
                isTocOpen && (
                    <div className="lg:hidden sticky top-28 z-[5] bg-white border-b border-gray-200 shadow-lg animate-in slide-in-from-top duration-200">
                        <div className="max-w-5xl mx-auto py-2">
                            <div className="flex items-center justify-between px-6 py-2 border-b border-gray-50">
                                <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest">Table of Contents</span>
                                <button onClick={() => setIsTocOpen(false)} className="text-gray-400 hover:text-gray-600">
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>
                            <TableOfContents
                                content={document.content}
                                variant={docType}
                                isMobile={true}
                                onClose={() => setIsTocOpen(false)}
                                isEditing={isEditing}
                                editContent={isEditing ? editContent : undefined}
                            />
                        </div>
                    </div>
                )
            }

            {/* (C) PC 화살표 네비게이션 (md 이상, fixed) */}
            {fromTab && (
                <>
                    <button
                        onClick={goPrev}
                        disabled={!prevId}
                        className={`hidden md:flex fixed top-1/2 -translate-y-1/2 left-4 w-14 h-14 rounded-full bg-white/70 backdrop-blur-md shadow-lg items-center justify-center hover:bg-white/95 hover:scale-105 transition-all z-30 ${!prevId ? 'opacity-30 pointer-events-none' : ''}`}
                        title="이전 문서"
                    >
                        <svg className="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M15 18l-6-6 6-6" />
                        </svg>
                    </button>
                    <button
                        onClick={goNext}
                        disabled={!nextId}
                        className={`hidden md:flex fixed top-1/2 -translate-y-1/2 right-4 w-14 h-14 rounded-full bg-white/70 backdrop-blur-md shadow-lg items-center justify-center hover:bg-white/95 hover:scale-105 transition-all z-30 ${!nextId ? 'opacity-30 pointer-events-none' : ''}`}
                        title="다음 문서"
                    >
                        <svg className="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M9 18l6-6-6-6" />
                        </svg>
                    </button>
                </>
            )}

            {/* 콘텐츠 영역 (스크롤러) — 모바일 스와이프 핸들러 부착 (편집 모드 제외) */}
            <div id="scroll-container" className="flex-1 overflow-y-auto relative scroll-smooth" {...(!isEditing ? swipeHandlers : {})}>
                <main className="max-w-5xl lg:max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8" data-doc-type={docType}>
                    {/* Shadow Indicator Alert */}
                    {shadowedDocId && document && (
                        <ShadowIndicator publicDocId={shadowedDocId} publicDocTitle={document.title} />
                    )}

                    {/* Soft Delete Banner */}
                    {document.isDeleted && (
                        <div className="bg-red-50 border-l-4 border-red-500 p-4 mb-6 rounded-r-lg shadow-sm">
                            <div className="flex items-center justify-between flex-wrap gap-2">
                                <div className="flex items-center">
                                    <svg className="h-5 w-5 text-red-500 mr-2" viewBox="0 0 20 20" fill="currentColor">
                                        <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                                    </svg>
                                    <p className="text-sm text-red-700 font-medium">
                                        이 문서는 휴지통에 있습니다.
                                        {document.deletedAt && ` (삭제일: ${(document.deletedAt as any)?.toDate?.()?.toLocaleString() || 'Unknown'})`}
                                    </p>
                                </div>
                                <div className="flex items-center gap-2">
                                    {((user?.uid === document.authorId) || isAdmin) && (
                                        <button
                                            onClick={handleRestore}
                                            className="text-xs bg-white text-red-600 border border-red-200 hover:bg-red-50 px-3 py-1.5 rounded-md font-bold transition-colors shadow-sm"
                                        >
                                            문서 복원하기
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}

                    <div className="flex flex-col lg:flex-row gap-4">
                        {/* 목차 사이드바 */}
                        <TableOfContents
                            content={document.content}
                            variant={docType}
                            isEditing={isEditing}
                            editContent={isEditing ? editContent : undefined}
                        />

                        {/* 문서 컨텐츠 */}
                        <div className="flex-1 min-w-0">
                            {/* 글로벌 문서 제목 UI */}
                            <h1 className="text-2xl lg:text-4xl font-extrabold text-gray-900 mb-8 tracking-tight break-words">
                                {document.title}
                            </h1>

                            {/* 출처/신뢰도 메타 정보 (Phase 2) */}
                            {!isEditing && document.sourceType && (
                                <div className="mb-6 p-4 bg-gray-50/50 rounded-xl border border-gray-100">
                                    <SourceBadge
                                        sourceType={document.sourceType}
                                        authorityTier={document.authorityTier}
                                        verificationStatus={document.verificationStatus}
                                        size="md"
                                    />
                                    {document.sourceRef && (
                                        <div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-gray-500">
                                            {document.sourceRef.channelName && (
                                                <span className="inline-flex items-center gap-1">
                                                    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 8h2a2 2 0 012 2v6a2 2 0 01-2 2h-2v4l-4-4H9a1.994 1.994 0 01-1.414-.586m0 0L11 14h4a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2v4l.586-.586z" />
                                                    </svg>
                                                    출처: {document.sourceRef.channelName}
                                                </span>
                                            )}
                                            {document.sourceRef.collectedAt && (
                                                <span>
                                                    수집일: {
                                                        typeof document.sourceRef.collectedAt === 'string'
                                                            ? document.sourceRef.collectedAt
                                                            : document.sourceRef.collectedAt?.toDate?.()?.toLocaleDateString('ko-KR') || ''
                                                    }
                                                </span>
                                            )}
                                        </div>
                                    )}
                                </div>
                            )}

                            {/* 미검증 콘텐츠 배너 (Phase 2a) */}
                            {!isEditing && (!document.verificationStatus || document.verificationStatus === 'unverified') && document.sourceType && (
                                <UnverifiedBanner
                                    category={document.category}
                                    sourceType={document.sourceType}
                                    className="mb-6"
                                />
                            )}

                            {isEditing ? (
                                <div className="w-full overscroll-contain">
                                    <ReflectEditor
                                        content={editContent}
                                        onChange={(markdown) => setEditContent(markdown)}
                                        onSave={handleSave}
                                    />
                                    <div className="mt-2 flex items-center justify-between">
                                        <p className="text-xs text-gray-400 italic">
                                            Markdown 및 WikiLink([[...]])를 지원합니다.
                                        </p>
                                        {autoSave.draftStatus === 'saved' && autoSave.lastSavedAt && (
                                            <p className="text-xs text-gray-400">
                                                임시저장 {autoSave.lastSavedAt.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })}
                                            </p>
                                        )}
                                        {autoSave.draftStatus === 'saving' && (
                                            <p className="text-xs text-indigo-400 animate-pulse">
                                                임시저장 중...
                                            </p>
                                        )}
                                        {autoSave.draftStatus === 'error' && (
                                            <p className="text-xs text-red-400">
                                                임시저장 실패
                                            </p>
                                        )}
                                    </div>

                                </div>
                            ) : (
                                <article className="max-w-none">
                                    <div className="prose prose-indigo dark:prose-invert max-w-none prose-ul:pl-4 prose-ol:pl-4 prose-li:my-0.5 md:prose-ul:pl-8 md:prose-ol:pl-8">
                                        {/* Q&A 전용 렌더러 (카카오 단톡 문서) */}
                                        {(document.sourceType === 'kakao_expert' || document.sourceType === 'kakao_community') && (document.question || document.answer) && (
                                            <div className="mb-8 not-prose">
                                                <QnaRenderer
                                                    question={document.question}
                                                    answer={document.answer}
                                                    expertName={document.sourceMeta?.expertName}
                                                    channelName={document.sourceRef?.channelName}
                                                    collectedAt={document.sourceRef?.collectedAt}
                                                />
                                                {/* 단톡방 원문 (접이식) */}
                                                {(() => {
                                                    const rawMarker = '(원본)';
                                                    const markerIndex = document.content?.indexOf(rawMarker) ?? -1;
                                                    if (markerIndex === -1) return null;
                                                    const rawText = document.content!.slice(markerIndex + rawMarker.length).trim();
                                                    if (!rawText) return null;
                                                    return (
                                                        <KakaoRawSection rawText={rawText} />
                                                    );
                                                })()}
                                            </div>
                                        )}
                                        {document.content && !((document.sourceType === 'kakao_expert' || document.sourceType === 'kakao_community') && (document.question || document.answer)) ? (
                                            <ReactMarkdown
                                                remarkPlugins={[remarkGfm]}
                                                rehypePlugins={[rehypeRaw]}
                                                components={MarkdownComponents}
                                            >
                                                {document.content}
                                            </ReactMarkdown>
                                        ) : !((document.sourceType === 'kakao_expert' || document.sourceType === 'kakao_community') && (document.question || document.answer)) ? (
                                            <span className="text-gray-400 italic">내용이 없습니다. 편집 버튼을 눌러 내용을 작성해보세요.</span>
                                        ) : null}

                                        {docType !== 'daily' && document.visibility !== 'private' && (
                                            <>
                                                <hr className="my-8 border-gray-100" />
                                                <div className="not-prose text-sm text-gray-500 mb-8 p-5 bg-gray-50/50 rounded-xl border border-gray-100 shadow-sm">
                                                    <div className="font-bold text-gray-700">작성자: {formatAuthorName(document.authorName)}</div>
                                                    {revisions.length > 0 && (
                                                        <div className="mt-4 pt-4 border-t border-gray-200">
                                                            <div className="font-semibold text-gray-600 mb-3 text-xs">수정 히스토리</div>
                                                            <div className="space-y-1.5 text-xs text-gray-500 font-medium font-mono">
                                                                {[...revisions].reverse().map((rev: any) => (
                                                                    <div key={rev.id} className="flex items-center gap-2 ml-1">
                                                                        <span className="text-gray-300">-</span>
                                                                        <span>
                                                                            {rev.createdAt?.toDate?.()?.toLocaleString('ko-KR')} ({formatAuthorName(rev.authorName)})
                                                                        </span>
                                                                    </div>
                                                                ))}
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>
                                            </>
                                        )}

                                        {/* [NEW] 첨부 파일 섹션 */}
                                        {!isEditing && (
                                            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-8 not-prose">
                                                <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                                                    <span>📎</span> 첨부 파일
                                                    {document.attachments && document.attachments.length > 0 && (
                                                        <span className="text-sm font-normal text-gray-500">({document.attachments.length})</span>
                                                    )}
                                                </h3>

                                                {/* 파일 목록 */}
                                                <div className="space-y-2 mb-6">
                                                    {document.attachments && document.attachments.length > 0 ? (
                                                        [...document.attachments].reverse().map((file) => (
                                                            <div key={file.fileId} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-100 group hover:border-indigo-200 transition-colors">
                                                                <div className="flex items-center gap-3 min-w-0">
                                                                    <div className="w-10 h-10 rounded-lg bg-white flex items-center justify-center text-xl shadow-sm border border-gray-100 shrink-0">
                                                                        {file.type.includes('image') ? '🖼️' :
                                                                            file.type.includes('pdf') ? '📄' :
                                                                                '📁'}
                                                                    </div>
                                                                    <div className="min-w-0 flex-1">
                                                                        <a href={file.url} target="_blank" rel="noopener noreferrer" className="font-medium text-gray-900 hover:text-indigo-600 truncate block hover:underline">
                                                                            {file.name}
                                                                        </a>
                                                                        <div className="text-xs text-gray-500">
                                                                            {(file.uploadedAt && file.uploadedAt.seconds) ? new Date(file.uploadedAt.seconds * 1000).toLocaleDateString() : 'Just now'}
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                {(isAdmin || user?.uid === document.authorId) && (
                                                                    <button
                                                                        onClick={() => handleDeleteAttachment(file.fileId)}
                                                                        className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-full transition-colors opacity-0 group-hover:opacity-100"
                                                                        title="파일 삭제"
                                                                    >
                                                                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                                                        </svg>
                                                                    </button>
                                                                )}
                                                            </div>
                                                        ))
                                                    ) : (
                                                        <div className="text-center py-6 text-sm text-gray-400 bg-gray-50 rounded-lg border border-dashed border-gray-200">
                                                            첨부된 파일이 없습니다.
                                                        </div>
                                                    )}
                                                </div>

                                                {/* 업로드 버튼 */}
                                                {user && userRole !== 'guest' && (
                                                    <div className="mt-4">
                                                        <label className={`inline-flex items-center gap-2 px-4 py-2 bg-white text-gray-700 font-medium rounded-lg border border-gray-200 hover:bg-gray-50 hover:border-gray-300 transition-colors cursor-pointer text-sm shadow-sm ${isUploading ? 'opacity-50 cursor-wait' : ''}`}>
                                                            {isUploading ? (
                                                                <>
                                                                    <svg className="animate-spin h-4 w-4 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                                                    </svg>
                                                                    <span>업로드 중...</span>
                                                                </>
                                                            ) : (
                                                                <>
                                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                                                                    </svg>
                                                                    <span>파일 업로드</span>
                                                                </>
                                                            )}
                                                            <input
                                                                type="file"
                                                                className="hidden"
                                                                onChange={handleFileUpload}
                                                                disabled={isUploading}
                                                            />
                                                        </label>
                                                        <span className="text-xs text-gray-400 ml-2">
                                                            (Max 50MB)
                                                        </span>
                                                    </div>
                                                )}
                                            </div>
                                        )}

                                        {/* AI 관련 문서 추천 */}
                                        <RelatedDocsSidebar documentId={document.id} documentTitle={document.title} />

                                        {/* 기존 백링크 */}
                                        <BacklinksPanel documentId={document.id} documentTitle={document.title} />

                                        {/* 인라인 검토 패널 */}
                                        <InlineReviewPanel docId={document.id} />

                                        {/* 오류 신고 — 최하단 접힌 섹션 */}
                                        {user && userRole !== 'guest' && !isEditing && document.visibility === 'public' && (
                                            <ErrorReportButton docId={document.id} />
                                        )}
                                    </div>
                                </article>
                            )}
                        </div>
                    </div>

                    {/* 자동 임시저장 복구 모달 */}
                    <DraftRecoveryModal
                        isOpen={isDraftRecoveryOpen}
                        onRecover={handleDraftRecover}
                        onDiscard={handleDraftDiscard}
                        draftSavedAt={autoSave.draftData?.savedAt ?? null}
                        currentContent={document?.content ?? ''}
                        draftContent={autoSave.draftData?.content ?? ''}
                    />

                    {/* 편집 이탈 확인 모달 */}
                    <LeaveConfirmModal
                        isOpen={isLeaveConfirmOpen}
                        onSaveAndLeave={handleSaveAndLeave}
                        onDiscardAndLeave={handleDiscardAndLeave}
                        onContinueEditing={handleContinueEditing}
                        isSaving={isSaving}
                    />
                </main >
            </div >

            {/* 변경 이력 모달 */}
            < RevisionHistoryModal
                isOpen={isHistoryModalOpen}
                onClose={() => setIsHistoryModalOpen(false)
                }
                docId={docId}
                onRestore={(content: string, title: string) => {
                    setEditContent(content);
                    setEditTitle(title);
                    handleSave(content, true); // 즉시 저장하여 복원 완료 (isRestore 플래그 전달)
                }}
            />

            {/* 동의 녹취 확인 모달 */}
            <RecordingConsentModal
                isOpen={isConsentModalOpen}
                onClose={() => setIsConsentModalOpen(false)}
                onConsent={() => {
                    setIsConsentModalOpen(false);
                    // 동의 완료 → 녹음 시작 로직 (향후 Gemini Live 연동)
                    toast.success('동의가 확인되었습니다. 녹취를 시작합니다.');
                }}
                documentTitle={document?.title}
            />

            {/* AI 용어 감지 floating window */}
            {!isEditing && (
                <FloatingTermDetection documentId={document.id} documentTitle={document.title} />
            )}

            {/* 상담 녹음 FAB (데일리 노트 전용) */}
            <AudioRecorderButton
                isDailyNote={!!isDailyNote}
                onRecordingComplete={handleRecordingComplete}
            />
        </div >
    );
}
