/** أدوات تنظيف نصوص الـ API (HTML من محرر المحتوى) لاستخدامها في الوصف و JSON-LD */
export function stripHtml(html?: string | null): string {
    if (!html || typeof html !== "string") return "";
    return html
        .replace(/<style[\s\S]*?<\/style>|<script[\s\S]*?<\/script>/gi, " ")
        .replace(/<[^>]+>/g, " ")
        .replace(/&nbsp;/g, " ")
        .replace(/&amp;/g, "&")
        .replace(/&quot;/g, '"')
        .replace(/&#0?39;|&apos;/g, "'")
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/\s+/g, " ")
        .trim();
}

export function truncate(text: string, max = 160): string {
    if (text.length <= max) return text;
    const cut = text.slice(0, max - 1);
    const lastSpace = cut.lastIndexOf(" ");
    return `${(lastSpace > max * 0.6 ? cut.slice(0, lastSpace) : cut).trim()}…`;
}

/** أول قيمة نصية غير فارغة من قائمة حقول محتملة */
export function firstText(obj: any, fields: string[]): string {
    for (const f of fields) {
        const v = f.split(".").reduce((o: any, k) => (o == null ? undefined : o[k]), obj);
        const clean = stripHtml(typeof v === "string" ? v : "");
        if (clean) return clean;
    }
    return "";
}

export function toIsoDate(v?: string | null): string | undefined {
    if (!v) return undefined;
    const d = new Date(v);
    return Number.isNaN(d.getTime()) ? undefined : d.toISOString();
}
