/**
 * Card color assignment — localStorage-backed color labels for any card.
 *
 * Usage in card creation functions:
 *   import { wrapCard } from '../core/card-colors.ts';
 *
 *   return wrapCard({
 *       dataAttr: 'data-device-id',
 *       id: device.id,
 *       removeOnclick: `removeDevice('${device.id}')`,
 *       removeTitle: t('common.delete'),
 *       content: `<div class="card-header">...</div>`,
 *       actions: `<button class="btn btn-icon btn-secondary" ...>Edit</button>`,
 *   });
 *
 * The helper wraps content in a standard card shell:
 *   - Outer div (.card / .template-card) with border-left color
 *   - .card-top-actions with remove button + optional top buttons
 *   - Bottom actions (.card-actions / .template-card-actions) with color picker
 */

import { createColorPicker, registerColorPicker } from './color-picker.ts';

const STORAGE_KEY = 'cardColors';
const DEFAULT_SWATCH = '#808080';

function _getAll(): Record<string, string> {
    try { return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') || {}; }
    catch { return {}; }
}

export function getCardColor(id: string): string {
    return _getAll()[id] || '';
}

export function setCardColor(id: string, hex: string): void {
    const m = _getAll();
    if (hex) m[id] = hex; else delete m[id];
    localStorage.setItem(STORAGE_KEY, JSON.stringify(m));
}

/**
 * Returns inline style string for card border-left.
 * Empty string when no color is set.
 */
export function cardColorStyle(entityId: string): string {
    const c = getCardColor(entityId);
    return c ? `border-left: 3px solid ${c}` : '';
}

/**
 * Returns color picker HTML + registers the pick callback.
 * @param {string} entityId  Unique entity ID
 * @param {string} cardAttr  Data attribute selector, e.g. 'data-device-id'
 */
export function cardColorButton(entityId: string, cardAttr: string): string {
    const color = getCardColor(entityId) || DEFAULT_SWATCH;
    const pickerId = `cc-${entityId}`;

    registerColorPicker(pickerId, (hex) => {
        setCardColor(entityId, hex);
        // Find the card that contains this picker (not a global querySelector
        // which could match a dashboard compact card first)
        const wrapper = document.getElementById(`cp-wrap-${pickerId}`);
        const card = wrapper?.closest(`[${cardAttr}]`) as HTMLElement | null;
        if (card) card.style.borderLeft = hex ? `3px solid ${hex}` : '';
    });

    return createColorPicker({ id: pickerId, currentColor: color, onPick: undefined, anchor: 'left', showReset: true, resetColor: DEFAULT_SWATCH });
}

/**
 * Build a standard card shell with color support.
 *
 * Provides consistent structure across all card types:
 *   - .card-top-actions: remove button + optional extra top buttons
 *   - Bottom actions: action buttons + color picker (always last)
 *   - Automatic border-left color from localStorage
 *
 * @param {object} opts
 * @param {'card'|'template-card'} [opts.type='card']  Card CSS class
 * @param {string} opts.dataAttr   Data attribute name, e.g. 'data-device-id'
 * @param {string} opts.id         Entity ID value
 * @param {string} [opts.classes]  Extra CSS classes on root element
 * @param {string} [opts.topButtons]  HTML for extra top-right buttons (power, autostart)
 * @param {string} opts.removeOnclick  onclick handler string for remove button
 * @param {string} opts.removeTitle    title attribute for remove button
 * @param {string} opts.content    Inner HTML (header, props, metrics, etc.)
 * @param {string} opts.actions    Action button HTML (without wrapper div)
 */
export function wrapCard({
    type = 'card',
    dataAttr,
    id,
    classes = '',
    topButtons = '',
    removeOnclick,
    removeTitle,
    content,
    actions,
}: {
    type?: 'card' | 'template-card';
    dataAttr: string;
    id: string;
    classes?: string;
    topButtons?: string;
    removeOnclick: string;
    removeTitle: string;
    content: string;
    actions: string;
}): string {
    const actionsClass = type === 'template-card' ? 'template-card-actions' : 'card-actions';
    const colorStyle = cardColorStyle(id);
    return `
        <div class="${type}${classes ? ' ' + classes : ''}" ${dataAttr}="${id}"${colorStyle ? ` style="${colorStyle}" data-has-color="1"` : ''}>
            <div class="card-top-actions">
                ${topButtons}
                ${removeOnclick ? `<button class="card-remove-btn" onclick="${removeOnclick}" title="${removeTitle}">&#x2715;</button>` : ''}
            </div>
            ${content}
            <div class="${actionsClass}">
                ${actions}
                ${cardColorButton(id, dataAttr)}
            </div>
        </div>`;
}
