/**
 * Curated icon library for the card-icon picker.
 *
 * Each entry is `{ id, paths, label, aliases, category }` where ``id`` is the
 * stable string persisted on the entity (e.g. ``device.icon = "mouse"``) and
 * ``paths`` is the inner SVG markup (re-uses ``icon-paths.ts``).
 *
 * To add a new icon: import its path constant from ``icon-paths.ts`` (or add
 * it there first), then append a new entry below with a stable id, label,
 * search aliases, and category.
 *
 * The id is the contract — never rename without a migration.
 */

import * as P from './icon-paths.ts';

export type IconCategory =
    | 'hardware'
    | 'lighting'
    | 'rooms'
    | 'media'
    | 'signal'
    | 'ambience'
    | 'weather'
    | 'nature'
    | 'controls'
    | 'status'
    | 'office';

export interface DeviceIconDef {
    /** Stable identifier — persisted on the entity. */
    id: string;
    /** Inner SVG markup (no <svg> wrapper). */
    paths: string;
    /** Human-readable label (i18n key under ``device.icon.<id>`` if present). */
    label: string;
    /** Lowercase search aliases — matched as substrings against the query. */
    aliases: string[];
    /** Category bucket for the picker tabs. */
    category: IconCategory;
}

export const CATEGORIES: { id: IconCategory; label: string; i18n: string }[] = [
    { id: 'hardware',  label: 'Hardware',  i18n: 'device.icon.cat.hardware'  },
    { id: 'lighting',  label: 'Lighting',  i18n: 'device.icon.cat.lighting'  },
    { id: 'rooms',     label: 'Rooms',     i18n: 'device.icon.cat.rooms'     },
    { id: 'media',     label: 'Media',     i18n: 'device.icon.cat.media'     },
    { id: 'signal',    label: 'Signal',    i18n: 'device.icon.cat.signal'    },
    { id: 'ambience',  label: 'Ambience',  i18n: 'device.icon.cat.ambience'  },
    { id: 'weather',   label: 'Weather',   i18n: 'device.icon.cat.weather'   },
    { id: 'nature',    label: 'Nature',    i18n: 'device.icon.cat.nature'    },
    { id: 'controls',  label: 'Controls',  i18n: 'device.icon.cat.controls'  },
    { id: 'status',    label: 'Status',    i18n: 'device.icon.cat.status'    },
    { id: 'office',    label: 'Office',    i18n: 'device.icon.cat.office'    },
];

