/**
 * Home4j - Alpine.js 应用
 * 主题切换、语言切换、天气、日期时间等功能
 */

// ==================== 图标定义 ====================
var ICONS = {
    home: '<path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>',
    search: '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
    settings: '<circle cx="12" cy="12" r="3"/><path d="M12 1v2m0 18v2m-9-11h2m18 0h2m-4.2-5.8 1.4-1.4m-12.8 0L6.3 6.3m0 11.4-1.4 1.4m12.8 0 1.4-1.4"/>',
    user: '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
    edit: '<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/>',
    plus: '<path d="M5 12h14"/><path d="M12 5v14"/>',
    trash: '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
    x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
    folder: '<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>',
    link: '<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>',
    grid: '<rect width="7" height="7" x="3" y="3" rx="1"/><rect width="7" height="7" x="14" y="3" rx="1"/><rect width="7" height="7" x="14" y="14" rx="1"/><rect width="7" height="7" x="3" y="14" rx="1"/>',
    list: '<line x1="8" x2="21" y1="6" y2="6"/><line x1="8" x2="21" y1="12" y2="12"/><line x1="8" x2="21" y1="18" y2="18"/><line x1="3" x2="3.01" y1="6" y2="6"/><line x1="3" x2="3.01" y1="12" y2="12"/><line x1="3" x2="3.01" y1="18" y2="18"/>',
    sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>',
    moon: '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',
    inbox: '<polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/>',
    'chevron-right': '<path d="m9 18 6-6-6-6"/>',
    'chevron-down': '<path d="m6 9 6 6 6-6"/>',
    globe: '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
    code: '<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>',
    database: '<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/>',
    server: '<rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/>',
    cloud: '<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/>',
    file: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',
    heart: '<path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z"/>',
    star: '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',
    bookmark: '<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/>',
    github: '<path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/><path d="M9 18c-4.51 2-5-2-7-2"/>',
    youtube: '<path d="M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17"/><path d="m10 15 5-3-5-3z"/>',
    tool: '<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>',
    zap: '<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>',
    mail: '<rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>',
    terminal: '<polyline points="4 17 10 11 4 5"/><line x1="12" x2="20" y1="19" y2="19"/>',
    music: '<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>',
    video: '<path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5"/><rect x="2" y="6" width="14" height="12" rx="2"/>',
    image: '<rect width="18" height="18" x="3" y="3" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',
    download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
    upload: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/>',
    menu: '<line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/>',
    chevronDown: '<path d="m6 9 6 6 6-6"/>'
};

/**
 * 生成 SVG 图标 HTML
 */
function getIcon(name, size) {
    size = size || 24;
    var path = ICONS[name] || ICONS['link'];
    return '<svg xmlns="http://www.w3.org/2000/svg" width="' + size + '" height="' + size + '" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' + path + '</svg>';
}

