<div class="profile profile-home">
    {{- with site.Params.profileMode }}
    {{- $heroLine := cond (eq site.Language.Lang "zh") "在这里阅读我的 AI 技术、成长思考与旅行见闻。" "Read my writing on AI technology, personal growth, and travel adventures." -}}
    {{- $statusText := cond (eq site.Language.Lang "zh") "状态：在线探索中" "STATUS: ONLINE & EXPLORING" -}}
    {{- $roleText := cond (eq site.Language.Lang "zh") "AI 创业者 / 开源贡献者 / 数字游民" "AI Entrepreneur / Open Source Contributor / Digital Nomad" -}}
    {{- $startHereText := cond (eq site.Language.Lang "zh") "从哪里开始" "Start Here" -}}
    {{- $aboutMeText := cond (eq site.Language.Lang "zh") "我是谁" "Who I Am" -}}
    {{- $latestPostsText := cond (eq site.Language.Lang "zh") "最近写了什么" "Latest Posts" -}}
    {{- $aiTechLabel := cond (eq site.Language.Lang "zh") "AI / 技术" "AI / Technology" -}}
    {{- $growthLabel := cond (eq site.Language.Lang "zh") "成长 / 生活" "Growth / Life" -}}
    {{- $travelLabel := cond (eq site.Language.Lang "zh") "旅行 / 见闻" "Travel / Exploration" -}}
    {{- $projectsLabel := cond (eq site.Language.Lang "zh") "项目 / 开源" "Projects / Open Source" -}}
    {{- $viewAllText := cond (eq site.Language.Lang "zh") "查看全部 →" "View All →" -}}
    {{- $readingLabel := cond (eq site.Language.Lang "zh") "最近更新" "Recent Updates" -}}
    {{- $localeLabel := cond (eq site.Language.Lang "zh") "所在地" "Based In" -}}
    {{- $statusLabel := cond (eq site.Language.Lang "zh") "状态" "Status" -}}
    {{- $roamingText := cond (eq site.Language.Lang "zh") "漫游中" "ROAMING" -}}
    {{- $locationText := cond (eq site.Language.Lang "zh") "中国 / Remote" "China / Remote" -}}
    {{- /* Get recent pages across all content sections for this language */ -}}
    {{- $allPages := where site.RegularPages "Lang" site.Language.Lang -}}
    {{- $allPages = where $allPages "Kind" "page" -}}
    {{- $recentPages := first 5 ($allPages.ByDate.Reverse) -}}
    <div class="profile_fx profile_fx--grid" aria-hidden="true"></div>
    <div class="profile_fx profile_fx--glow profile_fx--left" aria-hidden="true"></div>
    <div class="profile_fx profile_fx--glow profile_fx--right" aria-hidden="true"></div>
    <div class="profile_shell">
        <section class="profile_hero">
            <div class="profile_copy">
                <div class="profile_status_bar">
                    <a class="profile_status" href="{{ "/about/" | relLangURL }}" title="{{ if eq site.Language.Lang "zh" }}关于我{{ else }}About me{{ end }}">
                        <span class="profile_status__dot"></span>
                        <span>{{ $statusText }}</span>
                    </a>
                    <div class="profile_quick_links">
                        <button class="profile_quick_link" type="button" onclick="triggerQuickAsk(this)" data-question="{{ if eq site.Language.Lang "zh" }}你是谁？介绍一下你自己，附上关于页面链接{{ else }}Who are you? Introduce yourself with a link to your about page{{ end }}" data-page="{{ "/about/" | absLangURL }}">
                            <span class="profile_quick_link__icon">👤</span>
                            <span>{{ $aboutMeText }}</span>
                        </button>
                        <button class="profile_quick_link" type="button" onclick="triggerQuickAsk(this)" data-question="{{ if eq site.Language.Lang "zh" }}你最近写了什么文章？给我推荐几篇，附上链接{{ else }}What have you written recently? Recommend some articles with links{{ end }}" data-page="{{ "#latest-posts" }}">
                            <span class="profile_quick_link__icon">📝</span>
                            <span>{{ $latestPostsText }}</span>
                        </button>
                        <button class="profile_quick_link" type="button" onclick="triggerQuickAsk(this)" data-question="{{ if eq site.Language.Lang "zh" }}新来的读者应该从哪里开始读？推荐入门文章，附上链接{{ else }}Where should a new reader start? Recommend entry-point articles with links{{ end }}" data-page="{{ "#start-here" }}">
                            <span class="profile_quick_link__icon">🚀</span>
                            <span>{{ $startHereText }}</span>
                        </button>
                    </div>
                    <button class="profile_chat_trigger" id="chatTrigger" onclick="toggleChatPanel()" type="button">
                        <span class="profile_chat_trigger__icon">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
                            </svg>
                        </span>
                        <span class="profile_chat_trigger__label">Ask AI</span>
                        <svg class="profile_chat_trigger__chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
                            <path d="M4 6l4 4 4-4" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </button>
                </div>

                <div class="profile_chat_panel" id="chatPanel">
                    <div class="profile_chat_inner">
                        <div class="profile_chat_messages" id="chatMessages">
                            <p class="profile_chat_greeting">// {{ if eq site.Language.Lang "zh" }}有什么想问的？{{ else }}what do you want to know?{{ end }}</p>
                            <div class="profile_chat_hints" id="chatHints">
                                <span class="profile_chat_hint" onclick="fillChatHint(this)">{{ if eq site.Language.Lang "zh" }}最近文章{{ else }}recent posts{{ end }}</span>
                                <span class="profile_chat_hint" onclick="fillChatHint(this)">{{ if eq site.Language.Lang "zh" }}AI 话题{{ else }}ai topics{{ end }}</span>
                                <span class="profile_chat_hint" onclick="fillChatHint(this)">{{ if eq site.Language.Lang "zh" }}总结博客{{ else }}summarize{{ end }}</span>
                            </div>
                        </div>
                        <div class="profile_chat_input_row">
                            <textarea class="profile_chat_input" id="chatInput" rows="1" placeholder="{{ if eq site.Language.Lang "zh" }}问任何问题...{{ else }}ask anything...{{ end }}"></textarea>
                            <button class="profile_chat_send" id="chatSendBtn" onclick="handleChatSend()" aria-label="Send">send →</button>
                        </div>
                    </div>
                </div>

                <h1 class="profile_title">
                    <span class="profile_title__name">Xinwei Xiong</span> <span class="profile_title__accent">(Bear).</span>
                </h1>

                <div class="profile_terminal" aria-live="polite">
                    <span class="profile_terminal__prompt">&gt;</span>
                    <span id="profile-typing-text" data-text="{{ $heroLine }}"></span>
                    <span class="profile_terminal__cursor"></span>
                </div>

                <p class="profile_summary">{{ $roleText }}</p>

                <div class="profile_intro">
                    {{ .subtitle | markdownify }}
                </div>

                {{- partial "social_icons.html" site.Params.socialIcons -}}

                {{- with .buttons }}
                <div class="profile_nav_tags">
                    {{- range . }}
                    <a class="profile_nav_tag" href="{{ trim .url " " }}" rel="noopener noreferrer" title="{{ .name }}">{{ .name }}</a>
                    {{- end }}
                </div>
                {{- end }}
            </div>

            <aside class="profile_sidecard">
                <div class="profile_avatar">
                    {{- if .imageUrl -}}
                    {{- $img := "" }}
                    {{- if not (urls.Parse .imageUrl).IsAbs }}
                        {{- $img = resources.Get .imageUrl }}
                    {{- end }}
                    {{- if $img }}
                        {{- $processableFormats := (slice "jpg" "jpeg" "png" "tif" "bmp" "gif") -}}
                        {{- if hugo.IsExtended -}}
                            {{- $processableFormats = $processableFormats | append "webp" -}}
                        {{- end -}}
                        {{- $prod := (hugo.IsProduction | or (eq site.Params.env "production")) }}
                        {{- if and (in $processableFormats $img.MediaType.SubType) (eq $prod true)}}
                            {{- if (not (and (not .imageHeight) (not .imageWidth))) }}
                                {{- $img = $img.Resize (printf "%dx%d" .imageWidth .imageHeight) }}
                            {{- else if .imageHeight }}
                                {{- $img = $img.Resize (printf "x%d" .imageHeight) }}
                            {{ else if .imageWidth }}
                                {{- $img = $img.Resize (printf "%dx" .imageWidth) }}
                            {{ else }}
                                {{- $img = $img.Resize "150x150" }}
                            {{- end }}
                        {{- end }}
                        <img draggable="false" src="{{ $img.Permalink }}" alt="{{ .imageTitle | default "Xinwei Xiong profile photo" }}" title="{{ .imageTitle }}"
                            height="{{ .imageHeight | default 150 }}" width="{{ .imageWidth | default 150 }}"
                            loading="eager" fetchpriority="high" decoding="async" />
                    {{- else }}
                        <img draggable="false" src="{{ .imageUrl | absURL }}" alt="{{ .imageTitle | default "Xinwei Xiong profile photo" }}" title="{{ .imageTitle }}"
                            height="{{ .imageHeight | default 150 }}" width="{{ .imageWidth | default 150 }}"
                            loading="eager" fetchpriority="high" decoding="async" />
                    {{- end }}
                    {{- end }}
                </div>

                <div class="profile_metrics profile_metrics--grid">
                    <div class="profile_metric">
                        <span class="profile_metric__label">{{ $localeLabel }}</span>
                        <strong class="profile_metric__value">{{ $locationText }}</strong>
                    </div>
                    <div class="profile_metric">
                        <span class="profile_metric__label">{{ $statusLabel }}</span>
                        <strong class="profile_metric__value">{{ $roamingText }}</strong>
                    </div>
                    <div class="profile_metric profile_metric--reading">
                        <span class="profile_metric__label">{{ $readingLabel }}</span>
                        <div class="profile_metric__status">
                            <span class="profile_metric__dot"></span>
                            <strong class="profile_metric__value">{{ $readingLabel }}</strong>
                        </div>
                        {{- if $recentPages }}
                        <div class="profile_recent-posts">
                            {{- range $recentPages }}
                            <a class="profile_recent-post" href="{{ .RelPermalink }}">
                                <span class="profile_recent-post__date">{{ .Date.Format "Jan 2" }}</span>
                                <span class="profile_recent-post__title">{{ .Title | truncate 48 }}</span>
                            </a>
                            {{- end }}
                        </div>
                        {{- else }}
                        <div class="profile_recent-posts">
                            <a class="profile_recent-post" href="{{ "/articles/" | relLangURL }}">
                                <span class="profile_recent-post__title">{{ if eq site.Language.Lang "zh" }}查看所有文章 →{{ else }}View all articles →{{ end }}</span>
                            </a>
                        </div>
                        {{- end }}
                    </div>
                </div>
            </aside>
        </section>

        <section class="profile_bento" id="start-here">
            <article class="profile_panel profile_panel--category profile_panel--ai-tech">
                <div class="profile_panel__header">
                    <span class="profile_panel__icon profile_panel__icon--ai">🤖</span>
                    <h3>{{ $aiTechLabel }}</h3>
                </div>
                <p>{{ if eq site.Language.Lang "zh" }}Kubernetes、Go 语言、AI Agents 与云原生技术实践{{ else }}Kubernetes, Go, AI Agents and Cloud Native engineering{{ end }}</p>
                <a href="{{ "ai-technology/" | relLangURL }}" class="profile_view_all">{{ $viewAllText }}</a>
            </article>

            <article class="profile_panel profile_panel--category profile_panel--growth">
                <div class="profile_panel__header">
                    <span class="profile_panel__icon profile_panel__icon--growth">🌱</span>
                    <h3>{{ $growthLabel }}</h3>
                </div>
                <p>{{ if eq site.Language.Lang "zh" }}年度复盘、认知升级、心流状态与个人成长方法论{{ else }}Annual reviews, cognitive upgrades, flow state and personal growth{{ end }}</p>
                <a href="{{ "growth/" | relLangURL }}" class="profile_view_all">{{ $viewAllText }}</a>
            </article>

            <article class="profile_panel profile_panel--category profile_panel--travel">
                <div class="profile_panel__header">
                    <span class="profile_panel__icon profile_panel__icon--travel">🌍</span>
                    <h3>{{ $travelLabel }}</h3>
                </div>
                <p>{{ if eq site.Language.Lang "zh" }}数字游民生活、9 国 35+ 城市旅行见闻与文化探索{{ else }}Digital nomad life across 9 countries, 35+ cities and cultural exploration{{ end }}</p>
                <a href="{{ "travel/" | relLangURL }}" class="profile_view_all">{{ $viewAllText }}</a>
            </article>

            <article class="profile_panel profile_panel--category profile_panel--projects">
                <div class="profile_panel__header">
                    <span class="profile_panel__icon profile_panel__icon--projects">📦</span>
                    <h3>{{ $projectsLabel }}</h3>
                </div>
                <p>{{ if eq site.Language.Lang "zh" }}OpenIM、OpenKF 等开源项目与 AI 工具实践{{ else }}OpenIM, OpenKF and other open source projects and AI tools{{ end }}</p>
                <a href="{{ "projects/" | relLangURL }}" class="profile_view_all">{{ $viewAllText }}</a>
            </article>
        </section>

        <!-- AI Chat Section - Integrated into status bar above -->

        <!-- Latest Posts Section -->
        <section class="profile_knowledge_grid" id="latest-posts">
            <article class="profile_panel profile_panel--knowledge profile_panel--ai-tech">
                <div class="profile_panel__topline">
                    <div>
                        <h2>AI Technology</h2>
                        <p>{{ if eq site.Language.Lang "zh" }}探索 AI Agents 与系统工程{{ else }}Exploring AI Agents & Engineering{{ end }}</p>
                    </div>
                </div>
                {{- $aiPages := where (where site.RegularPages "Section" "ai-technology") "Lang" site.Language.Lang -}}
                {{- $recentAi := first 3 ($aiPages.ByDate.Reverse) -}}
                <div class="profile_posts">
                    {{- range $index, $page := $recentAi }}
                    <a class="profile_post {{ if eq $index 0 }}profile_post--featured{{ end }}" href="{{ .RelPermalink }}">
                        <span class="profile_post__date">{{ .Date.Format "2006-01-02" }}</span>
                        <strong>{{ .Title }}</strong>
                        {{ if eq $index 0 }}
                        <p class="profile_post__summary">{{ .Description | default .Summary | truncate 80 }}</p>
                        {{ end }}
                    </a>
                    {{- end }}
                    <a href="{{ "ai-technology/" | relLangURL }}" class="profile_view_more">{{ $viewAllText }}</a>
                </div>
            </article>

            <article class="profile_panel profile_panel--knowledge profile_panel--growth-life">
                <div class="profile_panel__topline">
                    <div>
                        <h2>Growth & Life</h2>
                        <p>{{ if eq site.Language.Lang "zh" }}成长复盘与数字游民见闻{{ else }}Personal Growth & Nomad Life{{ end }}</p>
                    </div>
                </div>
                {{- $growthPages := where (where site.RegularPages "Section" "growth") "Lang" site.Language.Lang -}}
                {{- $recentGrowth := first 3 ($growthPages.ByDate.Reverse) -}}
                <div class="profile_posts">
                    {{- range $index, $page := $recentGrowth }}
                    <a class="profile_post {{ if eq $index 0 }}profile_post--featured{{ end }}" href="{{ .RelPermalink }}">
                        <span class="profile_post__date">{{ .Date.Format "2006-01-02" }}</span>
                        <strong>{{ .Title }}</strong>
                        {{ if eq $index 0 }}
                        <p class="profile_post__summary">{{ .Description | default .Summary | truncate 80 }}</p>
                        {{ end }}
                    </a>
                    {{- end }}
                    <a href="{{ "growth/" | relLangURL }}" class="profile_view_more">{{ $viewAllText }}</a>
                </div>
            </article>
        </section>

        <!-- RSS Subscribe Section -->
        <section class="profile_bento" style="margin-top: 24px;">
            <article class="profile_panel profile_panel--rss" style="grid-column: 1 / -1;">
                {{- partial "rss-subscribe.html" . }}
            </article>
        </section>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var target = document.getElementById('profile-typing-text');
            if (!target) return;

            var fullText = target.dataset.text || '';
            var current = 0;
            target.textContent = '';

            var timer = window.setInterval(function () {
                target.textContent = fullText.slice(0, current);
                current += 1;
                if (current > fullText.length) {
                    window.clearInterval(timer);
                }
            }, 42);

            // --- AI Chat Panel ---
            var chatEndpoint = '/.netlify/functions/blog-ai';
            var chatLang = document.documentElement.getAttribute('lang') || 'en';
            if (chatLang.startsWith('zh')) chatLang = 'zh';
            var chatContext = [];
            var CHAT_CTX_KEY = 'profile-chat-context';

            // Load saved context
            try {
                var saved = localStorage.getItem(CHAT_CTX_KEY);
                if (saved) chatContext = JSON.parse(saved);
            } catch(e) {}

            function saveChatContext() {
                try {
                    if (chatContext.length > 20) chatContext = chatContext.slice(-20);
                    localStorage.setItem(CHAT_CTX_KEY, JSON.stringify(chatContext));
                } catch(e) {}
            }

            // Simple markdown to HTML
            function chatMd(text) {
                if (!text) return '';
                var d = document.createElement('div');
                d.textContent = text;
                var h = d.innerHTML;
                h = h.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                     .replace(/\*(.*?)\*/g, '<em>$1</em>')
                     .replace(/`([^`]+)`/g, '<code>$1</code>')
                     .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
                     .replace(/\n/g, '<br>');
                return h;
            }

            var messagesEl = document.getElementById('chatMessages');

            function addChatMsg(content, isUser) {
                var msg = document.createElement('div');
                msg.className = 'profile_chat_msg ' + (isUser ? 'profile_chat_msg--user' : 'profile_chat_msg--ai');
                if (isUser) {
                    msg.textContent = content;
                } else {
                    msg.innerHTML = chatMd(content);
                }
                messagesEl.appendChild(msg);
                messagesEl.scrollTop = messagesEl.scrollHeight;
                return msg;
            }

            function showThinking() {
                var el = document.createElement('div');
                el.className = 'profile_chat_msg profile_chat_msg--ai profile_chat_thinking_msg';
                el.innerHTML = '<span class="profile_chat_dot"></span><span class="profile_chat_dot"></span><span class="profile_chat_dot"></span>';
                messagesEl.appendChild(el);
                messagesEl.scrollTop = messagesEl.scrollHeight;
                return el;
            }

            // Toggle panel
            window.toggleChatPanel = function() {
                var panel = document.getElementById('chatPanel');
                var chevron = document.querySelector('.profile_chat_trigger__chevron');
                panel.classList.toggle('open');
                chevron.classList.toggle('open');
                if (panel.classList.contains('open')) {
                    setTimeout(function() {
                        document.getElementById('chatInput').focus();
                    }, 300);
                }
            };

            // Quick ask from nav buttons
            window.triggerQuickAsk = function(btn) {
                var question = btn.getAttribute('data-question');
                if (!question) return;
                var panel = document.getElementById('chatPanel');
                var chevron = document.querySelector('.profile_chat_trigger__chevron');
                if (!panel.classList.contains('open')) {
                    panel.classList.add('open');
                    chevron && chevron.classList.add('open');
                }
                var input = document.getElementById('chatInput');
                if (input) input.value = question;
                setTimeout(function() { handleChatSend(); }, 200);
            };

            // Auto-resize textarea
            var chatTextarea = document.getElementById('chatInput');
            if (chatTextarea) {
                chatTextarea.addEventListener('input', function() {
                    this.style.height = 'auto';
                    this.style.height = Math.min(this.scrollHeight, 120) + 'px';
                });
                chatTextarea.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        handleChatSend();
                    }
                });
            }

            // Fill hint text and auto-send
            window.fillChatHint = function(el) {
                var input = document.getElementById('chatInput');
                if (input) {
                    input.value = el.textContent;
                    handleChatSend();
                }
            };

            // Handle chat send — real API call
            window.handleChatSend = async function() {
                var input = document.getElementById('chatInput');
                var btn = document.getElementById('chatSendBtn');
                var hints = document.getElementById('chatHints');

                if (!input || !input.value.trim()) return;

                var question = input.value.trim();
                input.value = '';
                input.style.height = 'auto';
                btn.disabled = true;
                if (hints) hints.style.display = 'none';

                addChatMsg(question, true);
                var thinkingEl = showThinking();

                try {
                    var resp = await fetch(chatEndpoint, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            question: question,
                            language: chatLang,
                            context: chatContext
                        })
                    });

                    if (!resp.ok) {
                        if (thinkingEl) thinkingEl.remove();
                        var errData = await resp.json().catch(function() { return {}; });
                        addChatMsg(errData.error || 'Request failed', false);
                        btn.disabled = false;
                        input.focus();
                        return;
                    }

                    var contentType = resp.headers.get('content-type') || '';
                    var answer = '';

                    if (contentType.includes('text/event-stream')) {
                        // Streaming SSE — typewriter effect
                        if (thinkingEl) thinkingEl.remove();
                        var streamMsg = addChatMsg('', false);
                        var reader = resp.body.getReader();
                        var decoder = new TextDecoder();
                        var buf = '';
                        var done = false;
                        while (!done) {
                            var chunk = await reader.read();
                            if (chunk.done) break;
                            buf += decoder.decode(chunk.value, { stream: true });
                            var lines = buf.split('\n');
                            buf = lines.pop();
                            for (var i = 0; i < lines.length; i++) {
                                var line = lines[i];
                                if (!line.startsWith('data: ')) continue;
                                var raw = line.slice(6).trim();
                                if (raw === '[DONE]') { done = true; break; }
                                try {
                                    var parsed = JSON.parse(raw);
                                    if (parsed.delta) {
                                        answer += parsed.delta;
                                        streamMsg.innerHTML = chatMd(answer);
                                        messagesEl.scrollTop = messagesEl.scrollHeight;
                                    }
                                } catch(e) {}
                            }
                        }
                    } else {
                        var data = await resp.json();
                        if (thinkingEl) thinkingEl.remove();
                        answer = data.answer || '';
                        addChatMsg(answer, false);
                    }

                    if (answer) {
                        chatContext.push({ role: 'user', content: question });
                        chatContext.push({ role: 'assistant', content: answer });
                        saveChatContext();
                    }
                } catch(err) {
                    if (thinkingEl) thinkingEl.remove();
                    addChatMsg(chatLang === 'zh' ? '网络连接失败，请稍后重试' : 'Connection failed, please try again', false);
                }
                btn.disabled = false;
                input.focus();
            };
        });
    </script>
    {{- end}}
</div>