export const DEVICE_ICONS: DeviceIconDef[] = [
    // Hardware
    { id: 'motherboard', paths: P.circuitBoard, label: 'Motherboard', aliases: ['mainboard', 'pcb', 'circuit', 'board', 'mobo'], category: 'hardware' },
    { id: 'cpu',         paths: P.cpu,          label: 'CPU',         aliases: ['processor', 'chip'], category: 'hardware' },
    { id: 'ram',         paths: P.layers,       label: 'RAM',         aliases: ['memory', 'dimm', 'stick'], category: 'hardware' },
    { id: 'ssd',         paths: P.hardDrive,    label: 'Storage',     aliases: ['ssd', 'hdd', 'drive', 'disk'], category: 'hardware' },
    { id: 'mouse',       paths: P.mouse,        label: 'Mouse',       aliases: ['rodent', 'pointer'], category: 'hardware' },
    { id: 'keyboard',    paths: P.keyboard,     label: 'Keyboard',    aliases: ['keys', 'kbd'], category: 'hardware' },
    { id: 'controller',  paths: P.gamepad2,     label: 'Controller',  aliases: ['gamepad', 'pad', 'joystick'], category: 'hardware' },
    { id: 'headphones',  paths: P.headphones,   label: 'Headphones',  aliases: ['headset', 'cans'], category: 'hardware' },
    { id: 'usb',         paths: P.usb,          label: 'USB',         aliases: ['cable', 'connector'], category: 'hardware' },
    { id: 'plug',        paths: P.plug,         label: 'Power plug',  aliases: ['outlet', 'socket'], category: 'hardware' },
    { id: 'phone',       paths: P.smartphone,   label: 'Phone',       aliases: ['mobile', 'tablet', 'cell', 'smartphone'], category: 'hardware' },
    { id: 'package',     paths: P.packageIcon,  label: 'Device unit', aliases: ['box', 'package', 'module', 'crate'], category: 'hardware' },
    { id: 'code',        paths: P.code,         label: 'Code',        aliases: ['script', 'firmware', 'dev'], category: 'hardware' },
    { id: 'laptop',      paths: P.laptop,       label: 'Laptop',      aliases: ['notebook', 'macbook', 'computer'], category: 'hardware' },
    { id: 'server',      paths: P.server,       label: 'Server',      aliases: ['rack', 'host', 'cluster', 'nas'], category: 'hardware' },
    { id: 'router',      paths: P.router,       label: 'Router',      aliases: ['network', 'gateway', 'access point', 'ap'], category: 'hardware' },
    { id: 'webcam',      paths: P.webcam,       label: 'Webcam',      aliases: ['cam', 'capture', 'video'], category: 'hardware' },
    { id: 'bot',         paths: P.bot,          label: 'Bot',         aliases: ['robot', 'vacuum', 'automation', 'roomba'], category: 'hardware' },
    { id: 'watch',       paths: P.watch,        label: 'Smartwatch',  aliases: ['wearable', 'wrist', 'fitness'], category: 'hardware' },
    { id: 'mcu',         paths: P.memoryStick,  label: 'Microcontroller', aliases: ['esp32', 'esp8266', 'arduino', 'mcu', 'chip', 'firmware'], category: 'hardware' },

    // Lighting
    { id: 'bulb',        paths: P.lightbulb,    label: 'Bulb',        aliases: ['lamp', 'light', 'lightbulb'], category: 'lighting' },
    { id: 'strip',       paths: P.rainbow,      label: 'LED strip',   aliases: ['strip', 'tape', 'rgb', 'wled'], category: 'lighting' },
    { id: 'panel',       paths: P.layoutDashboard, label: 'LED panel', aliases: ['matrix', 'tile', 'wall'], category: 'lighting' },
    { id: 'spot',        paths: P.zap,          label: 'Spotlight',   aliases: ['flash', 'beam', 'flood'], category: 'lighting' },
    { id: 'lamp',        paths: P.flaskConical, label: 'Floor lamp',  aliases: ['standing', 'pendant'], category: 'lighting' },
    { id: 'power',       paths: P.power,        label: 'Power',       aliases: ['onoff', 'switch', 'standby'], category: 'lighting' },
    { id: 'palette',     paths: P.palette,      label: 'Palette',     aliases: ['color', 'colour', 'paint'], category: 'lighting' },
    { id: 'dim',         paths: P.sunDim,       label: 'Dim light',   aliases: ['soft', 'low', 'mood'], category: 'lighting' },
    { id: 'ring',        paths: P.circle,       label: 'Ring light',  aliases: ['halo', 'round', 'circle'], category: 'lighting' },
    { id: 'point',       paths: P.circleDot,    label: 'Point light', aliases: ['pinpoint', 'dot', 'pixel'], category: 'lighting' },
    { id: 'ceiling',     paths: P.lampCeiling,  label: 'Ceiling light', aliases: ['chandelier', 'pendant', 'hanging'], category: 'lighting' },
    { id: 'desk_lamp',   paths: P.lampDesk,     label: 'Desk lamp',   aliases: ['task', 'workspace', 'pixar'], category: 'lighting' },
    { id: 'wall_light',  paths: P.lampWallUp,   label: 'Wall light',  aliases: ['sconce', 'uplight', 'mounted'], category: 'lighting' },
    { id: 'flashlight',  paths: P.flashlight,   label: 'Flashlight',  aliases: ['torch', 'beam', 'handheld'], category: 'lighting' },
    { id: 'bulb_off',    paths: P.lightbulbOff, label: 'Bulb off',    aliases: ['lightoff', 'dark', 'inactive', 'disabled'], category: 'lighting' },
    { id: 'candle',      paths: P.candle,       label: 'Candle',      aliases: ['flame', 'wax', 'ambient', 'romantic'], category: 'lighting' },

    // Rooms
    { id: 'bed',         paths: P.bed,          label: 'Bedroom',     aliases: ['sleep', 'bedroom'], category: 'rooms' },
    { id: 'sofa',        paths: P.armchair,     label: 'Living room', aliases: ['armchair', 'couch', 'lounge'], category: 'rooms' },
    { id: 'desk',        paths: P.layoutDashboard, label: 'Desk',     aliases: ['office', 'workstation'], category: 'rooms' },
    { id: 'door',        paths: P.doorOpen,     label: 'Door',        aliases: ['entry', 'doorway'], category: 'rooms' },
    { id: 'home',        paths: P.home,         label: 'Home',        aliases: ['house', 'household'], category: 'rooms' },
    { id: 'fan',         paths: P.fan,          label: 'Fan',         aliases: ['cooling', 'air'], category: 'rooms' },
    { id: 'thermostat',  paths: P.thermometer,  label: 'Thermostat',  aliases: ['temperature', 'heating', 'climate'], category: 'rooms' },
    { id: 'kitchen',     paths: P.chefHat,      label: 'Kitchen',     aliases: ['cook', 'chef', 'food'], category: 'rooms' },
    { id: 'bath',        paths: P.bath,         label: 'Bathroom',    aliases: ['bath', 'tub', 'shower'], category: 'rooms' },
    { id: 'garage',      paths: P.warehouse,    label: 'Garage',      aliases: ['workshop', 'shed', 'storage'], category: 'rooms' },
    { id: 'outdoor',     paths: P.trees,        label: 'Outdoor',     aliases: ['garden', 'yard', 'patio', 'park'], category: 'rooms' },

    // Media
    { id: 'monitor',     paths: P.monitor,      label: 'Monitor',     aliases: ['display', 'screen'], category: 'media' },
    { id: 'tv',          paths: P.tv,           label: 'TV',          aliases: ['television'], category: 'media' },
    { id: 'camera',      paths: P.camera,       label: 'Camera',      aliases: ['cam', 'webcam'], category: 'media' },
    { id: 'mic',         paths: P.mic,          label: 'Microphone',  aliases: ['mic', 'audio in'], category: 'media' },
    { id: 'speaker',     paths: P.volume2,      label: 'Speaker',     aliases: ['audio', 'output', 'monitor'], category: 'media' },
    { id: 'music',       paths: P.music,        label: 'Music',       aliases: ['note', 'audio'], category: 'media' },
    { id: 'film',        paths: P.film,         label: 'Film',        aliases: ['video', 'movie', 'reel'], category: 'media' },
    { id: 'projector',   paths: P.projector,    label: 'Projector',   aliases: ['beamer', 'cinema', 'home theater'], category: 'media' },
    { id: 'camcorder',   paths: P.video,        label: 'Camcorder',   aliases: ['video', 'recorder', 'cam'], category: 'media' },
    { id: 'disc',        paths: P.disc,         label: 'Disc',        aliases: ['vinyl', 'record', 'cd', 'dvd'], category: 'media' },
    { id: 'image',       paths: P.image,        label: 'Image',       aliases: ['picture', 'photo', 'still'], category: 'media' },
    { id: 'audio_file',  paths: P.fileAudio,    label: 'Audio file',  aliases: ['sound', 'sample', 'track'], category: 'media' },

    // Signal
    { id: 'wifi',        paths: P.wifi,         label: 'Wi-Fi',       aliases: ['wireless', 'network'], category: 'signal' },
    { id: 'bluetooth',   paths: P.bluetooth,    label: 'Bluetooth',   aliases: ['bt', 'wireless'], category: 'signal' },
    { id: 'radio',       paths: P.radio,        label: 'Radio',       aliases: ['rf', 'antenna', 'broadcast'], category: 'signal' },
    { id: 'globe',       paths: P.globe,        label: 'Network',     aliases: ['internet', 'web', 'world'], category: 'signal' },
    { id: 'cloud',       paths: P.cloudSun,     label: 'Cloud',       aliases: ['weather', 'mqtt'], category: 'signal' },
    { id: 'gps',         paths: P.mapPin,       label: 'Location',    aliases: ['map', 'gps', 'pin', 'place'], category: 'signal' },
    { id: 'send',        paths: P.send,         label: 'Send',        aliases: ['push', 'publish', 'mqtt', 'transmit'], category: 'signal' },

    // Ambience
    { id: 'sun',         paths: P.sun,          label: 'Sun',         aliases: ['daylight', 'sunny', 'bright'], category: 'ambience' },
    { id: 'moon',        paths: P.moon,         label: 'Moon',        aliases: ['night', 'dark'], category: 'ambience' },
    { id: 'flame',       paths: P.flame,        label: 'Flame',       aliases: ['fire', 'candle', 'warm'], category: 'ambience' },
    { id: 'star',        paths: P.star,         label: 'Star',        aliases: ['favorite', 'special'], category: 'ambience' },
    { id: 'sparkles',    paths: P.sparkles,     label: 'Sparkles',    aliases: ['effect', 'magic', 'glow'], category: 'ambience' },
    { id: 'gamepad',     paths: P.gamepad2,     label: 'Game',        aliases: ['gaming', 'play'], category: 'ambience' },
    { id: 'heart',       paths: P.heart,        label: 'Heart',       aliases: ['love', 'favorite'], category: 'ambience' },

    // Weather
    { id: 'rain',        paths: P.cloudRain,    label: 'Rain',        aliases: ['rainy', 'shower', 'drizzle', 'wet'], category: 'weather' },
    { id: 'snow',        paths: P.cloudSnow,    label: 'Snow',        aliases: ['snowy', 'blizzard', 'cold'], category: 'weather' },
    { id: 'thunder',     paths: P.cloudLightning, label: 'Thunder',   aliases: ['lightning', 'storm', 'bolt'], category: 'weather' },
    { id: 'fog',         paths: P.cloudFog,     label: 'Fog',         aliases: ['mist', 'haze', 'foggy'], category: 'weather' },
    { id: 'wind',        paths: P.wind,         label: 'Wind',        aliases: ['breeze', 'gust', 'windy'], category: 'weather' },
    { id: 'snowflake',   paths: P.snowflake,    label: 'Snowflake',   aliases: ['frost', 'ice', 'crystal'], category: 'weather' },
    { id: 'umbrella',    paths: P.umbrella,     label: 'Umbrella',    aliases: ['rain', 'shelter', 'parasol'], category: 'weather' },
    { id: 'sunrise',     paths: P.sunrise,      label: 'Sunrise',     aliases: ['dawn', 'morning', 'sunup'], category: 'weather' },
    { id: 'sunset',      paths: P.sunset,       label: 'Sunset',      aliases: ['dusk', 'evening', 'twilight'], category: 'weather' },

    // Nature
    { id: 'tree',        paths: P.treeDeciduous, label: 'Tree',       aliases: ['plant', 'oak', 'forest', 'wood'], category: 'nature' },
    { id: 'flower',      paths: P.flower2,      label: 'Flower',      aliases: ['bloom', 'blossom', 'garden'], category: 'nature' },
    { id: 'mountain',    paths: P.mountain,     label: 'Mountain',    aliases: ['peak', 'hill', 'summit', 'alpine'], category: 'nature' },
    { id: 'waves',       paths: P.waves,        label: 'Waves',       aliases: ['water', 'ocean', 'sea', 'ripple'], category: 'nature' },
    { id: 'sprout',      paths: P.sprout,       label: 'Sprout',      aliases: ['seedling', 'shoot', 'grow', 'eco'], category: 'nature' },
    { id: 'water_drops', paths: P.droplets,     label: 'Water drops', aliases: ['humidity', 'liquid', 'wet', 'splash'], category: 'nature' },
    { id: 'leaf',        paths: P.leaf,         label: 'Leaf',        aliases: ['plant', 'eco', 'nature', 'green'], category: 'nature' },

    // Controls
    { id: 'switch',      paths: P.toggleRight,  label: 'Switch',      aliases: ['toggle', 'on', 'off'], category: 'controls' },
    { id: 'slider',      paths: P.slidersHorizontal, label: 'Slider', aliases: ['mixer', 'eq', 'level', 'dimmer'], category: 'controls' },
    { id: 'settings',    paths: P.settings,     label: 'Settings',    aliases: ['cog', 'preferences', 'gear'], category: 'controls' },
    { id: 'refresh',     paths: P.refreshCw,    label: 'Refresh',     aliases: ['reload', 'sync', 'cycle'], category: 'controls' },
    { id: 'undo',        paths: P.undo2,        label: 'Undo',        aliases: ['back', 'revert'], category: 'controls' },
    { id: 'trash',       paths: P.trash2,       label: 'Trash',       aliases: ['delete', 'remove', 'bin'], category: 'controls' },
    { id: 'link',        paths: P.link,         label: 'Link',        aliases: ['chain', 'connect', 'url'], category: 'controls' },
    { id: 'search',      paths: P.search,       label: 'Search',      aliases: ['find', 'magnify', 'lookup'], category: 'controls' },
    { id: 'add',         paths: P.plus,         label: 'Add',         aliases: ['plus', 'new', 'create'], category: 'controls' },
    { id: 'show',        paths: P.eye,          label: 'Show',        aliases: ['view', 'visible', 'preview'], category: 'controls' },
    { id: 'lock',        paths: P.lock,         label: 'Lock',        aliases: ['secure', 'private', 'closed'], category: 'controls' },
    { id: 'key',         paths: P.keyRound,     label: 'Key',         aliases: ['credential', 'token', 'auth'], category: 'controls' },
    { id: 'tool',        paths: P.wrench,       label: 'Tool',        aliases: ['wrench', 'fix', 'maintenance'], category: 'controls' },

    // Status
    { id: 'check',       paths: P.check,        label: 'Check',       aliases: ['done', 'ok', 'tick'], category: 'status' },
    { id: 'ok',          paths: P.circleCheck,  label: 'OK',          aliases: ['success', 'valid', 'good'], category: 'status' },
    { id: 'warning',     paths: P.triangleAlert, label: 'Warning',    aliases: ['caution', 'alert', 'attention'], category: 'status' },
    { id: 'help',        paths: P.circleHelp,   label: 'Help',        aliases: ['question', 'unknown', 'about'], category: 'status' },
    { id: 'off',         paths: P.circleOff,    label: 'Disabled',    aliases: ['disable', 'inactive', 'banned'], category: 'status' },
    { id: 'shield',      paths: P.shield,       label: 'Shield',      aliases: ['secure', 'protect', 'guard'], category: 'status' },
    { id: 'target',      paths: P.target,       label: 'Target',      aliases: ['goal', 'aim', 'focus'], category: 'status' },
    { id: 'pulse',       paths: P.activity,     label: 'Pulse',       aliases: ['activity', 'live', 'heartbeat', 'metrics'], category: 'status' },
    { id: 'trend',       paths: P.trendingUp,   label: 'Trending',    aliases: ['rising', 'up', 'graph'], category: 'status' },
    { id: 'battery',     paths: P.batteryFull,  label: 'Battery',     aliases: ['power', 'charge', 'cell'], category: 'status' },

    // Office
    { id: 'calendar',    paths: P.calendar,     label: 'Calendar',    aliases: ['date', 'schedule', 'event'], category: 'office' },
    { id: 'mail',        paths: P.mail,         label: 'Mail',        aliases: ['email', 'envelope', 'message'], category: 'office' },
    { id: 'coffee',      paths: P.coffee,       label: 'Coffee',      aliases: ['drink', 'cafe', 'break'], category: 'office' },
    { id: 'briefcase',   paths: P.briefcase,    label: 'Briefcase',   aliases: ['work', 'business', 'job'], category: 'office' },
    { id: 'doc',         paths: P.fileText,     label: 'Document',    aliases: ['file', 'paper', 'text'], category: 'office' },
    { id: 'checklist',   paths: P.clipboardList, label: 'Checklist',  aliases: ['list', 'tasks', 'todo'], category: 'office' },
    { id: 'hashtag',     paths: P.hash,         label: 'Hashtag',     aliases: ['tag', 'number', 'channel'], category: 'office' },
    { id: 'clock',       paths: P.clock,        label: 'Clock',       aliases: ['time', 'hour', 'minute'], category: 'office' },
];

