"use client";

import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { Palette, Brain, UserCircle, Activity, Check, Save, Upload, Sun, Moon, ImageIcon, X, ZoomIn, ZoomOut, RotateCcw, Move, ChevronDown, ChevronRight, ChevronLeft, Server, Database, Bot, Type } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { cn } from "@/lib/utils";
import { API_BASE_URL } from "@/lib/config";
import {
  ACCENT_PRESETS,
  DARK_TONES,
  LIGHT_TONES,
  loadTheme,
  saveTheme,
  applyTheme,
  type AccentColor,
  type ThemeMode,
  type BackgroundTone,
} from "@/lib/stores/theme";
import { loadProfile, loadProfileFromServer, saveProfile, type UserProfile } from "@/lib/stores/profile";
import { fetchLLMSettings, updateLLMSettings, checkHealth, type LLMSettings, type HealthResult } from "@/lib/api/settings";
import { fetchMemorySettings, updateMemorySettings, type MemorySettings } from "@/lib/api/memory";

// --- Provider Model Catalog (2026-02 verified) ---
const MODEL_CATALOG = [
  {
    provider: "Google Gemini",
    envKey: "GOOGLE_API_KEY",
    models: [
      { label: "Gemini 3 Pro (Preview)", model: "gemini/gemini-3-pro-preview" },
      { label: "Gemini 3 Flash (Preview)", model: "gemini/gemini-3-flash-preview" },
      { label: "Gemini 2.5 Pro", model: "gemini/gemini-2.5-pro" },
      { label: "Gemini 2.5 Flash", model: "gemini/gemini-2.5-flash" },
      { label: "Gemini 2.5 Flash Lite", model: "gemini/gemini-2.5-flash-lite" },
      { label: "Gemini 2.0 Flash", model: "gemini/gemini-2.0-flash" },
      { label: "Gemini 2.0 Flash Lite", model: "gemini/gemini-2.0-flash-lite" },
      { label: "Gemini 1.5 Pro", model: "gemini/gemini-1.5-pro" },
      { label: "Gemini 1.5 Flash", model: "gemini/gemini-1.5-flash" },
    ],
  },
  {
    provider: "OpenAI",
    envKey: "OPENAI_API_KEY",
    models: [
      { label: "GPT-5", model: "openai/gpt-5" },
      { label: "GPT-5 Mini", model: "openai/gpt-5-mini" },
      { label: "GPT-4.1", model: "openai/gpt-4.1" },
      { label: "GPT-4.1 Mini", model: "openai/gpt-4.1-mini" },
      { label: "GPT-4o", model: "openai/gpt-4o" },
      { label: "GPT-4o Mini", model: "openai/gpt-4o-mini" },
      { label: "o3", model: "openai/o3" },
      { label: "o3 Mini", model: "openai/o3-mini" },
      { label: "o4 Mini", model: "openai/o4-mini" },
    ],
  },
  {
    provider: "Anthropic",
    envKey: "ANTHROPIC_API_KEY",
    models: [
      { label: "Claude Opus 4.6", model: "anthropic/claude-opus-4-6" },
      { label: "Claude Opus 4.5", model: "anthropic/claude-opus-4-5" },
      { label: "Claude Sonnet 4.5", model: "anthropic/claude-sonnet-4-5-20250929" },
      { label: "Claude Sonnet 4", model: "anthropic/claude-sonnet-4-20250514" },
      { label: "Claude Sonnet 4.6", model: "anthropic/claude-sonnet-4-6" },
      { label: "Claude Haiku 4.5", model: "anthropic/claude-haiku-4-5-20251001" },
    ],
  },
  {
    provider: "xAI Grok",
    envKey: "XAI_API_KEY",
    models: [
      { label: "Grok 4.2", model: "xai/grok-4-2" },
      { label: "Grok 4.1 Fast (Reasoning)", model: "xai/grok-4-1-fast-reasoning" },
      { label: "Grok 4.1 Fast (Non-reasoning)", model: "xai/grok-4-1-fast-non-reasoning" },
      { label: "Grok 4 Fast (Reasoning)", model: "xai/grok-4-fast-reasoning" },
      { label: "Grok 4 Fast (Non-reasoning)", model: "xai/grok-4-fast-non-reasoning" },
      { label: "Grok 4 (0709)", model: "xai/grok-4-0709" },
      { label: "Grok 3", model: "xai/grok-3" },
      { label: "Grok 3 Mini", model: "xai/grok-3-mini" },
      { label: "Grok Code Fast", model: "xai/grok-code-fast-1" },
    ],
  },
  {
    provider: "OpenRouter",
    envKey: "OPENROUTER_API_KEY",
    models: [
      { label: "GLM 5.0", model: "openrouter/z-ai/glm-5-20260211" },
      { label: "GLM 4.7", model: "openrouter/z-ai/glm-4.7-20251222" },
      { label: "GLM 4.7 Flash", model: "openrouter/z-ai/glm-4.7-flash-20260119" },
      { label: "Kimi K2", model: "openrouter/moonshotai/kimi-k2" },
      { label: "MiniMax M1", model: "openrouter/minimax/minimax-m1" },
    ],
  },
  {
    provider: "Custom / Self-hosted",
    envKey: "",
    models: [
      { label: "Hosted vLLM (사내 서버)", model: "openai/" },
      { label: "Ollama (로컬)", model: "ollama/" },
    ],
  },
];

type Section = null | "theme" | "llm" | "memory" | "profile" | "status";

