const WEBSITE_URL = process.env.WEBSITE_URL || '';

export const PRIVATE_CAMPAIGN_SHARE_TITLE = 'Private campaign';

/**
 * Same OG image as root layout metadata (`layout.tsx` openGraph.images).
 * Relative path on purpose: absolute `{WEBSITE_URL}/...` makes Next fetch the
 * image during generateMetadata, which hairpins through Cloudflare and times out.
 * metadataBase turns this into an absolute og:image for crawlers.
 */
export const CONNECTOR_DEFAULT_OG_IMAGE_PATH = '/assets/images/bee-logo.png';

export const buildConnectorDefaultOgImageUrl = () => CONNECTOR_DEFAULT_OG_IMAGE_PATH;

export const getInfluencerJobUrl = (slug: string) => {
    const base = WEBSITE_URL.replace(/\/$/, '');
    return `${base}/influencer/jobs/${slug}`;
};

export const trimShareDescription = (text: string | null | undefined, maxLength = 160) => {
    if (!text) return '';
    const plain = text
        .replace(/<[^>]*>/g, ' ')
        .replace(/\s+/g, ' ')
        .trim();
    if (plain.length <= maxLength) return plain;
    return `${plain.slice(0, maxLength - 1).trim()}…`;
};

const getAttachmentFilename = (item: unknown): string | undefined => {
    if (!item) return undefined;
    if (typeof item === 'string') return item;
    if (typeof item === 'object') {
        const obj = item as Record<string, unknown>;
        if (typeof obj.fileName === 'string') return obj.fileName;
        const [firstKey] = Object.keys(obj);
        return firstKey || undefined;
    }
    return undefined;
};

export const buildCampaignOgImageUrl = (
    attachment: unknown,
    campaignPath?: string | null,
) => {
    const items = Array.isArray(attachment) ? attachment : attachment ? [attachment] : [];
    const file = getAttachmentFilename(items[0]);
    if (!file) return undefined;
    if (file.startsWith('http://') || file.startsWith('https://')) return file;
    if (!campaignPath) return undefined;
    const prefix = campaignPath.replace(/\/$/, '');
    return `${prefix}/${file.replace(/^\//, '')}`;
};

/**
 * `campaign_image` may be a plain filename string (old format) or an object
 * keyed by filename with focal-point coords (new format), e.g.
 * `{ 'fabz-kopter_569055074.jpg': { x: 74.6, y: 36.7 } }`.
 * Returns just the filename string for both shapes.
 */
export const getCampaignImageFilename = (
    campaignImage: string | Record<string, unknown> | null | undefined,
): string | undefined => {
    if (!campaignImage) return undefined;
    if (typeof campaignImage === 'string') return campaignImage;
    if (typeof campaignImage === 'object') {
        const [firstKey] = Object.keys(campaignImage);
        return firstKey || undefined;
    }
    return undefined;
};

/**
 * Full campaign banner URL for link previews.
 * API returns `campaign_image` as filename only; `baseUrl` is only used here.
 */
export const buildPublicCampaignBannerUrl = (
    campaignImage: string | Record<string, unknown> | null | undefined,
    baseUrl?: string | null,
) => {
    const filename = getCampaignImageFilename(campaignImage);
    if (!filename) return undefined;
    if (filename.startsWith('http://') || filename.startsWith('https://')) {
        return filename;
    }
    if (!baseUrl) return undefined;
    const prefix = baseUrl.replace(/\/$/, '');
    const path = filename.replace(/^\//, '');
    return `${prefix}/${path}`;
};
