export interface ItemData {
    id: number;
    color: string;
    name: string;
    description: string;
    descriptionColor: string;
    rawDescription: string;
}

export interface DescriptionSegment {
    text: string;
    color: string;
}

let itemDatabase: Map<number, ItemData> | null = null;
let loadingPromise: Promise<Map<number, ItemData>> | null = null;

export async function loadItemDatabase(): Promise<Map<number, ItemData>> {
    if (itemDatabase) {
        return itemDatabase;
    }

    if (loadingPromise) {
        return loadingPromise;
    }

    loadingPromise = fetch('/img/RAE_Exported_Table.tab')
        .then(response => response.text())
        .then(text => {
            const db = new Map<number, ItemData>();
            const lines = text.split('\n');

            for (const line of lines) {
                if (!line.trim()) continue;

                const parts = line.split('\t');
                if (parts.length < 3) continue;

                const id = parseInt(parts[0], 10);
                if (isNaN(id)) continue;

                const color = parts[1] || 'FFFFFF';
                const name = parts[2] || '';
                const rawDescription = parts[3] || '';
                const { description, descriptionColor } = parseDescription(rawDescription);

                db.set(id, {
                    id,
                    color,
                    name: cleanItemName(name),
                    description,
                    descriptionColor,
                    rawDescription,
                });
            }

            itemDatabase = db;
            return db;
        })
        .catch(err => {
            console.error('Failed to load item database:', err);
            return new Map<number, ItemData>();
        });

    return loadingPromise;
}

function cleanItemName(name: string): string {
    return name.replace(/^N\/A/, '').trim();
}

function parseDescription(desc: string): { description: string; descriptionColor: string } {
    // Extract color code like ^ffcb4a from the beginning
    const colorMatch = desc.match(/^\^([0-9a-fA-F]{6})/);
    const descriptionColor = colorMatch ? colorMatch[1].toUpperCase() : 'AAAAAA';
    
    // Remove all color codes and clean up
    const description = desc
        .replace(/\^[0-9a-fA-F]{6}/g, '')
        .replace(/\\r/g, '\n')
        .trim();
    
    return { description, descriptionColor };
}

export function getItemData(id: number): ItemData | undefined {
    return itemDatabase?.get(id);
}

export function getItemName(id: number): string {
    const item = itemDatabase?.get(id);
    return item?.name || `Item #${id}`;
}

export function getItemColor(id: number): string {
    const item = itemDatabase?.get(id);
    return item?.color || 'FFFFFF';
}

export function getItemIconUrl(id: number): string {
    return `/img/Icons/${id}.png`;
}

export function isItemDatabaseLoaded(): boolean {
    return itemDatabase !== null;
}

export function parseDescriptionSegments(rawDescription: string): DescriptionSegment[] {
    if (!rawDescription) return [];
    
    const segments: DescriptionSegment[] = [];
    const regex = /\^([0-9a-fA-F]{6})/g;
    let lastIndex = 0;
    let currentColor = 'AAAAAA';
    let match;
    
    while ((match = regex.exec(rawDescription)) !== null) {
        if (match.index > lastIndex) {
            const text = rawDescription.substring(lastIndex, match.index)
                .replace(/\\r/g, '\n')
                .replace(/\r/g, '\n');
            if (text) {
                segments.push({ text, color: currentColor });
            }
        }
        currentColor = match[1].toUpperCase();
        lastIndex = regex.lastIndex;
    }
    
    if (lastIndex < rawDescription.length) {
        const text = rawDescription.substring(lastIndex)
            .replace(/\\r/g, '\n')
            .replace(/\r/g, '\n');
        if (text) {
            segments.push({ text, color: currentColor });
        }
    }
    
    return segments;
}