// ==================== 国际化文本 ====================
var I18N = {
    'zh-CN': {
        appName: 'Home4j',
        search: '搜索书签...',
        viewMode: '视图模式',
        listView: '列表视图',
        cardView: '卡片视图',
        cardMode: '卡片样式',
        iconMode: '图标模式',
        imageMode: '背景图模式',
        theme: '主题',
        language: '语言',
        addBookmark: '添加书签',
        addGroup: '添加分组',
        background: '背景设置',
        bgSettings: '背景设置',
        account: '账户',
        adminPanel: '管理面板',
        logout: '退出登录',
        login: '登录',
        loginBtn: '登录',
        username: '用户名',
        password: '密码',
        heroSubtitle: '快速访问您的常用网站',
        searchBookmark: '搜索书签',
        searchEngines: '搜索引擎',
        searchGoogle: '使用 Google 搜索...',
        searchBing: '使用 Bing 搜索...',
        searchBaidu: '使用百度搜索...',
        searchDuckDuckGo: '使用 DuckDuckGo 搜索...',
        baidu: '百度',
        emptyTitle: '还没有书签',
        emptyDesc: '点击上方按钮开始添加书签和分组',
        edit: '编辑',
        delete: '删除',
        bookmarkName: '名称',
        bookmarkNamePlaceholder: '书签名称',
        description: '描述',
        descriptionPlaceholder: '书签描述（可选）',
        icon: '图标',
        group: '分组',
        selectGroup: '选择分组',
        displayMode: '显示模式',
        backgroundImage: '背景图片',
        bgImagePlaceholder: 'https://example.com/image.jpg',
        openInNewTab: '在新标签页打开',
        save: '保存',
        add: '添加',
        cancel: '取消',
        groupName: '分组名称',
        groupNamePlaceholder: '分组名称',
        sortOrder: '排序',
        sortOrderHint: '数字越小越靠前',
        bgType: '背景类型',
        bgTheme: '跟随主题',
        bgColor: '纯色背景',
        bgImage: '图片背景',
        selectColor: '选择颜色',
        imageUrl: '图片URL',
        saveSuccess: '保存成功',
        saveFailed: '保存失败',
        deleteSuccess: '删除成功',
        deleteFailed: '删除失败',
        confirmDelete: '确定要删除吗？',
        confirmDeleteGroup: '确定要删除这个分组及其所有书签吗？'
    },
    'en-US': {
        appName: 'Home4j',
        search: 'Search bookmarks...',
        viewMode: 'View Mode',
        listView: 'List View',
        cardView: 'Card View',
        cardMode: 'Card Style',
        iconMode: 'Icon Mode',
        imageMode: 'Image Mode',
        theme: 'Theme',
        language: 'Language',
        addBookmark: 'Add Bookmark',
        addGroup: 'Add Group',
        background: 'Background',
        bgSettings: 'Background Settings',
        account: 'Account',
        adminPanel: 'Admin Panel',
        logout: 'Logout',
        login: 'Login',
        loginBtn: 'Sign In',
        username: 'Username',
        password: 'Password',
        heroSubtitle: 'Quick access to your favorite sites',
        searchBookmark: 'Search Bookmarks',
        searchEngines: 'Search Engines',
        searchGoogle: 'Search with Google...',
        searchBing: 'Search with Bing...',
        searchBaidu: 'Search with Baidu...',
        searchDuckDuckGo: 'Search with DuckDuckGo...',
        baidu: 'Baidu',
        emptyTitle: 'No bookmarks yet',
        emptyDesc: 'Click the button above to start adding bookmarks and groups',
        edit: 'Edit',
        delete: 'Delete',
        bookmarkName: 'Name',
        bookmarkNamePlaceholder: 'Bookmark name',
        description: 'Description',
        descriptionPlaceholder: 'Bookmark description (optional)',
        icon: 'Icon',
        group: 'Group',
        selectGroup: 'Select group',
        displayMode: 'Display Mode',
        backgroundImage: 'Background Image',
        bgImagePlaceholder: 'https://example.com/image.jpg',
        openInNewTab: 'Open in new tab',
        save: 'Save',
        add: 'Add',
        cancel: 'Cancel',
        groupName: 'Group Name',
        groupNamePlaceholder: 'Group name',
        sortOrder: 'Sort Order',
        sortOrderHint: 'Lower number comes first',
        bgType: 'Background Type',
        bgTheme: 'Follow Theme',
        bgColor: 'Solid Color',
        bgImage: 'Image',
        selectColor: 'Select Color',
        imageUrl: 'Image URL',
        saveSuccess: 'Saved successfully',
        saveFailed: 'Failed to save',
        deleteSuccess: 'Deleted successfully',
        deleteFailed: 'Failed to delete',
        confirmDelete: 'Are you sure you want to delete?',
        confirmDeleteGroup: 'Delete this group and all its bookmarks?'
    }
};