const _byId: Record<string, DeviceIconDef> = Object.fromEntries(
    DEVICE_ICONS.map((d) => [d.id, d]),
);

/** Lookup an icon definition by its persisted id. Returns null if unknown. */
export function getDeviceIconDef(iconId: string | undefined | null): DeviceIconDef | null {
    if (!iconId) return null;
    return _byId[iconId] ?? null;
}

/** Render an icon by id as inline SVG, or empty string if the id is unknown.
 *  Caller decides the wrapper — typically wraps it in an instrument-panel
 *  ``.mod-icon`` plate. */
export function renderDeviceIconSvg(iconId: string | undefined | null, opts: { size?: number; strokeWidth?: number } = {}): string {
    const def = getDeviceIconDef(iconId);
    if (!def) return '';
    const size = opts.size ?? 28;
    const sw = opts.strokeWidth ?? 1.6;
    return `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="${sw}" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${def.paths}</svg>`;
}

/** Render an icon by id as a `.icon`-class SVG that scales with its CSS
 *  context (matches the shape of `_svg()` in icons.ts). Returns empty
 *  string if the id is unknown so callers can chain `|| FALLBACK`. */
export function renderDeviceIcon(iconId: string | undefined | null): string {
    const def = getDeviceIconDef(iconId);
    if (!def) return '';
    return `<svg class="icon" viewBox="0 0 24 24">${def.paths}</svg>`;
}

/** All icons as a flat list, ordered by category then by definition order. */
export function allIcons(): DeviceIconDef[] {
    return DEVICE_ICONS.slice();
}

/** Filter icons by a free-text query (matches id, label, aliases). */
export function filterIcons(query: string): DeviceIconDef[] {
    const q = query.trim().toLowerCase();
    if (!q) return DEVICE_ICONS.slice();
    return DEVICE_ICONS.filter((d) => {
        if (d.id.includes(q)) return true;
        if (d.label.toLowerCase().includes(q)) return true;
        return d.aliases.some((a) => a.includes(q));
    });
}

/** Group icons by category. Returns categories in display order. */
export function iconsByCategory(): { category: IconCategory; label: string; i18n: string; items: DeviceIconDef[] }[] {
    return CATEGORIES.map((c) => ({
        category: c.id,
        label: c.label,
        i18n: c.i18n,
        items: DEVICE_ICONS.filter((d) => d.category === c.id),
    }));
}
