/**
 * API Client
 * WordPress REST API クライアント
 */

/**
 * APIクライアントクラス
 */
class ZenblocksApiClient {
	constructor() {
		this.baseUrl = window.zenBlocksData?.apiUrl || '/wp-json/zenblocks/v1';
		this.nonce = window.zenBlocksData?.nonce || '';
	}

	/**
	 * GETリクエスト
	 * @param {string} endpoint
	 * @return {Promise<Object>}
	 */
	async get( endpoint ) {
		try {
			const response = await fetch( `${ this.baseUrl }${ endpoint }`, {
				method: 'GET',
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': this.nonce,
				},
			} );

			if ( ! response.ok ) {
				throw new Error( `HTTP error! status: ${ response.status }` );
			}

			return await response.json();
		} catch ( error ) {
			console.error( 'API GET Error:', error.message );
			throw error;
		}
	}

	/**
	 * POSTリクエスト
	 * @param {string} endpoint
	 * @param {Object} data
	 * @return {Promise<Object>}
	 */
	async post( endpoint, data = {} ) {
		try {
			const response = await fetch( `${ this.baseUrl }${ endpoint }`, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': this.nonce,
				},
				body: JSON.stringify( data ),
			} );

			if ( ! response.ok ) {
				throw new Error( `HTTP error! status: ${ response.status }` );
			}

			return await response.json();
		} catch ( error ) {
			console.error( 'API POST Error:', error.message );
			throw error;
		}
	}

	/**
	 * PUTリクエスト
	 * @param {string} endpoint
	 * @param {Object} data
	 * @return {Promise<Object>}
	 */
	async put( endpoint, data = {} ) {
		try {
			const response = await fetch( `${ this.baseUrl }${ endpoint }`, {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': this.nonce,
				},
				body: JSON.stringify( data ),
			} );

			if ( ! response.ok ) {
				throw new Error( `HTTP error! status: ${ response.status }` );
			}

			return await response.json();
		} catch ( error ) {
			console.error( 'API PUT Error:', error.message );
			throw error;
		}
	}

	/**
	 * DELETEリクエスト
	 * @param {string} endpoint
	 * @return {Promise<Object>}
	 */
	async delete( endpoint ) {
		try {
			const response = await fetch( `${ this.baseUrl }${ endpoint }`, {
				method: 'DELETE',
				headers: {
					'Content-Type': 'application/json',
					'X-WP-Nonce': this.nonce,
				},
			} );

			if ( ! response.ok ) {
				throw new Error( `HTTP error! status: ${ response.status }` );
			}

			return await response.json();
		} catch ( error ) {
			console.error( 'API DELETE Error:', error.message );
			throw error;
		}
	}
}

/**
 * APIクライアントの初期化
 */
export function initApiClient() {
	const apiClient = new ZenblocksApiClient();
	window.zenBlocks.api = apiClient;

	return apiClient;
}

/**
 * グローバルAPIクライアントを取得
 * @return {ZenblocksApiClient}
 */
export function getApiClient() {
	if ( ! window.zenBlocks.api ) {
		return initApiClient();
	}
	return window.zenBlocks.api;
}

export default ZenblocksApiClient;