// ==================== 主题配置 ====================
var THEMES = [
    { id: 'light', name: 'Light', colors: { primary: '#570df8', secondary: '#f000b8', accent: '#37cdbe' } },
    { id: 'dark', name: 'Dark', colors: { primary: '#661ae6', secondary: '#d926aa', accent: '#1fb2a5' } },
    { id: 'cupcake', name: 'Cupcake', colors: { primary: '#65c3c8', secondary: '#ef9fbc', accent: '#eeaf3a' } },
    { id: 'bumblebee', name: 'Bumblebee', colors: { primary: '#e0a82e', secondary: '#f9d72f', accent: '#181830' } },
    { id: 'emerald', name: 'Emerald', colors: { primary: '#66cc8a', secondary: '#377cfb', accent: '#ea5234' } },
    { id: 'corporate', name: 'Corporate', colors: { primary: '#4b6bfb', secondary: '#7b92b2', accent: '#67cba0' } },
    { id: 'synthwave', name: 'Synthwave', colors: { primary: '#e779c1', secondary: '#58c7f3', accent: '#f3cc30' } },
    { id: 'retro', name: 'Retro', colors: { primary: '#ef9995', secondary: '#a4cbb4', accent: '#dc8850' } },
    { id: 'cyberpunk', name: 'Cyberpunk', colors: { primary: '#ff7598', secondary: '#75d1f0', accent: '#c07eec' } },
    { id: 'valentine', name: 'Valentine', colors: { primary: '#e96d7b', secondary: '#a991f7', accent: '#88dbdd' } },
    { id: 'halloween', name: 'Halloween', colors: { primary: '#f28c18', secondary: '#6d3a9c', accent: '#51a800' } },
    { id: 'garden', name: 'Garden', colors: { primary: '#5c7f67', secondary: '#ecf4e7', accent: '#fae5e5' } },
    { id: 'forest', name: 'Forest', colors: { primary: '#1eb854', secondary: '#1db990', accent: '#1db9ac' } },
    { id: 'aqua', name: 'Aqua', colors: { primary: '#09ecf3', secondary: '#966fb3', accent: '#ffe999' } },
    { id: 'lofi', name: 'Lo-Fi', colors: { primary: '#0d0d0d', secondary: '#1a1919', accent: '#262626' } },
    { id: 'pastel', name: 'Pastel', colors: { primary: '#d1c1d7', secondary: '#f6cbd1', accent: '#b4e9d6' } },
    { id: 'fantasy', name: 'Fantasy', colors: { primary: '#6e0b75', secondary: '#007ebd', accent: '#f8860d' } },
    { id: 'wireframe', name: 'Wireframe', colors: { primary: '#b8b8b8', secondary: '#b8b8b8', accent: '#b8b8b8' } },
    { id: 'black', name: 'Black', colors: { primary: '#343232', secondary: '#343232', accent: '#343232' } },
    { id: 'luxury', name: 'Luxury', colors: { primary: '#ffffff', secondary: '#152747', accent: '#513448' } },
    { id: 'dracula', name: 'Dracula', colors: { primary: '#ff79c6', secondary: '#bd93f9', accent: '#ffb86c' } },
    { id: 'cmyk', name: 'CMYK', colors: { primary: '#45aeee', secondary: '#e8488a', accent: '#fff232' } },
    { id: 'autumn', name: 'Autumn', colors: { primary: '#8c0327', secondary: '#d85251', accent: '#d59b6a' } },
    { id: 'business', name: 'Business', colors: { primary: '#1c4f82', secondary: '#7c909a', accent: '#eb6b47' } },
    { id: 'acid', name: 'Acid', colors: { primary: '#ff00f4', secondary: '#ff7400', accent: '#cbff00' } },
    { id: 'lemonade', name: 'Lemonade', colors: { primary: '#519903', secondary: '#e9e92e', accent: '#f7f7f7' } },
    { id: 'night', name: 'Night', colors: { primary: '#38bdf8', secondary: '#818cf8', accent: '#f471b5' } },
    { id: 'coffee', name: 'Coffee', colors: { primary: '#db924b', secondary: '#6f4e37', accent: '#263e3f' } },
    { id: 'winter', name: 'Winter', colors: { primary: '#047aff', secondary: '#463aa2', accent: '#c149ad' } },
    { id: 'dim', name: 'Dim', colors: { primary: '#9fe88d', secondary: '#ff7d5c', accent: '#c792e9' } },
    { id: 'nord', name: 'Nord', colors: { primary: '#5e81ac', secondary: '#81a1c1', accent: '#88c0d0' } },
    { id: 'sunset', name: 'Sunset', colors: { primary: '#ff865b', secondary: '#fd6f9c', accent: '#b387fa' } }
];

