/**
 * integrations.ts — External service integrations for editors.
 *
 * Stock image pickers (Unsplash/Pexels), Adobe CC connector,
 * Figma import/export, template library, and AI image generation.
 */
// ── Unsplash Integration ────────────────────────────────────────
class UnsplashProvider {
    constructor(accessKey) {
        this.accessKey = accessKey;
    }
    async search(options) {
        const { query, page = 1, perPage = 20, orientation } = options;
        const params = new URLSearchParams({
            query,
            page: String(page),
            per_page: String(perPage),
            ...(orientation ? { orientation } : {}),
        });
        const response = await fetch(`https://api.unsplash.com/search/photos?${params}`, { headers: { Authorization: `Client-ID ${this.accessKey}` } });
        if (!response.ok)
            throw new Error(`Unsplash API error: ${response.status}`);
        const data = await response.json();
        return data.results.map((r) => ({
            id: String(r.id),
            url: String(r.urls.regular),
            thumbnailUrl: String(r.urls.thumb),
            author: String(r.user.name),
            source: "unsplash",
            width: Number(r.width),
            height: Number(r.height),
            description: r.description ? String(r.description) : undefined,
        }));
    }
}
// ── Pexels Integration ──────────────────────────────────────────
class PexelsProvider {
    constructor(apiKey) {
        this.apiKey = apiKey;
    }
    async search(options) {
        const { query, page = 1, perPage = 20, orientation } = options;
        const params = new URLSearchParams({
            query,
            page: String(page),
            per_page: String(perPage),
            ...(orientation ? { orientation } : {}),
        });
        const response = await fetch(`https://api.pexels.com/v1/search?${params}`, { headers: { Authorization: this.apiKey } });
        if (!response.ok)
            throw new Error(`Pexels API error: ${response.status}`);
        const data = await response.json();
        return data.photos.map((p) => {
            var _a;
            return ({
                id: String(p.id),
                url: String(p.src.large),
                thumbnailUrl: String(p.src.tiny),
                author: String(p.photographer),
                source: "pexels",
                width: Number(p.width),
                height: Number(p.height),
                description: String((_a = p.alt) !== null && _a !== void 0 ? _a : ""),
            });
        });
    }
}
class AdobeCCConnector {
    constructor(config) {
        this.config = config;
    }
    /** Get the OAuth authorization URL. */
    getAuthUrl() {
        const params = new URLSearchParams({
            client_id: this.config.clientId,
            redirect_uri: this.config.redirectUri,
            scope: "openid,creative_sdk",
            response_type: "code",
        });
        return `https://ims-na1.adobelogin.com/ims/authorize/v2?${params}`;
    }
    /** Import a file from Adobe CC Libraries. */
    async importFromLibrary(accessToken, assetId) {
        const response = await fetch(`https://cc-api-storage.adobe.io/assets/${encodeURIComponent(assetId)}/rendition`, { headers: { Authorization: `Bearer ${accessToken}`, "x-api-key": this.config.clientId } });
        if (!response.ok)
            throw new Error(`Adobe CC API error: ${response.status}`);
        return response.blob();
    }
}
// ── Figma Integration ───────────────────────────────────────────
class FigmaConnector {
    constructor(accessToken) {
        this.accessToken = accessToken;
    }
    /** Import nodes from a Figma file. */
    async importFile(fileKey, nodeIds) {
        var _a;
        const url = `https://api.figma.com/v1/files/${encodeURIComponent(fileKey)}` +
            ((nodeIds === null || nodeIds === void 0 ? void 0 : nodeIds.length) ? `?ids=${nodeIds.map(encodeURIComponent).join(",")}` : "");
        const response = await fetch(url, {
            headers: { "X-Figma-Token": this.accessToken },
        });
        if (!response.ok)
            throw new Error(`Figma API error: ${response.status}`);
        const data = await response.json();
        const nodes = this.extractNodes(data.document);
        // Fetch images for nodes
        const images = new Map();
        if (nodes.length > 0) {
            const ids = nodes.map((n) => n.id).join(",");
            const imgResp = await fetch(`https://api.figma.com/v1/images/${encodeURIComponent(fileKey)}?ids=${ids}&format=svg`, { headers: { "X-Figma-Token": this.accessToken } });
            if (imgResp.ok) {
                const imgData = await imgResp.json();
                for (const [id, imgUrl] of Object.entries((_a = imgData.images) !== null && _a !== void 0 ? _a : {})) {
                    if (typeof imgUrl === "string") {
                        const blobResp = await fetch(imgUrl);
                        if (blobResp.ok)
                            images.set(id, await blobResp.blob());
                    }
                }
            }
        }
        return { nodes, images };
    }
    /** Export a design to Figma (via plugin API—returns Figma plugin code). */
    exportToFigmaPlugin(svg, nodeName = "Nice2Dev Export") {
        return `// Figma Plugin — paste into Figma Plugin Console
const node = figma.createNodeFromSvg(\`${svg.replace(/`/g, "\\`")}\`);
node.name = "${nodeName}";
figma.currentPage.appendChild(node);
figma.viewport.scrollAndZoomIntoView([node]);
figma.closePlugin("Imported from Nice2Dev");`;
    }
    extractNodes(document) {
        const nodes = [];
        const walk = (node) => {
            var _a, _b, _c;
            if (node.type && node.id) {
                const abs = node.absoluteBoundingBox;
                nodes.push({
                    id: String(node.id),
                    name: String((_a = node.name) !== null && _a !== void 0 ? _a : ""),
                    type: String(node.type),
                    width: (_b = abs === null || abs === void 0 ? void 0 : abs.width) !== null && _b !== void 0 ? _b : 0,
                    height: (_c = abs === null || abs === void 0 ? void 0 : abs.height) !== null && _c !== void 0 ? _c : 0,
                });
            }
            const children = node.children;
            if (Array.isArray(children))
                children.forEach(walk);
        };
        walk(document);
        return nodes;
    }
}
// ── Template Library ────────────────────────────────────────────
class TemplateLibrary {
    constructor() {
        this.templates = [];
    }
    /** Register a template. */
    register(template) {
        this.templates.push(template);
    }
    /** Get all templates. */
    getAll() {
        return [...this.templates];
    }
    /** Get templates by category. */
    getByCategory(category) {
        return this.templates.filter((t) => t.category === category);
    }
    /** Get all categories. */
    getCategories() {
        return [...new Set(this.templates.map((t) => t.category))];
    }
    /** Search templates by name. */
    search(query) {
        const lower = query.toLowerCase();
        return this.templates.filter((t) => t.name.toLowerCase().includes(lower));
    }
}
// ── AI Image Generation ─────────────────────────────────────────
async function generateAIImage(options) {
    var _a, _b;
    const { prompt, width = 512, height = 512, style = "realistic", provider, apiKey, apiUrl } = options;
    if (!apiKey)
        throw new Error("API key is required for AI image generation");
    let url;
    let body;
    const headers = { "Content-Type": "application/json" };
    switch (provider) {
        case "openai":
            url = "https://api.openai.com/v1/images/generations";
            headers["Authorization"] = `Bearer ${apiKey}`;
            body = JSON.stringify({
                model: "dall-e-3",
                prompt: `${prompt} (style: ${style})`,
                n: 1,
                size: `${width}x${height}`,
                response_format: "url",
            });
            break;
        case "stability":
            url = "https://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-image";
            headers["Authorization"] = `Bearer ${apiKey}`;
            body = JSON.stringify({
                text_prompts: [{ text: prompt, weight: 1 }],
                cfg_scale: 7,
                width, height,
                samples: 1,
                steps: 30,
                style_preset: style === "pixel-art" ? "pixel-art" : style === "vector" ? "line-art" : undefined,
            });
            break;
        case "custom":
            if (!apiUrl)
                throw new Error("Custom API URL is required");
            url = apiUrl;
            headers["Authorization"] = `Bearer ${apiKey}`;
            body = JSON.stringify({ prompt, width, height, style });
            break;
        default:
            throw new Error(`Unknown AI provider: ${provider}`);
    }
    const response = await fetch(url, { method: "POST", headers, body });
    if (!response.ok)
        throw new Error(`AI generation failed: ${response.status}`);
    const data = await response.json();
    // Extract image URL based on provider
    let imageUrl;
    if (provider === "openai") {
        imageUrl = data.data[0].url;
    }
    else if (provider === "stability") {
        imageUrl = `data:image/png;base64,${data.artifacts[0].base64}`;
    }
    else {
        imageUrl = (_b = (_a = data.url) !== null && _a !== void 0 ? _a : data.image) !== null && _b !== void 0 ? _b : "";
    }
    const imgResp = imageUrl.startsWith("data:") ? null : await fetch(imageUrl);
    const imageBlob = imgResp ? await imgResp.blob() : base64ToBlob(imageUrl.split(",")[1], "image/png");
    return { imageUrl, imageBlob, metadata: data };
}
function base64ToBlob(base64, mimeType) {
    const bytes = atob(base64);
    const arr = new Uint8Array(bytes.length);
    for (let i = 0; i < bytes.length; i++)
        arr[i] = bytes.charCodeAt(i);
    return new Blob([arr], { type: mimeType });
}

export { AdobeCCConnector, FigmaConnector, PexelsProvider, TemplateLibrary, UnsplashProvider, generateAIImage };
//# sourceMappingURL=integrations.js.map
