import { handlebars } from '@opengis/fastify-table/utils.js'

async function format(d, key, data) {

    if (!key?.includes) return '';
    if (d === true) return 'Так';
    if (d === false) return 'Ні';

    if (key.includes('{{')) {
        return await handlebars.compile(key)(data);
    }

    return d;
}
export default async function descriptionList(data, opt) {
    const { hash } = opt;

    // no data
    if (hash.nodata && !data) {
        const noDataText =
            typeof hash.nodata == 'string'
                ? hash.nodata
                : '<div class="bg-gray-200 dark:bg-transparent dark:text-white text-center p-6 rounded-xl"><h3 class="text-lg font-semibold">Інформація відсутня</h3></div>';
        return noDataText;
    }
    if (!hash.columns) return 'columns empty'
    const keys = hash.columns.split(hash.divider || ',').map(el => hash.comma ? el.trim().replace(new RegExp(hash.comma || '#', 'g'), ',') : el.trim());

    const result = [];

    for (let i = 0; i < keys.length; i += 2) {
        const name = keys[i];
        const nameHBS = name.includes('{{') ? await handlebars.compile(name)({ ...data, hash }) : false;

        if (!nameHBS && name.includes('{{')) continue;

        const key = keys[i + 1];

        const d1 = await format(data[key], key, data) || '-';

        result.push(`
            <div class="grid grid-cols-1 gap-1 py-3 sm:grid-cols-3 sm:gap-4 
                        even:bg-gray-50 dark:bg-transparent bg-white
                        text-[12px] text-gray-700 dark:text-white">
                <dt class="text-gray-900 dark:text-white">${nameHBS || name}</dt>
                <dd class="text-gray-700 dark:text-white sm:col-span-2">${d1}</dd>
            </div>
        `);

    }
    return `
        <div class="min-w-full relative overflow-auto 
            divide-y divide-gray-200 dark:divide-gray-700
            bg-white dark:bg-transparent 
            text-[12px] text-gray-600 dark:text-white">
            ${result.join('')}
        </div>
    `;
}