// ==================== 天气图标映射 ====================
var WEATHER_ICONS = {
    '113': '☀️', // Sunny
    '116': '⛅', // Partly cloudy
    '119': '☁️', // Cloudy
    '122': '☁️', // Overcast
    '143': '🌫️', // Mist
    '176': '🌧️', // Patchy rain
    '179': '🌨️', // Patchy snow
    '182': '🌨️', // Patchy sleet
    '185': '🌨️', // Patchy freezing drizzle
    '200': '⛈️', // Thundery outbreaks
    '227': '❄️', // Blowing snow
    '230': '❄️', // Blizzard
    '248': '🌫️', // Fog
    '260': '🌫️', // Freezing fog
    '263': '🌧️', // Patchy light drizzle
    '266': '🌧️', // Light drizzle
    '281': '🌧️', // Freezing drizzle
    '284': '🌧️', // Heavy freezing drizzle
    '293': '🌧️', // Patchy light rain
    '296': '🌧️', // Light rain
    '299': '🌧️', // Moderate rain at times
    '302': '🌧️', // Moderate rain
    '305': '🌧️', // Heavy rain at times
    '308': '🌧️', // Heavy rain
    '311': '🌧️', // Light freezing rain
    '314': '🌧️', // Moderate or heavy freezing rain
    '317': '🌨️', // Light sleet
    '320': '🌨️', // Moderate or heavy sleet
    '323': '🌨️', // Patchy light snow
    '326': '🌨️', // Light snow
    '329': '🌨️', // Patchy moderate snow
    '332': '🌨️', // Moderate snow
    '335': '🌨️', // Patchy heavy snow
    '338': '❄️', // Heavy snow
    '350': '🌨️', // Ice pellets
    '353': '🌧️', // Light rain shower
    '356': '🌧️', // Moderate or heavy rain shower
    '359': '🌧️', // Torrential rain shower
    '362': '🌨️', // Light sleet showers
    '365': '🌨️', // Moderate or heavy sleet showers
    '368': '🌨️', // Light snow showers
    '371': '🌨️', // Moderate or heavy snow showers
    '386': '⛈️', // Patchy light rain with thunder
    '389': '⛈️', // Moderate or heavy rain with thunder
    '392': '⛈️', // Patchy light snow with thunder
    '395': '⛈️'  // Moderate or heavy snow with thunder
};

/**
 * Home4jApp - Alpine.js 组件
 */
