{% extends "layout.html" %}

{% block title %}成员详情 - {{ member.name }}{% endblock %}

{% block extra_css %}
<style>
    .info-label { color: #6c757d; font-weight: normal; width: 120px; display: inline-block; }
    .info-value { color: #212529; font-weight: 500; }
    .detail-section { background: white; border-radius: 8px; padding: 25px; margin-bottom: 20px; box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); }
    .section-title { font-size: 1.1rem; font-weight: bold; border-bottom: 2px solid #f8f9fa; padding-bottom: 10px; margin-bottom: 20px; color: #0d6efd; }
    .relation-card { border-left: 4px solid #198754; background: #f8fff9; padding: 10px 15px; margin-bottom: 10px; border-radius: 4px; }
    
    /* Image Preview in Sidebar */
    .source-image-preview {
        cursor: pointer;
        position: relative;
        overflow: hidden;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        transition: transform 0.2s;
    }
    .source-image-preview:hover {
        transform: scale(1.02);
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    .source-image-preview img {
        width: 100%;
        height: auto;
        display: block;
    }
    .preview-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,0.6);
        color: white;
        padding: 5px;
        text-align: center;
        font-size: 0.8rem;
        opacity: 0;
        transition: opacity 0.2s;
    }
    .source-image-preview:hover .preview-overlay {
        opacity: 1;
    }

    /* Modal Image Viewer */
    .modal-image-container {
        height: 80vh;
        display: flex;
        flex-direction: column;
    }
    .image-toolbar {
        background: #e9ecef;
        padding: 5px 10px;
        border-bottom: 1px solid #dee2e6;
        display: flex;
        gap: 10px;
        align-items: center;
        flex-wrap: wrap;
    }
    .image-viewer { 
        flex: 1; 
        border: 1px solid #ccc; 
        background: #f0f0f0; 
        overflow: hidden; 
        text-align: center; 
        position: relative; 
        cursor: grab;
        user-select: none;
    }
    .image-viewer:active {
        cursor: grabbing;
    }
    .image-wrapper {
        display: inline-block;
        transition: transform 0.2s ease-out;
        transform-origin: center center;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .image-wrapper img {
        max-width: 100%;
        max-height: 100%; /* Fit within viewer initially */
        display: block;
        pointer-events: none;
        user-select: none;
        transition: filter 0.2s;
        box-shadow: 0 0 20px rgba(0,0,0,0.1);
    }
    /* 放大镜样式 - Optional if we want it in modal too */
    .magnifier-glass {
        position: absolute;
        border: 3px solid #000;
        border-radius: 50%;
        cursor: none;
        width: 150px;
        height: 150px;
        box-shadow: 0 0 10px rgba(0,0,0,0.5);
        display: none;
        z-index: 1000;
        background-repeat: no-repeat;
        background-color: white;
        pointer-events: none;
    }
</style>
{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="bi bi-person-badge"></i> {{ member.name }} 的个人详情</h2>
        <div class="btn-group">
            <a href="{{ url_for('edit_member', member_id=member.id) }}" class="btn btn-primary">
                <i class="bi bi-pencil"></i> 编辑信息
            </a>
            <a href="{{ url_for('members') }}" class="btn btn-outline-secondary">返回列表</a>
        </div>
    </div>

    <div class="row">
        <!-- 基本与核心信息 -->
        <div class="col-md-8">
            <div class="detail-section">
                <div class="section-title">基本信息</div>
                <div class="row g-3">
                    <div class="col-md-6">
                        <span class="info-label">姓名（繁体）：</span>
                        <span class="info-value">{{ member.name }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">姓名（简体）：</span>
                        <span class="info-value">{{ member.simplified_name or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">性别：</span>
                        <span class="info-value">{{ '男' if member.sex == 1 else '女' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">曾用名：</span>
                        <span class="info-value">{{ member.former_name or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">幼名/乳名：</span>
                        <span class="info-value">{{ member.childhood_name or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">出生日期：</span>
                        <span class="info-value">{{ member.birthday_str or '未知' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">民族：</span>
                        <span class="info-value">{{ member.nation or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">状态：</span>
                        <span class="info-value">
                            {% if member.is_pass_away == 1 %}
                                <span class="text-danger">已故</span>
                            {% else %}
                                <span class="text-success">健在</span>
                            {% endif %}
                        </span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">婚姻状况：</span>
                        <span class="info-value">
                            {% set marital_map = {0: '未知', 1: '未婚', 2: '已婚', 3: '离异/丧偶'} %}
                            {{ marital_map.get(member.marital_status, '未知') }}
                        </span>
                    </div>
                </div>

                <div class="section-title mt-4">谱系资料</div>
                <div class="row g-3">
                    <div class="col-md-6">
                        <span class="info-label">字辈：</span>
                        <span class="info-value">{{ member.name_word or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">堂内排行：</span>
                        <span class="info-value">{{ member.family_rank or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">世系世代：</span>
                        <span class="info-value">{{ member.name_word_generation or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">名号/封号：</span>
                        <span class="info-value">{{ member.name_title or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">分房/堂号：</span>
                        <span class="info-value">{{ member.branch_family_hall or '-' }}</span>
                    </div>
                    <div class="col-md-12">
                        <span class="info-label">聚居地：</span>
                        <span class="info-value">{{ member.cluster_place or '-' }}</span>
                    </div>
                </div>

                <div class="section-title mt-4">联系与地址</div>
                <div class="row g-3">
                    <div class="col-md-6">
                        <span class="info-label">手机号：</span>
                        <span class="info-value">{{ member.phone or '-' }}</span>
                    </div>
                    <div class="col-md-6">
                        <span class="info-label">微信号：</span>
                        <span class="info-value">{{ member.wechat_account or '-' }}</span>
                    </div>
                    <div class="col-md-12">
                        <span class="info-label">现居住址：</span>
                        <span class="info-value">{{ member.residential_address or '-' }}</span>
                    </div>
                </div>
            </div>

            <div class="detail-section">
                <div class="section-title">个人履历与成就</div>
                <div class="mb-4">
                    <label class="info-label d-block mb-2">标签：</label>
                    <div class="p-3 bg-light rounded">{{ member.tags or '暂无' }}</div>
                </div>
                <div class="mb-4">
                    <label class="info-label d-block mb-2">人员备注：</label>
                    <div class="p-3 bg-light rounded">{{ member.notes or '暂无' }}</div>
                </div>
                <div class="mb-4">
                    <label class="info-label d-block mb-2">职业背景：</label>
                    <div class="p-3 bg-light rounded">{{ member.occupation or '暂无信息' }}</div>
                </div>
                <div class="mb-4">
                    <label class="info-label d-block mb-2">教育经历：</label>
                    <div class="p-3 bg-light rounded">{{ member.educational or '暂无信息' }}</div>
                </div>
                <div>
                    <label class="info-label d-block mb-2">个人成就：</label>
                    <div class="p-3 bg-light rounded">{{ member.personal_achievements or '暂无信息' }}</div>
                </div>
            </div>
        </div>

        <!-- 关系信息与原图 -->
        <div class="col-md-4">
            
            {% if member.source_image_url %}
            <div class="detail-section">
                <div class="section-title">来源原图</div>
                <div class="source-image-preview" onclick="openImageViewer()">
                    <img src="{{ member.source_image_url }}" alt="来源家谱">
                    <div class="preview-overlay">
                        <i class="bi bi-arrows-fullscreen"></i> 点击查看大图 (第{{ member.source_page }}页)
                    </div>
                </div>
            </div>
            {% endif %}

            <div class="detail-section">
                <div class="section-title">家族关系</div>
                
                <h6 class="fw-bold mb-3"><i class="bi bi-arrow-up-circle me-1"></i> 尊辈/关联人</h6>
                {% for p in parents %}
                <div class="relation-card">
                    <div class="d-flex justify-content-between align-items-center">
                        <a href="{{ url_for('member_detail', member_id=p.id) }}" class="text-decoration-none fw-bold">
                            {{ p.name }}
                        </a>
                        <span class="badge bg-success small">
                            {% set rel_map = {1: '父亲', 2: '母亲', 10: '配偶', 11: '兄弟', 12: '姐妹'} %}
                            {{ rel_map.get(p.relation_type, '关联人') }}
                        </span>
                    </div>
                </div>
                {% endfor %}
                {% if not parents %}
                <p class="text-muted small">暂无上层关系记录</p>
                {% endif %}

                <h6 class="fw-bold mt-4 mb-3"><i class="bi bi-arrow-down-circle me-1"></i> 子嗣/晚辈</h6>
                {% for c in children %}
                <div class="relation-card" style="border-left-color: #0d6efd; background: #f0f7ff;">
                    <div class="d-flex justify-content-between align-items-center">
                        <a href="{{ url_for('member_detail', member_id=c.id) }}" class="text-decoration-none fw-bold">
                            {{ c.name }}
                        </a>
                        <span class="badge bg-primary small">
                            {% set rel_map = {1: '子女', 2: '子女', 10: '配偶', 11: '兄弟', 12: '姐妹'} %}
                            {{ rel_map.get(c.relation_type, '后辈') }}
                        </span>
                    </div>
                </div>
                {% endfor %}
                {% if not children %}
                <p class="text-muted small">暂无下层关系记录</p>
                {% endif %}
            </div>

            <div class="detail-section text-center">
                <div class="section-title">系统操作</div>
                <div class="small text-muted mb-3">
                    记录创建于：{{ member.create_time }}<br>
                    最后修改：{{ member.modified_time }}
                </div>
                <button class="btn btn-sm btn-outline-danger w-100" onclick="confirmDelete()">
                    <i class="bi bi-trash"></i> 删除此成员
                </button>
                <form id="deleteForm" action="{{ url_for('delete_member', member_id=member.id) }}" method="POST" style="display: none;"></form>
            </div>
        </div>
    </div>
</div>

<!-- Image Viewer Modal -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content bg-light">
            <div class="modal-header py-2">
                <h5 class="modal-title fs-6"><i class="bi bi-image"></i> 来源扫描件查看 - 第 {{ member.source_page }} 页</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-0 modal-image-container">
                <div class="image-toolbar">
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary" onclick="rotateImage(-90)" title="左旋90°"><i class="bi bi-arrow-counterclockwise"></i></button>
                        <button type="button" class="btn btn-outline-secondary" onclick="rotateImage(90)" title="右旋90°"><i class="bi bi-arrow-clockwise"></i></button>
                    </div>
                    <div class="d-flex align-items-center gap-2 mx-3 border-start border-end px-3">
                        <i class="bi bi-brightness-high" title="亮度"></i>
                        <input type="range" class="form-range" min="50" max="150" value="100" id="brightnessRange" oninput="updateImageFilter()" style="width: 80px;">
                        <i class="bi bi-circle-half ms-2" title="对比度"></i>
                        <input type="range" class="form-range" min="50" max="200" value="100" id="contrastRange" oninput="updateImageFilter()" style="width: 80px;">
                        <button class="btn btn-link btn-sm text-decoration-none py-0" onclick="resetFilters()">重置</button>
                    </div>
                    <div class="form-check form-switch ms-auto mb-0" title="开启后鼠标悬停图片可局部放大">
                        <input class="form-check-input" type="checkbox" id="magnifierSwitch">
                        <label class="form-check-label small" for="magnifierSwitch">🔍 放大镜</label>
                    </div>
                </div>
                <div class="image-viewer shadow-inner" id="viewer">
                    <div id="magnifier" class="magnifier-glass"></div>
                    <div id="imageWrapper" class="image-wrapper">
                        {% if member.source_image_url %}
                            <img id="refImage" src="{{ member.source_image_url }}" alt="家谱图片" draggable="false">
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    function confirmDelete() {
        if(confirm('确定要删除此成员吗？\n这将同时删除其所有关联关系记录！')) {
            document.getElementById('deleteForm').submit();
        }
    }

    function openImageViewer() {
        var myModal = new bootstrap.Modal(document.getElementById('imageModal'));
        myModal.show();
        // Reset state when opening
        resetFilters();
    }

    // --- Image Viewer Logic (Reused from add_member) ---
    // Image State
    let imgRotation = 0;
    let imgBrightness = 100;
    let imgContrast = 100;
    
    // Dragging State
    let isDragging = false;
    let hasDragged = false;
    let startX = 0, startY = 0;
    let currentX = 0, currentY = 0; // Relative to center

    // Zoom State
    let isZoomedIn = false;
    const ZOOM_LEVEL = 2.0;

    // Elements
    const viewer = document.getElementById('viewer');
    const magnifier = document.getElementById('magnifier');
    const magnifierSwitch = document.getElementById('magnifierSwitch');
    const imageWrapper = document.getElementById('imageWrapper');
    const refImage = document.getElementById('refImage');
    
    // Initialize Dragging and Zooming
    if (imageWrapper) {
        // Center initial position logic is handled by CSS (top 50% left 50% translate -50%)
        
        viewer.style.cursor = 'zoom-in';

        viewer.addEventListener('mousedown', (e) => {
            if (e.target.closest('.image-toolbar') || e.target.closest('.magnifier-glass')) return;
            isDragging = true;
            hasDragged = false;
            startX = e.clientX;
            startY = e.clientY;
            
            viewer.style.cursor = 'grabbing';
            e.preventDefault(); 
        });
        
        window.addEventListener('mousemove', (e) => {
            if (!isDragging) return;
            
            const dx = e.clientX - startX;
            const dy = e.clientY - startY;
            
            if (Math.abs(dx) > 2 || Math.abs(dy) > 2) {
                hasDragged = true;
            }

            currentX += dx;
            currentY += dy;
            
            startX = e.clientX;
            startY = e.clientY;
            
            updateImageTransform();
        });
        
        window.addEventListener('mouseup', (e) => {
            if (isDragging) {
                isDragging = false;
                viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
                
                if (!hasDragged && viewer.contains(e.target)) {
                    toggleZoom();
                }
            }
        });
    }

    function toggleZoom() {
        isZoomedIn = !isZoomedIn;
        if (!isZoomedIn) {
            currentX = 0;
            currentY = 0;
        }
        updateImageTransform();
        viewer.style.cursor = isZoomedIn ? 'grab' : 'zoom-in';
    }
    
    // Magnifier Logic
    viewer.addEventListener('mousemove', function(e) {
        if (!magnifierSwitch.checked) {
            magnifier.style.display = 'none';
            return;
        }
        
        if (isDragging) {
             magnifier.style.display = 'none';
             return;
        }
        
        if (!refImage) return;

        const rect = refImage.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        if (x < 0 || x > rect.width || y < 0 || y > rect.height) {
            magnifier.style.display = 'none';
            return;
        }

        magnifier.style.display = 'block';
        
        const glassOffset = 20;
        const viewerRect = viewer.getBoundingClientRect();
        magnifier.style.left = (e.clientX - viewerRect.left + glassOffset) + 'px';
        magnifier.style.top = (e.clientY - viewerRect.top + glassOffset) + 'px';
        
        const zoom = 2.5;
        magnifier.style.backgroundImage = `url('${refImage.src}')`;
        magnifier.style.backgroundSize = `${rect.width * zoom}px ${rect.height * zoom}px`;
        magnifier.style.backgroundPosition = `-${x * zoom - 75}px -${y * zoom - 75}px`; 
    });

    function rotateImage(deg) {
        imgRotation = (imgRotation + deg) % 360;
        updateImageTransform();
    }
    
    function updateImageFilter() {
        imgBrightness = document.getElementById('brightnessRange').value;
        imgContrast = document.getElementById('contrastRange').value;
        applyImageFilters();
    }
    
    function resetFilters() {
        imgRotation = 0;
        imgBrightness = 100;
        imgContrast = 100;
        currentX = 0;
        currentY = 0;
        isZoomedIn = false;
        
        document.getElementById('brightnessRange').value = 100;
        document.getElementById('contrastRange').value = 100;
        if(magnifierSwitch) magnifierSwitch.checked = false;
        
        updateImageTransform();
        applyImageFilters();
        if(viewer) viewer.style.cursor = 'zoom-in';
    }
    
    function updateImageTransform() {
        if (imageWrapper) {
            const scale = isZoomedIn ? ZOOM_LEVEL : 1;
            imageWrapper.style.transform = `translate(calc(-50% + ${currentX}px), calc(-50% + ${currentY}px)) rotate(${imgRotation}deg) scale(${scale})`;
        }
    }
    
    function applyImageFilters() {
        if (refImage) {
            refImage.style.filter = `brightness(${imgBrightness}%) contrast(${imgContrast}%)`;
        }
    }
</script>
{% endblock %}