export default function SettingsPage() {
  const [activeSection, setActiveSection] = useState<Section>(null);

  // --- Browser history sync for drill-down navigation ---
  const openSection = useCallback((section: NonNullable<Section>) => {
    setActiveSection(section);
    window.history.pushState({ section }, "");
  }, []);

  const goBack = useCallback(() => {
    window.history.back();
  }, []);

  useEffect(() => {
    // Restore section from history state on mount/refresh
    const section = window.history.state?.section ?? null;
    if (section) setActiveSection(section);
  }, []);

  useEffect(() => {
    const handlePopState = (e: PopStateEvent) => {
      setActiveSection(e.state?.section ?? null);
    };
    window.addEventListener("popstate", handlePopState);
    return () => window.removeEventListener("popstate", handlePopState);
  }, []);

  // --- Theme ---
  const [accent, setAccent] = useState<AccentColor>("amber");
  const [mode, setMode] = useState<ThemeMode>("dark");
  const [tone, setTone] = useState<BackgroundTone>("default");
  const [showBlobs, setShowBlobs] = useState(true);
  const [chatBgImage, setChatBgImage] = useState("/rubber-track.png");
  const [chatBgOpacity, setChatBgOpacity] = useState(0.3);
  const [chatBgScale, setChatBgScale] = useState(1.1);
  const [chatBgPosX, setChatBgPosX] = useState(50);
  const [chatBgPosY, setChatBgPosY] = useState(50);
  const bgImageInputRef = useRef<HTMLInputElement>(null);
  const previewRef = useRef<HTMLDivElement>(null);
  const [previewDragging, setPreviewDragging] = useState(false);
  const previewDragStart = useRef({ x: 0, y: 0, posX: 50, posY: 50 });

  // --- LLM ---
  const [llm, setLlm] = useState<LLMSettings | null>(null);
  const [llmModel, setLlmModel] = useState("");
  const [llmApiBase, setLlmApiBase] = useState("");
  const [llmApiKey, setLlmApiKey] = useState("");
  const [llmTemp, setLlmTemp] = useState(0.7);
  const [llmMaxTokens, setLlmMaxTokens] = useState(4096);
  const [llmSystemPrompt, setLlmSystemPrompt] = useState("");
  const [llmSaving, setLlmSaving] = useState(false);
  const [llmSaved, setLlmSaved] = useState(false);

  // --- Profile ---
  const [profile, setProfile] = useState<UserProfile>({ name: "", avatar: "", platformName: "Track Platform", platformSubtitle: "Nexus System", botName: "Nexus Platform Core", botAvatar: "" });
  const [profileSaved, setProfileSaved] = useState(false);
  const avatarInputRef = useRef<HTMLInputElement>(null);
  const botAvatarInputRef = useRef<HTMLInputElement>(null);

  // --- Health ---
  const [health, setHealth] = useState<HealthResult | null>(null);
  const [checking, setChecking] = useState(false);

  // --- Memory ---
  const [memSettings, setMemSettings] = useState<MemorySettings | null>(null);
  const [memLoaded, setMemLoaded] = useState(false);
  const [memSaving, setMemSaving] = useState(false);
  const [memSaved, setMemSaved] = useState(false);

  // --- Model Selector ---
  const [openProviders, setOpenProviders] = useState<Set<string>>(new Set());

  // Load initial state
  useEffect(() => {
    const theme = loadTheme();
    setAccent(theme.accentColor);
    setMode(theme.mode);
    setTone(theme.tone);
    setShowBlobs(theme.showBlobs);
    setChatBgImage(theme.chatBgImage);
    setChatBgOpacity(theme.chatBgOpacity);
    setChatBgScale(theme.chatBgScale);
    setChatBgPosX(theme.chatBgPositionX);
    setChatBgPosY(theme.chatBgPositionY);

    setProfile(loadProfile()); // 캐시에서 즉시 표시
    loadProfileFromServer().then(setProfile).catch(() => {}); // 서버에서 최신 로드

    fetchLLMSettings().then((s) => {
      setLlm(s);
      setLlmModel(s.model);
      setLlmApiBase(s.api_base || "");
      setLlmApiKey("");
      setLlmTemp(s.temperature);
      setLlmMaxTokens(s.max_tokens);
      setLlmSystemPrompt(s.system_prompt);
    }).catch(() => {});

    checkHealth().then(setHealth).catch(() => {});
    fetchMemorySettings().then(setMemSettings).catch(() => {}).finally(() => setMemLoaded(true));
  }, []);

  // --- Theme handlers ---
  const applyAndSave = (updates: Partial<{
    accentColor: AccentColor; mode: ThemeMode; tone: BackgroundTone; showBlobs: boolean;
    chatBgImage: string; chatBgOpacity: number; chatBgScale: number; chatBgPositionX: number; chatBgPositionY: number;
  }>) => {
    const next = {
      accentColor: accent, mode, tone, showBlobs,
      chatBgImage, chatBgOpacity, chatBgScale,
      chatBgPositionX: chatBgPosX, chatBgPositionY: chatBgPosY,
      ...updates,
    };
    if (updates.accentColor) setAccent(updates.accentColor);
    if (updates.mode) setMode(updates.mode);
    if (updates.tone !== undefined) setTone(updates.tone);
    if (updates.showBlobs !== undefined) setShowBlobs(updates.showBlobs);
    if (updates.chatBgImage !== undefined) setChatBgImage(updates.chatBgImage);
    if (updates.chatBgOpacity !== undefined) setChatBgOpacity(updates.chatBgOpacity);
    if (updates.chatBgScale !== undefined) setChatBgScale(updates.chatBgScale);
    if (updates.chatBgPositionX !== undefined) setChatBgPosX(updates.chatBgPositionX);
    if (updates.chatBgPositionY !== undefined) setChatBgPosY(updates.chatBgPositionY);
    saveTheme(next);
    applyTheme(next);
    window.dispatchEvent(new Event("theme-change"));
  };

  // --- Preview drag handlers ---
  const handlePreviewDragStart = (e: React.MouseEvent) => {
    e.preventDefault();
    setPreviewDragging(true);
    previewDragStart.current = { x: e.clientX, y: e.clientY, posX: chatBgPosX, posY: chatBgPosY };
  };

  useEffect(() => {
    if (!previewDragging) return;
    const handleMove = (e: MouseEvent) => {
      const container = previewRef.current;
      if (!container) return;
      const rect = container.getBoundingClientRect();
      const dx = e.clientX - previewDragStart.current.x;
      const dy = e.clientY - previewDragStart.current.y;
      const pctX = (dx / rect.width) * 100;
      const pctY = (dy / rect.height) * 100;
      const newX = Math.max(0, Math.min(100, previewDragStart.current.posX - pctX));
      const newY = Math.max(0, Math.min(100, previewDragStart.current.posY - pctY));
      applyAndSave({ chatBgPositionX: newX, chatBgPositionY: newY });
    };
    const handleUp = () => setPreviewDragging(false);
    window.addEventListener("mousemove", handleMove);
    window.addEventListener("mouseup", handleUp);
    return () => {
      window.removeEventListener("mousemove", handleMove);
      window.removeEventListener("mouseup", handleUp);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [previewDragging]);

  // --- LLM handlers ---
  const handleLLMSave = async () => {
    setLlmSaving(true);
    try {
      const updates: Partial<LLMSettings> = {
        model: llmModel,
        api_base: llmApiBase || null,
        temperature: llmTemp,
        max_tokens: llmMaxTokens,
        system_prompt: llmSystemPrompt,
      };
      if (llmApiKey) {
        updates.api_key = llmApiKey;
      } else if (!llmApiBase) {
        updates.api_key = null;
      }
      const saved = await updateLLMSettings(updates);
      setLlm(saved);
      setLlmSaved(true);
      setTimeout(() => setLlmSaved(false), 2000);
    } catch (err) {
      console.error("Failed to save LLM settings:", err);
    } finally {
      setLlmSaving(false);
    }
  };

  const toggleProvider = (provider: string) => {
    setOpenProviders((prev) => {
      const next = new Set(prev);
      if (next.has(provider)) next.delete(provider);
      else next.add(provider);
      return next;
    });
  };

  // --- Profile handlers ---
  const handleAvatarSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const dataUrl = reader.result as string;
      setProfile((p) => ({ ...p, avatar: dataUrl }));
    };
    reader.readAsDataURL(file);
    e.target.value = "";
  };

  const handleBotAvatarSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const dataUrl = reader.result as string;
      setProfile((p) => ({ ...p, botAvatar: dataUrl }));
    };
    reader.readAsDataURL(file);
    e.target.value = "";
  };

  const handleProfileSave = async () => {
    try {
      await saveProfile(profile);
      setProfileSaved(true);
      window.dispatchEvent(new Event("profile-change"));
      setTimeout(() => setProfileSaved(false), 2000);
    } catch (e) {
      console.error("Failed to save profile:", e);
    }
  };

  // --- Memory handlers ---
  const handleMemorySave = async () => {
    if (!memSettings) return;
    setMemSaving(true);
    try {
      const saved = await updateMemorySettings(memSettings);
      setMemSettings(saved);
      setMemSaved(true);
      setTimeout(() => setMemSaved(false), 2000);
    } catch (err) {
      console.error("Failed to save memory settings:", err);
    } finally {
      setMemSaving(false);
    }
  };

  // --- Health ---
  const handleHealthCheck = useCallback(async () => {
    setChecking(true);
    const ok = await checkHealth();
    setHealth(ok);
    setChecking(false);
  }, []);

  // --- Section header with back button ---
  const SectionHeader = ({ title, subtitle }: { title: string; subtitle: string }) => (
    <div className="flex items-center gap-4 mb-8">
      <Button
        variant="ghost"
        size="icon"
        className="h-10 w-10 rounded-2xl border border-foreground/10 bg-foreground/5 hover:bg-foreground/10 shrink-0"
        onClick={goBack}
      >
        <ChevronLeft className="w-5 h-5" />
      </Button>
      <div>
        <h2 className="text-2xl font-black uppercase tracking-tight">{title}</h2>
        <p className="text-[10px] text-muted-foreground font-bold uppercase tracking-widest">{subtitle}</p>
      </div>
    </div>
  );

  // --- Menu card summaries ---
  const llmSummary = llm?.model || "Not configured";
  const themeSummary = `${mode === "dark" ? "Dark" : "Light"} / ${accent}`;
  const memorySummary = memSettings ? (memSettings.enabled ? `Active (${memSettings.max_memories} max)` : "Disabled") : (memLoaded ? "Unavailable" : "Loading...");
  const profileSummary = [profile.name, profile.platformName].filter(Boolean).join(" / ") || "Not set";
  const statusSummary = health?.server === "ok" ? (health.llm_connected ? "All systems ok" : "LLM disconnected") : "Unknown";

  // ===== MAIN MENU =====
  if (activeSection === null) {
    return (
      <div className="h-full overflow-y-auto p-10 bg-background relative">
        <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />

        <div className="relative flex flex-col gap-4 mb-10">
          <div className="flex items-center gap-4">
            <div className="w-2 h-10 bg-primary" />
            <h1 className="text-4xl font-black uppercase tracking-tighter text-foreground">Settings</h1>
          </div>
          <p className="text-muted-foreground text-sm font-bold uppercase tracking-[0.1em] ml-6">
            Platform Configuration
          </p>
        </div>

        <div className="relative max-w-2xl grid gap-3">
          {/* Theme */}
          <button
            onClick={() => openSection("theme")}
            className="group flex items-center gap-5 p-5 rounded-2xl border border-foreground/5 bg-foreground/[0.02] hover:bg-foreground/5 hover:border-foreground/10 transition-all duration-200 text-left"
          >
            <div className="p-3.5 bg-foreground/5 rounded-2xl border border-foreground/10 group-hover:bg-primary/10 group-hover:border-primary/20 transition-colors">
              <Palette className="w-5 h-5 text-primary" />
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-sm font-black uppercase tracking-wider">Theme & Appearance</h3>
              <p className="text-xs text-muted-foreground mt-0.5 truncate">{themeSummary}</p>
            </div>
            <ChevronRight className="w-5 h-5 text-muted-foreground/30 group-hover:text-foreground/50 transition-colors shrink-0" />
          </button>

          {/* LLM */}
          <button
            onClick={() => openSection("llm")}
            className="group flex items-center gap-5 p-5 rounded-2xl border border-foreground/5 bg-foreground/[0.02] hover:bg-foreground/5 hover:border-foreground/10 transition-all duration-200 text-left"
          >
            <div className="p-3.5 bg-foreground/5 rounded-2xl border border-foreground/10 group-hover:bg-primary/10 group-hover:border-primary/20 transition-colors">
              <Brain className="w-5 h-5 text-primary" />
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-sm font-black uppercase tracking-wider">LLM Configuration</h3>
              <p className="text-xs text-muted-foreground font-mono mt-0.5 truncate">{llmSummary}</p>
            </div>
            <ChevronRight className="w-5 h-5 text-muted-foreground/30 group-hover:text-foreground/50 transition-colors shrink-0" />
          </button>

          {/* Memory */}
          <button
            onClick={() => openSection("memory")}
            className="group flex items-center gap-5 p-5 rounded-2xl border border-foreground/5 bg-foreground/[0.02] hover:bg-foreground/5 hover:border-foreground/10 transition-all duration-200 text-left"
          >
            <div className="p-3.5 bg-foreground/5 rounded-2xl border border-foreground/10 group-hover:bg-purple-500/10 group-hover:border-purple-500/20 transition-colors">
              <Database className="w-5 h-5 text-purple-400" />
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-sm font-black uppercase tracking-wider">Memory</h3>
              <p className="text-xs text-muted-foreground mt-0.5 truncate">{memorySummary}</p>
            </div>
            <ChevronRight className="w-5 h-5 text-muted-foreground/30 group-hover:text-foreground/50 transition-colors shrink-0" />
          </button>

          {/* Profile */}
          <button
            onClick={() => openSection("profile")}
            className="group flex items-center gap-5 p-5 rounded-2xl border border-foreground/5 bg-foreground/[0.02] hover:bg-foreground/5 hover:border-foreground/10 transition-all duration-200 text-left"
          >
            <div className="p-3.5 bg-foreground/5 rounded-2xl border border-foreground/10 group-hover:bg-primary/10 group-hover:border-primary/20 transition-colors overflow-hidden">
              {profile.avatar ? (
                <img src={profile.avatar} alt="" className="w-5 h-5 object-cover rounded-lg -m-0.5 scale-[1.4]" />
              ) : (
                <UserCircle className="w-5 h-5 text-primary" />
              )}
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-sm font-black uppercase tracking-wider">User Profile</h3>
              <p className="text-xs text-muted-foreground mt-0.5 truncate">{profileSummary}</p>
            </div>
            <ChevronRight className="w-5 h-5 text-muted-foreground/30 group-hover:text-foreground/50 transition-colors shrink-0" />
          </button>

          {/* Connection Status */}
          <button
            onClick={() => openSection("status")}
            className="group flex items-center gap-5 p-5 rounded-2xl border border-foreground/5 bg-foreground/[0.02] hover:bg-foreground/5 hover:border-foreground/10 transition-all duration-200 text-left"
          >
            <div className="p-3.5 bg-foreground/5 rounded-2xl border border-foreground/10 group-hover:bg-primary/10 group-hover:border-primary/20 transition-colors">
              <Activity className="w-5 h-5 text-primary" />
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="text-sm font-black uppercase tracking-wider">Connection Status</h3>
              <p className="text-xs text-muted-foreground mt-0.5 truncate">{statusSummary}</p>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              {health?.server === "ok" && (
                <div className={cn(
                  "w-2 h-2 rounded-full",
                  health.llm_connected
                    ? "bg-emerald-500 shadow-[0_0_8px_theme(colors.emerald.500)]"
                    : "bg-amber-500 shadow-[0_0_8px_theme(colors.amber.500)]"
                )} />
              )}
              <ChevronRight className="w-5 h-5 text-muted-foreground/30 group-hover:text-foreground/50 transition-colors" />
            </div>
          </button>
        </div>
      </div>
    );
  }

  // ===== THEME & APPEARANCE =====
  if (activeSection === "theme") {
    return (
      <div className="h-full overflow-y-auto p-10 bg-background relative">
        <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />
        <div className="relative max-w-3xl space-y-8">
          <SectionHeader title="Theme & Appearance" subtitle="액센트 컬러 및 배경 설정" />

          {/* Mode Toggle */}
          <div className="space-y-4">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Mode</Label>
            <div className="flex gap-3">
              <button
                onClick={() => applyAndSave({ mode: "dark", tone: "default" })}
                className={cn(
                  "flex-1 flex items-center justify-center gap-3 p-4 rounded-2xl border-2 transition-all duration-300",
                  mode === "dark" ? "border-primary/50 bg-primary/10" : "border-foreground/5 bg-foreground/5 hover:border-foreground/10"
                )}
              >
                <Moon className="w-5 h-5" />
                <span className="text-xs font-black uppercase tracking-widest">Dark</span>
              </button>
              <button
                onClick={() => applyAndSave({ mode: "light", tone: "default" })}
                className={cn(
                  "flex-1 flex items-center justify-center gap-3 p-4 rounded-2xl border-2 transition-all duration-300",
                  mode === "light" ? "border-primary/50 bg-primary/10" : "border-foreground/5 bg-foreground/5 hover:border-foreground/10"
                )}
              >
                <Sun className="w-5 h-5" />
                <span className="text-xs font-black uppercase tracking-widest">Light</span>
              </button>
            </div>
          </div>

          {/* Background Tone */}
          <div className="space-y-4">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Background Tone</Label>
            <div className="flex gap-3 flex-wrap">
              {(mode === "dark" ? DARK_TONES : LIGHT_TONES).map((t) => (
                <button
                  key={t.key}
                  onClick={() => applyAndSave({ tone: t.key })}
                  className={cn(
                    "relative flex flex-col items-center gap-2 p-3 rounded-2xl border-2 transition-all duration-300 min-w-[90px]",
                    tone === t.key ? "border-primary/50 bg-primary/10 scale-105" : "border-foreground/5 bg-foreground/5 hover:border-foreground/10"
                  )}
                >
                  <div className="w-12 h-12 rounded-xl border border-foreground/10" style={{ backgroundColor: t.preview }} />
                  <span className="text-[9px] font-black uppercase tracking-widest">{t.label}</span>
                  <span className="text-[8px] text-muted-foreground">{t.desc}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Accent Color */}
          <div className="space-y-4">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Accent Color</Label>
            <div className="flex gap-3 flex-wrap">
              {(Object.entries(ACCENT_PRESETS) as [AccentColor, typeof ACCENT_PRESETS[AccentColor]][]).map(([key, preset]) => (
                <button
                  key={key}
                  onClick={() => applyAndSave({ accentColor: key })}
                  className={cn(
                    "relative w-14 h-14 rounded-2xl border-2 transition-all duration-300 flex items-center justify-center",
                    accent === key ? "border-foreground/40 scale-110 shadow-lg" : "border-foreground/10 hover:border-foreground/20 hover:scale-105"
                  )}
                  style={{ backgroundColor: preset.preview }}
                >
                  {accent === key && <Check className="w-5 h-5 text-white drop-shadow-lg" />}
                  <span className="absolute -bottom-5 text-[8px] font-black uppercase tracking-widest text-muted-foreground">{preset.label}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Background Blobs */}
          <div className="flex items-center justify-between p-4 bg-card rounded-2xl border border-border/50 mt-8">
            <div>
              <span className="text-[10px] font-black uppercase tracking-widest text-foreground">Background Blobs</span>
              <p className="text-[10px] text-muted-foreground mt-1">배경 글로우 효과 표시</p>
            </div>
            <Switch checked={showBlobs} onCheckedChange={(checked) => applyAndSave({ showBlobs: checked })} className="data-[state=checked]:bg-primary" />
          </div>

          {/* Chat Background Image */}
          <div className="space-y-5 mt-8">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Chat Background Image</Label>
            <div className="flex gap-3 flex-wrap items-end">
              <button onClick={() => applyAndSave({ chatBgImage: "" })} className={cn("relative flex flex-col items-center gap-2 p-2 rounded-2xl border-2 transition-all duration-300 min-w-[80px]", !chatBgImage ? "border-primary/50 bg-primary/10 scale-105" : "border-foreground/5 bg-foreground/5 hover:border-foreground/10")}>
                <div className="w-16 h-16 rounded-xl border border-foreground/10 bg-foreground/5 flex items-center justify-center"><X className="w-5 h-5 text-muted-foreground/40" /></div>
                <span className="text-[9px] font-black uppercase tracking-widest">None</span>
              </button>
              {[{ url: "/rubber-track.png", label: "Track" }, { url: "/nano-banana.png", label: "Banana" }].map((preset) => (
                <button key={preset.url} onClick={() => applyAndSave({ chatBgImage: preset.url })} className={cn("relative flex flex-col items-center gap-2 p-2 rounded-2xl border-2 transition-all duration-300 min-w-[80px]", chatBgImage === preset.url ? "border-primary/50 bg-primary/10 scale-105" : "border-foreground/5 bg-foreground/5 hover:border-foreground/10")}>
                  <div className="w-16 h-16 rounded-xl border border-foreground/10 overflow-hidden bg-black/20"><img src={preset.url} alt={preset.label} className="w-full h-full object-cover grayscale" /></div>
                  <span className="text-[9px] font-black uppercase tracking-widest">{preset.label}</span>
                </button>
              ))}
              <input ref={bgImageInputRef} type="file" accept="image/*" className="hidden" onChange={(e) => { const file = e.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = () => applyAndSave({ chatBgImage: reader.result as string }); reader.readAsDataURL(file); e.target.value = ""; }} />
              <button onClick={() => bgImageInputRef.current?.click()} className={cn("relative flex flex-col items-center gap-2 p-2 rounded-2xl border-2 transition-all duration-300 min-w-[80px]", chatBgImage && chatBgImage.startsWith("data:") ? "border-primary/50 bg-primary/10 scale-105" : "border-foreground/5 bg-foreground/5 hover:border-foreground/10")}>
                <div className="w-16 h-16 rounded-xl border border-dashed border-foreground/10 flex items-center justify-center bg-foreground/5 overflow-hidden">
                  {chatBgImage && chatBgImage.startsWith("data:") ? <img src={chatBgImage} alt="custom" className="w-full h-full object-cover grayscale" /> : <ImageIcon className="w-5 h-5 text-muted-foreground/40" />}
                </div>
                <span className="text-[9px] font-black uppercase tracking-widest">Custom</span>
              </button>
            </div>

            {chatBgImage && (
              <>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Opacity</Label>
                    <span className="text-xs font-mono font-bold text-primary">{(chatBgOpacity * 100).toFixed(0)}%</span>
                  </div>
                  <input type="range" min="0" max="1" step="0.05" value={chatBgOpacity} onChange={(e) => applyAndSave({ chatBgOpacity: parseFloat(e.target.value) })} className="w-full accent-primary h-1.5" />
                </div>
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Scale</Label>
                    <div className="flex items-center gap-2">
                      <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => applyAndSave({ chatBgScale: Math.max(0.5, chatBgScale - 0.1) })}><ZoomOut className="w-3 h-3" /></Button>
                      <span className="text-xs font-mono font-bold text-primary w-12 text-center">{(chatBgScale * 100).toFixed(0)}%</span>
                      <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => applyAndSave({ chatBgScale: Math.min(5, chatBgScale + 0.1) })}><ZoomIn className="w-3 h-3" /></Button>
                    </div>
                  </div>
                  <input type="range" min="0.5" max="5" step="0.1" value={chatBgScale} onChange={(e) => applyAndSave({ chatBgScale: parseFloat(e.target.value) })} className="w-full accent-primary h-1.5" />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Position X</Label>
                      <span className="text-[10px] font-mono font-bold text-foreground/60">{chatBgPosX.toFixed(0)}%</span>
                    </div>
                    <input type="range" min="0" max="100" step="1" value={chatBgPosX} onChange={(e) => applyAndSave({ chatBgPositionX: parseFloat(e.target.value) })} className="w-full accent-primary h-1.5" />
                  </div>
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Position Y</Label>
                      <span className="text-[10px] font-mono font-bold text-foreground/60">{chatBgPosY.toFixed(0)}%</span>
                    </div>
                    <input type="range" min="0" max="100" step="1" value={chatBgPosY} onChange={(e) => applyAndSave({ chatBgPositionY: parseFloat(e.target.value) })} className="w-full accent-primary h-1.5" />
                  </div>
                </div>
                <div className="flex justify-end">
                  <Button variant="ghost" size="sm" className="text-[10px] font-black uppercase tracking-widest text-muted-foreground hover:text-foreground h-8 px-3" onClick={() => applyAndSave({ chatBgScale: 1.1, chatBgPositionX: 50, chatBgPositionY: 50, chatBgOpacity: 0.3 })}>
                    <RotateCcw className="w-3 h-3 mr-1.5" />Reset
                  </Button>
                </div>
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Live Preview</Label>
                    <span className="text-[9px] font-mono text-muted-foreground/40 flex items-center gap-1.5"><Move className="w-3 h-3" /> 드래그하여 위치 조정</span>
                  </div>
                  <div ref={previewRef} className={cn("relative w-full rounded-2xl border border-foreground/10 overflow-hidden bg-background select-none", previewDragging ? "cursor-grabbing" : "cursor-grab")} style={{ aspectRatio: "16 / 9" }} onMouseDown={handlePreviewDragStart}>
                    <div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-primary/5 blur-[60px] rounded-full pointer-events-none" />
                    <div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] bg-primary/5 blur-[60px] rounded-full pointer-events-none" />
                    <div className="absolute inset-0" style={{ backgroundImage: `url("${chatBgImage}")`, backgroundPosition: `${chatBgPosX}% ${chatBgPosY}%`, backgroundSize: `${chatBgScale * 100}%`, backgroundRepeat: "no-repeat", filter: "blur(3px) grayscale(100%)", opacity: chatBgOpacity }} />
                    <div className="absolute inset-0 pointer-events-none opacity-30" style={{ backgroundImage: "linear-gradient(rgba(255,255,255,0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.04) 1px, transparent 1px)", backgroundSize: "10% 10%" }} />
                    <div className="absolute top-1/2 left-0 right-0 h-px bg-primary/10 pointer-events-none" />
                    <div className="absolute left-1/2 top-0 bottom-0 w-px bg-primary/10 pointer-events-none" />
                    <div className="absolute top-0 left-0 right-0 h-[14%] bg-background/40 backdrop-blur-sm border-b border-foreground/5 flex items-center px-4 pointer-events-none">
                      <div className="w-1 h-[60%] bg-primary/40 rounded-full" /><div className="ml-2 space-y-1"><div className="h-1.5 w-16 bg-foreground/20 rounded-full" /><div className="h-1 w-10 bg-foreground/10 rounded-full" /></div>
                    </div>
                    <div className="absolute top-[22%] left-4 right-[30%] pointer-events-none"><div className="flex items-start gap-2"><div className="w-5 h-5 rounded-lg bg-foreground/10 shrink-0" /><div className="h-6 bg-foreground/5 rounded-xl rounded-tl-none border border-foreground/5 flex-1" /></div></div>
                    <div className="absolute top-[40%] right-4 left-[30%] pointer-events-none"><div className="flex items-start gap-2 flex-row-reverse"><div className="w-5 h-5 rounded-lg bg-primary/30 shrink-0" /><div className="h-8 bg-primary/10 rounded-xl rounded-tr-none border border-primary/20 flex-1" /></div></div>
                    <div className="absolute top-[58%] left-4 right-[20%] pointer-events-none"><div className="flex items-start gap-2"><div className="w-5 h-5 rounded-lg bg-foreground/10 shrink-0" /><div className="h-10 bg-foreground/5 rounded-xl rounded-tl-none border border-foreground/5 flex-1" /></div></div>
                    <div className="absolute bottom-[6%] left-[8%] right-[8%] h-[12%] bg-background/60 backdrop-blur-sm rounded-full border border-foreground/10 pointer-events-none flex items-center px-4"><div className="flex-1 h-1.5 bg-foreground/5 rounded-full" /><div className="w-6 h-6 rounded-full bg-primary/30 ml-3 shrink-0" /></div>
                  </div>
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ===== LLM CONFIGURATION =====
  if (activeSection === "llm") {
    return (
      <div className="h-full overflow-y-auto p-10 bg-background relative">
        <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />
        <div className="relative max-w-3xl space-y-8">
          <SectionHeader title="LLM Configuration" subtitle="모델 선택 및 파라미터 설정" />

          {/* Quick Preset */}
          <div className="space-y-2">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Quick Preset</Label>
            <button
              onClick={() => { setLlmModel("hosted_vllm/openai/gpt-oss-120b"); setLlmApiBase("http://192.168.1.120:11436/v1"); setLlmApiKey("dummy"); setLlmTemp(0.7); setLlmMaxTokens(4096); }}
              className={cn("w-full flex items-center gap-4 p-4 rounded-2xl border-2 transition-all duration-300 text-left", llmModel === "hosted_vllm/openai/gpt-oss-120b" ? "border-primary/50 bg-primary/10" : "border-foreground/5 bg-foreground/[0.02] hover:border-foreground/10 hover:bg-foreground/5")}
            >
              <div className="p-2.5 bg-primary/10 rounded-xl border border-primary/20 shrink-0"><Server className="w-4 h-4 text-primary" /></div>
              <div className="flex-1 min-w-0">
                <div className="text-[11px] font-black uppercase tracking-wider">사내 vLLM 서버</div>
                <div className="text-[9px] font-mono text-muted-foreground mt-0.5 truncate">hosted_vllm/openai/gpt-oss-120b</div>
              </div>
              {llmModel === "hosted_vllm/openai/gpt-oss-120b" && <Check className="w-4 h-4 text-primary shrink-0" />}
            </button>
          </div>

          {/* Model Selector */}
          <div className="space-y-2">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Model Select</Label>
            <div className="border border-foreground/10 rounded-2xl overflow-hidden divide-y divide-foreground/5">
              {MODEL_CATALOG.map((group) => {
                const isOpen = openProviders.has(group.provider);
                const hasSelected = group.models.some((m) => llmModel === m.model);
                return (
                  <div key={group.provider}>
                    <button onClick={() => toggleProvider(group.provider)} className={cn("w-full flex items-center justify-between p-4 hover:bg-foreground/5 transition-colors", hasSelected && "bg-primary/5")}>
                      <div className="flex items-center gap-3">
                        {isOpen ? <ChevronDown className="w-4 h-4 text-muted-foreground" /> : <ChevronRight className="w-4 h-4 text-muted-foreground" />}
                        <span className="text-xs font-black uppercase tracking-widest">{group.provider}</span>
                        {group.envKey && <span className="text-[9px] font-mono text-muted-foreground/50">{group.envKey}</span>}
                      </div>
                      {hasSelected && <span className="text-[9px] font-mono text-primary">{group.models.find((m) => m.model === llmModel)?.label}</span>}
                    </button>
                    {isOpen && (
                      <div className="bg-foreground/[0.02]">
                        {group.models.map((m) => (
                          <button key={m.model} onClick={() => { setLlmModel(m.model); if (group.envKey) { setLlmApiBase(""); setLlmApiKey(""); } }} className={cn("w-full flex items-center justify-between px-6 py-3 text-left transition-colors", llmModel === m.model ? "bg-primary/10 border-l-2 border-primary" : "hover:bg-foreground/5 border-l-2 border-transparent")}>
                            <div><span className="text-[11px] font-bold">{m.label}</span><p className="text-[9px] font-mono text-muted-foreground mt-0.5">{m.model}</p></div>
                            {llmModel === m.model && <Check className="w-4 h-4 text-primary shrink-0" />}
                          </button>
                        ))}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          <div className="space-y-3">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Model Name</Label>
            <Input value={llmModel} onChange={(e) => setLlmModel(e.target.value)} placeholder="gemini/gemini-3-flash-preview" className="bg-black/20 border-foreground/10 h-11 text-sm font-mono" />
          </div>
          <div className="space-y-3">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">API Base URL (Optional)</Label>
            <Input value={llmApiBase} onChange={(e) => setLlmApiBase(e.target.value)} placeholder="http://your-vllm-server:8000/v1" className="bg-black/20 border-foreground/10 h-11 text-sm font-mono" />
            <p className="text-[10px] text-muted-foreground font-mono">vLLM, Ollama 등 자체 서버 사용 시 입력 (기본 프로바이더는 비워둠)</p>
          </div>
          <div className="space-y-3">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">API Key Override (Optional)</Label>
            <Input type="password" value={llmApiKey} onChange={(e) => setLlmApiKey(e.target.value)} placeholder="서버 .env의 API 키를 오버라이드" className="bg-black/20 border-foreground/10 h-11 text-sm font-mono" />
          </div>
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Temperature</Label>
              <span className="text-sm font-mono font-bold text-primary">{llmTemp.toFixed(1)}</span>
            </div>
            <input type="range" min="0" max="2" step="0.1" value={llmTemp} onChange={(e) => setLlmTemp(parseFloat(e.target.value))} className="w-full accent-primary h-2" />
            <div className="flex justify-between text-[9px] text-muted-foreground font-mono"><span>0.0 (정확)</span><span>1.0</span><span>2.0 (창의적)</span></div>
          </div>
          <div className="space-y-3">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Max Tokens</Label>
            <Input type="number" value={llmMaxTokens} onChange={(e) => setLlmMaxTokens(parseInt(e.target.value) || 4096)} className="bg-black/20 border-foreground/10 h-11 text-sm font-mono w-40" />
          </div>
          <div className="space-y-3">
            <Label className="text-[10px] font-black uppercase tracking-widest text-primary">System Prompt</Label>
            <textarea value={llmSystemPrompt} onChange={(e) => setLlmSystemPrompt(e.target.value)} placeholder="기본 시스템 프롬프트를 입력하세요 (비어있으면 기본값 사용)" className="w-full bg-black/20 border border-foreground/10 rounded-md p-4 text-xs font-mono text-foreground min-h-[120px] resize-y focus:outline-none focus:border-primary/50 transition-colors" />
          </div>
          <Button onClick={handleLLMSave} disabled={llmSaving} className="h-12 px-8 bg-primary text-primary-foreground font-black uppercase tracking-widest hover:opacity-90">
            {llmSaved ? <><Check className="w-4 h-4 mr-2" /> Saved</> : <><Save className="w-4 h-4 mr-2" /> {llmSaving ? "Saving..." : "Save LLM Settings"}</>}
          </Button>
        </div>
      </div>
    );
  }

  // ===== MEMORY =====
  if (activeSection === "memory") {
    return (
      <div className="h-full overflow-y-auto p-10 bg-background relative">
        <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />
        <div className="relative max-w-3xl space-y-8">
          <SectionHeader title="Memory" subtitle="장기 기억 자동 추출 및 주입 설정" />

          {!memLoaded ? (
            <div className="flex items-center gap-3 p-5 bg-foreground/5 rounded-2xl border border-foreground/5">
              <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Loading...</span>
            </div>
          ) : !memSettings ? (
            <div className="flex items-center gap-3 p-5 bg-red-500/5 rounded-2xl border border-red-500/10">
              <span className="text-[10px] font-bold text-red-400">백엔드 서버에 연결할 수 없습니다. 서버를 시작한 후 다시 시도하세요.</span>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between p-5 bg-card rounded-2xl border border-border/50">
                <div>
                  <span className="text-xs font-black uppercase tracking-widest text-foreground">Auto Memory</span>
                  <p className="text-[11px] text-muted-foreground mt-1">대화에서 자동으로 기억을 추출하고 시스템 프롬프트에 주입</p>
                </div>
                <Switch checked={memSettings.enabled} onCheckedChange={(checked) => setMemSettings((s) => s ? { ...s, enabled: checked } : s)} className="data-[state=checked]:bg-purple-500" />
              </div>
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-purple-400">Max Memories</Label>
                  <span className="text-sm font-mono font-bold text-purple-400">{memSettings.max_memories}</span>
                </div>
                <input type="range" min="10" max="200" step="10" value={memSettings.max_memories} onChange={(e) => setMemSettings((s) => s ? { ...s, max_memories: parseInt(e.target.value) } : s)} className="w-full accent-purple-500 h-2" />
                <div className="flex justify-between text-[9px] text-muted-foreground font-mono"><span>10</span><span>100</span><span>200</span></div>
              </div>
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <Label className="text-[10px] font-black uppercase tracking-widest text-purple-400">Max Injection Tokens</Label>
                  <span className="text-sm font-mono font-bold text-purple-400">{memSettings.max_injection_tokens}</span>
                </div>
                <input type="range" min="500" max="8000" step="500" value={memSettings.max_injection_tokens} onChange={(e) => setMemSettings((s) => s ? { ...s, max_injection_tokens: parseInt(e.target.value) } : s)} className="w-full accent-purple-500 h-2" />
                <div className="flex justify-between text-[9px] text-muted-foreground font-mono"><span>500</span><span>4000</span><span>8000</span></div>
                <p className="text-[10px] text-muted-foreground font-mono">시스템 프롬프트에 주입되는 메모리의 최대 토큰 수</p>
              </div>
              <Button onClick={handleMemorySave} disabled={memSaving} className="h-12 px-8 bg-purple-600 text-white font-black uppercase tracking-widest hover:opacity-90">
                {memSaved ? <><Check className="w-4 h-4 mr-2" /> Saved</> : <><Save className="w-4 h-4 mr-2" /> {memSaving ? "Saving..." : "Save Memory Settings"}</>}
              </Button>
            </>
          )}
        </div>
      </div>
    );
  }

  // ===== USER PROFILE =====
  if (activeSection === "profile") {
    return (
      <div className="h-full overflow-y-auto p-10 bg-background relative">
        <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />
        <div className="relative max-w-3xl space-y-10">
          <SectionHeader title="Profile & Branding" subtitle="사용자 프로필 및 플랫폼 브랜딩 설정" />

          {/* --- User Profile --- */}
          <div className="space-y-5">
            <div className="flex items-center gap-2.5">
              <UserCircle className="w-4 h-4 text-primary" />
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">User Profile</Label>
            </div>
            <div className="flex items-start gap-8">
              <div className="space-y-3 flex flex-col items-center">
                <input ref={avatarInputRef} type="file" accept="image/*" className="hidden" onChange={handleAvatarSelect} />
                <div className="w-24 h-24 rounded-2xl border-2 border-dashed border-foreground/10 overflow-hidden cursor-pointer hover:border-primary/30 transition-colors flex items-center justify-center bg-foreground/5" onClick={() => avatarInputRef.current?.click()}>
                  {profile.avatar ? <img src={profile.avatar} alt="avatar" className="w-full h-full object-cover" /> : <Upload className="w-6 h-6 text-foreground/20" />}
                </div>
                <span className="text-[9px] text-muted-foreground font-mono">클릭하여 변경</span>
              </div>
              <div className="flex-1 space-y-3">
                <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Display Name</Label>
                <Input value={profile.name} onChange={(e) => setProfile((p) => ({ ...p, name: e.target.value }))} placeholder="이름을 입력하세요" className="bg-black/20 border-foreground/10 h-11 text-sm" />
                <p className="text-[10px] text-muted-foreground">채팅 메시지에 표시됩니다.</p>
              </div>
            </div>
          </div>

          <div className="h-px bg-foreground/5" />

          {/* --- Bot Profile --- */}
          <div className="space-y-5">
            <div className="flex items-center gap-2.5">
              <Bot className="w-4 h-4 text-primary" />
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">AI Bot Profile</Label>
            </div>
            <div className="flex items-start gap-8">
              <div className="space-y-3 flex flex-col items-center">
                <input ref={botAvatarInputRef} type="file" accept="image/*" className="hidden" onChange={handleBotAvatarSelect} />
                <div className="w-24 h-24 rounded-2xl border-2 border-dashed border-foreground/10 overflow-hidden cursor-pointer hover:border-primary/30 transition-colors flex items-center justify-center bg-foreground/5" onClick={() => botAvatarInputRef.current?.click()}>
                  {profile.botAvatar ? <img src={profile.botAvatar} alt="bot avatar" className="w-full h-full object-cover" /> : <Bot className="w-6 h-6 text-foreground/20" />}
                </div>
                <span className="text-[9px] text-muted-foreground font-mono">클릭하여 변경</span>
              </div>
              <div className="flex-1 space-y-3">
                <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Bot Name</Label>
                <Input value={profile.botName} onChange={(e) => setProfile((p) => ({ ...p, botName: e.target.value }))} placeholder="AI 봇 이름" className="bg-black/20 border-foreground/10 h-11 text-sm" />
                <p className="text-[10px] text-muted-foreground">채팅에서 AI 응답 아래에 표시됩니다.</p>
              </div>
            </div>
          </div>

          <div className="h-px bg-foreground/5" />

          {/* --- Platform Branding --- */}
          <div className="space-y-5">
            <div className="flex items-center gap-2.5">
              <Type className="w-4 h-4 text-primary" />
              <Label className="text-[10px] font-black uppercase tracking-widest text-primary">Platform Branding</Label>
            </div>
            <div className="grid gap-5">
              <div className="space-y-3">
                <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Platform Name</Label>
                <Input value={profile.platformName} onChange={(e) => setProfile((p) => ({ ...p, platformName: e.target.value }))} placeholder="Track Platform" className="bg-black/20 border-foreground/10 h-11 text-sm" />
                <p className="text-[10px] text-muted-foreground">사이드바 상단에 표시되는 플랫폼 이름</p>
              </div>
              <div className="space-y-3">
                <Label className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Platform Subtitle</Label>
                <Input value={profile.platformSubtitle} onChange={(e) => setProfile((p) => ({ ...p, platformSubtitle: e.target.value }))} placeholder="Nexus System" className="bg-black/20 border-foreground/10 h-11 text-sm" />
                <p className="text-[10px] text-muted-foreground">사이드바 상단 플랫폼 이름 아래 표시</p>
              </div>
            </div>
          </div>

          <Button onClick={handleProfileSave} className="h-12 px-8 bg-primary text-primary-foreground font-black uppercase tracking-widest hover:opacity-90">
            {profileSaved ? <><Check className="w-4 h-4 mr-2" /> Saved</> : <><Save className="w-4 h-4 mr-2" /> Save Profile</>}
          </Button>
        </div>
      </div>
    );
  }

  // ===== CONNECTION STATUS =====
  return (
    <div className="h-full overflow-y-auto p-10 bg-background relative">
      <div className="absolute inset-0 opacity-[0.02] pointer-events-none bg-[url('https://www.transparenttextures.com/patterns/carbon-fibre.png')]" />
      <div className="relative max-w-3xl space-y-8">
        <SectionHeader title="Connection Status" subtitle="백엔드 서버 연결 상태" />

        <div className="space-y-4">
          <div className="flex items-center justify-between p-5 bg-foreground/5 rounded-2xl border border-foreground/5">
            <div>
              <span className="text-xs font-black uppercase tracking-widest text-foreground">API Server</span>
              <p className="text-xs font-mono text-muted-foreground mt-1">{API_BASE_URL || "(same origin)"}</p>
            </div>
            {health === null ? (
              <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Unknown</span>
            ) : health.server === "ok" ? (
              <span className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-emerald-400">
                <div className="w-2 h-2 rounded-full bg-emerald-500 shadow-[0_0_8px_theme(colors.emerald.500)]" />Running
              </span>
            ) : (
              <span className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-red-400">
                <div className="w-2 h-2 rounded-full bg-red-500 shadow-[0_0_8px_theme(colors.red.500)]" />Unreachable
              </span>
            )}
          </div>
          <div className="flex items-center justify-between p-5 bg-foreground/5 rounded-2xl border border-foreground/5">
            <div>
              <span className="text-xs font-black uppercase tracking-widest text-foreground">LLM Connection</span>
              <p className="text-xs font-mono text-muted-foreground mt-1">{health?.model || llm?.model || "—"}</p>
            </div>
            {health === null ? (
              <span className="text-[10px] font-black uppercase tracking-widest text-muted-foreground">Unknown</span>
            ) : health.llm_connected ? (
              <span className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-emerald-400">
                <div className="w-2 h-2 rounded-full bg-emerald-500 shadow-[0_0_8px_theme(colors.emerald.500)]" />Connected
              </span>
            ) : (
              <span className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-red-400">
                <div className="w-2 h-2 rounded-full bg-red-500 shadow-[0_0_8px_theme(colors.red.500)]" />Disconnected
              </span>
            )}
          </div>
          {health?.error && (
            <div className="p-4 bg-red-500/5 border border-red-500/20 rounded-2xl">
              <span className="text-[10px] font-black uppercase tracking-widest text-red-400">Error</span>
              <p className="text-xs font-mono text-red-400/80 mt-1 break-all">{health.error}</p>
            </div>
          )}
          <Button variant="outline" onClick={handleHealthCheck} disabled={checking} className="h-12 rounded-none border-2 px-6 font-black uppercase tracking-widest hover:bg-foreground/5">
            <Activity className={cn("w-4 h-4 mr-2", checking && "animate-spin")} />
            {checking ? "Checking..." : "Check Connection"}
          </Button>
        </div>
      </div>
    </div>
  );
}