function Home4jApp() {
    return {
        // ========== 基础状态 ==========
        searchQuery: '',
        searchMode: localStorage.getItem('home4j_search_mode') || 'bookmark',
        viewMode: localStorage.getItem('home4j_view') || 'card',
        cardDisplayMode: localStorage.getItem('home4j_card_mode') || 'icon',
        currentTheme: localStorage.getItem('home4j_theme') || 'light',
        language: localStorage.getItem('home4j_lang') || 'zh-CN',
        collapsedGroups: JSON.parse(localStorage.getItem('home4j_collapsed') || '[]'),
        
        // 背景设置
        bgType: localStorage.getItem('home4j_bg_type') || 'theme',
        bgColor: localStorage.getItem('home4j_bg_color') || '#f5f5f5',
        bgImage: localStorage.getItem('home4j_bg_image') || '',
        
        // 日期时间天气
        currentDate: '',
        currentTime: '',
        weather: null,
        
        // 主题列表
        themes: THEMES,
        
        // 国际化
        i18n: I18N['zh-CN'],
        
        // 抽屉状态
        drawerOpen: false,
        drawerType: '',
        drawerTitle: '',
        saving: false,
        
        // 表单
        bookmarkForm: {
            id: null,
            name: '',
            url: '',
            description: '',
            icon: 'link',
            groupId: '',
            openInNewTab: true,
            visible: true,
            displayMode: 'icon',
            backgroundImage: ''
        },
        groupForm: {
            id: null,
            name: '',
            icon: 'folder',
            sortOrder: 0,
            visible: true
        },
        
        // Toast
        toasts: [],
        
        // ========== 初始化 ==========
        init: function() {
            var self = this;
            
            // 应用主题
            document.documentElement.setAttribute('data-theme', this.currentTheme);
            
            // 应用语言
            this.i18n = I18N[this.language] || I18N['zh-CN'];
            
            // 更新日期时间
            this.updateDateTime();
            setInterval(function() { self.updateDateTime(); }, 1000);
            
            // 获取天气
            this.fetchWeather();
            
            // 加载用户设置（如果已登录）
            if (window.HOME4J_DATA && window.HOME4J_DATA.isAdmin) {
                this.loadUserSettings();
            }
        },
        
        // ========== 工具方法 ==========
        getIcon: function(name, size) {
            return getIcon(name, size);
        },
        
        // ========== 日期时间 ==========
        updateDateTime: function() {
            var now = new Date();
            var lang = this.language;
            
            // 格式化日期
            var dateOptions = { weekday: 'short', month: 'short', day: 'numeric' };
            this.currentDate = now.toLocaleDateString(lang === 'zh-CN' ? 'zh-CN' : 'en-US', dateOptions);
            
            // 格式化时间
            this.currentTime = now.toLocaleTimeString(lang === 'zh-CN' ? 'zh-CN' : 'en-US', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });
        },
        
        // ========== 天气 ==========
        fetchWeather: function() {
            var self = this;
            var city = localStorage.getItem('home4j_weather_city') || '';
            
            // 使用 wttr.in 免费天气 API
            var url = 'https://wttr.in/' + encodeURIComponent(city) + '?format=j1';
            
            fetch(url)
                .then(function(res) { return res.json(); })
                .then(function(data) {
                    if (data && data.current_condition && data.current_condition[0]) {
                        var current = data.current_condition[0];
                        var code = current.weatherCode;
                        var icon = WEATHER_ICONS[code] || '🌤️';
                        
                        self.weather = {
                            icon: icon,
                            temp: current.temp_C + '°C',
                            city: data.nearest_area && data.nearest_area[0] ? 
                                  data.nearest_area[0].areaName[0].value : ''
                        };
                    }
                })
                .catch(function(err) {
                    console.log('Weather fetch failed:', err);
                });
        },
        
        // ========== 用户设置 ==========
        loadUserSettings: function() {
            var self = this;
            fetch('/api/settings')
                .then(function(res) { return res.json(); })
                .then(function(data) {
                    if (data) {
                        if (data.language) {
                            self.language = data.language;
                            self.i18n = I18N[data.language] || I18N['zh-CN'];
                            localStorage.setItem('home4j_lang', data.language);
                        }
                        if (data.bgType) {
                            self.bgType = data.bgType;
                            localStorage.setItem('home4j_bg_type', data.bgType);
                        }
                        if (data.bgColor) {
                            self.bgColor = data.bgColor;
                            localStorage.setItem('home4j_bg_color', data.bgColor);
                        }
                        if (data.bgImage) {
                            self.bgImage = data.bgImage;
                            localStorage.setItem('home4j_bg_image', data.bgImage);
                        }
                        if (data.defaultView) {
                            self.viewMode = data.defaultView;
                            localStorage.setItem('home4j_view', data.defaultView);
                        }
                        if (data.cardDisplayMode) {
                            self.cardDisplayMode = data.cardDisplayMode;
                            localStorage.setItem('home4j_card_mode', data.cardDisplayMode);
                        }
                        if (data.weatherCity) {
                            localStorage.setItem('home4j_weather_city', data.weatherCity);
                            self.fetchWeather();
                        }
                    }
                })
                .catch(function() {});
        },
        
        // ========== 主题 ==========
        setTheme: function(theme) {
            this.currentTheme = theme;
            localStorage.setItem('home4j_theme', theme);
            document.documentElement.setAttribute('data-theme', theme);
        },
        
        // ========== 语言 ==========
        setLanguage: function(lang) {
            this.language = lang;
            this.i18n = I18N[lang] || I18N['zh-CN'];
            localStorage.setItem('home4j_lang', lang);
            this.updateDateTime();
            
            // 保存到服务器（如果已登录）
            if (window.HOME4J_DATA && window.HOME4J_DATA.isAdmin) {
                this.saveUserSetting({ language: lang });
            }
        },
        
        // ========== 视图模式 ==========
        setViewMode: function(mode) {
            this.viewMode = mode;
            localStorage.setItem('home4j_view', mode);
        },
        
        setCardDisplayMode: function(mode) {
            this.cardDisplayMode = mode;
            localStorage.setItem('home4j_card_mode', mode);
        },
        
        // ========== 搜索功能 ==========
        getSearchPlaceholder: function() {
            var placeholders = {
                'bookmark': this.i18n.search,
                'google': this.i18n.searchGoogle,
                'bing': this.i18n.searchBing,
                'baidu': this.i18n.searchBaidu,
                'duckduckgo': this.i18n.searchDuckDuckGo
            };
            return placeholders[this.searchMode] || this.i18n.search;
        },
        
        handleSearch: function() {
            var query = this.searchQuery.trim();
            if (!query) return;
            
            // 保存搜索模式
            localStorage.setItem('home4j_search_mode', this.searchMode);
            
            if (this.searchMode === 'bookmark') {
                // 书签搜索由 x-model 自动处理，不需要额外操作
                return;
            }
            
            // 搜索引擎 URL 映射
            var searchUrls = {
                'google': 'https://www.google.com/search?q=',
                'bing': 'https://www.bing.com/search?q=',
                'baidu': 'https://www.baidu.com/s?wd=',
                'duckduckgo': 'https://duckduckgo.com/?q='
            };
            
            var url = searchUrls[this.searchMode];
            if (url) {
                window.open(url + encodeURIComponent(query), '_blank');
                this.searchQuery = ''; // 清空搜索框
            }
        },
        
        // ========== 分组折叠 ==========
        isGroupCollapsed: function(groupId) {
            return this.collapsedGroups.indexOf(groupId) !== -1;
        },
        
        toggleGroupCollapse: function(groupId) {
            var idx = this.collapsedGroups.indexOf(groupId);
            if (idx !== -1) {
                this.collapsedGroups.splice(idx, 1);
            } else {
                this.collapsedGroups.push(groupId);
            }
            localStorage.setItem('home4j_collapsed', JSON.stringify(this.collapsedGroups));
        },
        
        // ========== 搜索 ==========
        groupHasMatchingBookmarks: function(groupId) {
            if (!this.searchQuery) return true;
            var query = this.searchQuery.toLowerCase();
            var data = window.HOME4J_DATA;
            if (!data || !data.groups) return true;
            
            for (var i = 0; i < data.groups.length; i++) {
                if (data.groups[i].id == groupId) {
                    var bookmarks = data.groups[i].bookmarks || [];
                    for (var j = 0; j < bookmarks.length; j++) {
                        var b = bookmarks[j];
                        if ((b.name && b.name.toLowerCase().indexOf(query) !== -1) ||
                            (b.description && b.description.toLowerCase().indexOf(query) !== -1) ||
                            (b.url && b.url.toLowerCase().indexOf(query) !== -1)) {
                            return true;
                        }
                    }
                    return false;
                }
            }
            return true;
        },
        
        bookmarkMatchesSearch: function(name, desc, url) {
            if (!this.searchQuery) return true;
            var query = this.searchQuery.toLowerCase();
            name = name || '';
            desc = desc || '';
            url = url || '';
            return name.toLowerCase().indexOf(query) !== -1 ||
                   desc.toLowerCase().indexOf(query) !== -1 ||
                   url.toLowerCase().indexOf(query) !== -1;
        },
        
        // ========== 抽屉操作 ==========
        openDrawer: function(type, title) {
            this.drawerType = type;
            this.drawerTitle = title;
            this.drawerOpen = true;
            document.getElementById('app-drawer').checked = true;
        },
        
        closeDrawer: function() {
            this.drawerOpen = false;
            document.getElementById('app-drawer').checked = false;
        },
        
        openAddBookmarkDrawer: function() {
            this.bookmarkForm = {
                id: null,
                name: '',
                url: '',
                description: '',
                icon: 'link',
                groupId: '',
                openInNewTab: true,
                visible: true,
                displayMode: 'icon',
                backgroundImage: ''
            };
            this.openDrawer('bookmark', this.i18n.addBookmark);
        },
        
        openEditBookmarkDrawer: function(id) {
            var self = this;
            var data = window.HOME4J_DATA;
            if (data && data.groups) {
                for (var i = 0; i < data.groups.length; i++) {
                    var bookmarks = data.groups[i].bookmarks || [];
                    for (var j = 0; j < bookmarks.length; j++) {
                        if (bookmarks[j].id == id) {
                            var b = bookmarks[j];
                            self.bookmarkForm = {
                                id: b.id,
                                name: b.name || '',
                                url: b.url || '',
                                description: b.description || '',
                                icon: b.icon || 'link',
                                groupId: b.groupId || data.groups[i].id,
                                openInNewTab: b.openInNewTab !== false,
                                visible: b.visible !== false,
                                displayMode: b.displayMode || 'icon',
                                backgroundImage: b.backgroundImage || ''
                            };
                            self.openDrawer('bookmark', self.i18n.edit + ' ' + self.i18n.bookmarkName);
                            return;
                        }
                    }
                }
            }
        },
        
        openAddGroupDrawer: function() {
            this.groupForm = {
                id: null,
                name: '',
                icon: 'folder',
                sortOrder: 0,
                visible: true
            };
            this.openDrawer('group', this.i18n.addGroup);
        },
        
        openEditGroupDrawer: function(id) {
            var self = this;
            var data = window.HOME4J_DATA;
            if (data && data.groups) {
                for (var i = 0; i < data.groups.length; i++) {
                    if (data.groups[i].id == id) {
                        var g = data.groups[i];
                        self.groupForm = {
                            id: g.id,
                            name: g.name || '',
                            icon: g.icon || 'folder',
                            sortOrder: g.sortOrder || 0,
                            visible: g.visible !== false
                        };
                        self.openDrawer('group', self.i18n.edit + ' ' + self.i18n.groupName);
                        return;
                    }
                }
            }
        },
        
        openBackgroundSettings: function() {
            this.openDrawer('background', this.i18n.bgSettings);
        },
        
        // ========== 保存操作 ==========
        saveBookmark: function() {
            var self = this;
            self.saving = true;
            
            var method = self.bookmarkForm.id ? 'PUT' : 'POST';
            var url = self.bookmarkForm.id 
                ? '/api/admin/bookmarks/' + self.bookmarkForm.id 
                : '/api/admin/bookmarks';
            
            fetch(url, {
                method: method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(self.bookmarkForm)
            })
            .then(function(res) {
                if (res.ok) {
                    self.showToast(self.i18n.saveSuccess, 'success');
                    self.closeDrawer();
                    setTimeout(function() { location.reload(); }, 500);
                } else {
                    self.showToast(self.i18n.saveFailed, 'error');
                }
            })
            .catch(function() {
                self.showToast(self.i18n.saveFailed, 'error');
            })
            .finally(function() {
                self.saving = false;
            });
        },
        
        saveGroup: function() {
            var self = this;
            self.saving = true;
            
            var method = self.groupForm.id ? 'PUT' : 'POST';
            var url = self.groupForm.id 
                ? '/api/admin/groups/' + self.groupForm.id 
                : '/api/admin/groups';
            
            fetch(url, {
                method: method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(self.groupForm)
            })
            .then(function(res) {
                if (res.ok) {
                    self.showToast(self.i18n.saveSuccess, 'success');
                    self.closeDrawer();
                    setTimeout(function() { location.reload(); }, 500);
                } else {
                    self.showToast(self.i18n.saveFailed, 'error');
                }
            })
            .catch(function() {
                self.showToast(self.i18n.saveFailed, 'error');
            })
            .finally(function() {
                self.saving = false;
            });
        },
        
        saveBackground: function() {
            var self = this;
            self.saving = true;
            
            // 保存到本地
            localStorage.setItem('home4j_bg_type', this.bgType);
            localStorage.setItem('home4j_bg_color', this.bgColor);
            localStorage.setItem('home4j_bg_image', this.bgImage);
            
            // 保存到服务器
            this.saveUserSetting({
                bgType: this.bgType,
                bgColor: this.bgColor,
                bgImage: this.bgImage
            }).finally(function() {
                self.saving = false;
                self.showToast(self.i18n.saveSuccess, 'success');
                self.closeDrawer();
            });
        },
        
        saveUserSetting: function(settings) {
            return fetch('/api/settings', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(settings)
            }).catch(function() {});
        },
        
        // ========== 删除操作 ==========
        deleteBookmark: function(id) {
            var self = this;
            if (!confirm(this.i18n.confirmDelete)) return;
            
            fetch('/api/admin/bookmarks/' + id, { method: 'DELETE' })
            .then(function(res) {
                if (res.ok) {
                    self.showToast(self.i18n.deleteSuccess, 'success');
                    setTimeout(function() { location.reload(); }, 500);
                } else {
                    self.showToast(self.i18n.deleteFailed, 'error');
                }
            })
            .catch(function() {
                self.showToast(self.i18n.deleteFailed, 'error');
            });
        },
        
        deleteGroup: function(id) {
            var self = this;
            if (!confirm(this.i18n.confirmDeleteGroup)) return;
            
            fetch('/api/admin/groups/' + id, { method: 'DELETE' })
            .then(function(res) {
                if (res.ok) {
                    self.showToast(self.i18n.deleteSuccess, 'success');
                    setTimeout(function() { location.reload(); }, 500);
                } else {
                    self.showToast(self.i18n.deleteFailed, 'error');
                }
            })
            .catch(function() {
                self.showToast(self.i18n.deleteFailed, 'error');
            });
        },
        
        // ========== Toast ==========
        showToast: function(message, type) {
            var self = this;
            var id = Date.now();
            self.toasts.push({ id: id, message: message, type: type || 'info' });
            setTimeout(function() {
                self.toasts = self.toasts.filter(function(t) { return t.id !== id; });
            }, 3000);
        }
    };
}
