<?php
/**
 * Creative Cards — interactive grid: click a card to load content panel.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

use AuraBuilder\Document\Node;
use AuraBuilder\Widgets\WidgetBase;

final class CreativeCardsWidget extends WidgetBase {

	public function get_type(): string {
		return 'creative_cards';
	}

	public function get_title(): string {
		return 'Grade criativa';
	}

	public function get_category(): string {
		return 'creative';
	}

	public function get_icon(): string {
		return 'creative';
	}

	public function get_defaults(): array {
		return array(
			'columns'        => '4',
			'columns_tablet' => '2',
			'columns_mobile' => '1',
			'gap'            => '16',
			'height'         => '160',
			'radius'         => '16',
			// items: one per line
			// image|IMAGE_URL|Title|Subtitle|Content (use \n for newlines in content via || )
			// color|#HEX|IconOrEmoji|Title|Subtitle|Content
			'items'          => "image||||Foto\ncolor|#e74c3c|▶|YouTube|Editor nativo|Hello Title||Item content. Double click to edit.||Lorem ipsum dolor sit amet.\ncolor|#9b59b6|👤|John Smith|Web Developer|Perfil||Desenvolvedor full-stack.\ncolor|#2ecc71|👤|Karen Pena|Photographer|Galeria||Fotografia de produto e retrato.",
			'open_first'     => '0',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$flag = static function ( $v, string $default = '0' ): string {
			if ( $v === null || $v === '' ) {
				return $default;
			}
			return ( $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes' ) ? '1' : '0';
		};

		return array(
			'columns'        => (string) max( 1, min( 6, (int) ( $settings['columns'] ?? 4 ) ) ),
			'columns_tablet' => (string) max( 1, min( 4, (int) ( $settings['columns_tablet'] ?? 2 ) ) ),
			'columns_mobile' => (string) max( 1, min( 2, (int) ( $settings['columns_mobile'] ?? 1 ) ) ),
			'gap'            => (string) max( 0, min( 48, (int) ( $settings['gap'] ?? 16 ) ) ),
			'height'         => (string) max( 80, min( 400, (int) ( $settings['height'] ?? 160 ) ) ),
			'radius'         => (string) max( 0, min( 40, (int) ( $settings['radius'] ?? 16 ) ) ),
			'items'          => $this->sanitize_items( (string) ( $settings['items'] ?? '' ) ),
			'open_first'     => $flag( $settings['open_first'] ?? null, '0' ),
		);
	}

	private function sanitize_items( string $raw ): string {
		// Cap size.
		if ( strlen( $raw ) > 20000 ) {
			$raw = substr( $raw, 0, 20000 );
		}
		return sanitize_textarea_field( $raw );
	}

	/**
	 * @return list<array{type:string,bg:string,image:string,icon:string,title:string,subtitle:string,content:string}>
	 */
	public static function parse_items( string $raw ): array {
		$out   = array();
		$lines = preg_split( '/\r\n|\r|\n/', $raw ) ?: array();
		foreach ( $lines as $line ) {
			$line = trim( $line );
			if ( $line === '' ) {
				continue;
			}
			// Split on | but allow || as paragraph break in content (last field).
			$parts = explode( '|', $line );
			$type  = strtolower( trim( (string) ( $parts[0] ?? 'color' ) ) );
			if ( ! in_array( $type, array( 'image', 'color', 'solid' ), true ) ) {
				$type = 'color';
			}
			if ( $type === 'solid' ) {
				$type = 'color';
			}

			$item = array(
				'type'     => $type,
				'bg'       => '#7c3aed',
				'image'    => '',
				'icon'     => '',
				'title'    => '',
				'subtitle' => '',
				'content'  => '',
			);

			if ( $type === 'image' ) {
				$item['image']    = esc_url_raw( trim( (string) ( $parts[1] ?? '' ) ) );
				$item['title']    = sanitize_text_field( trim( (string) ( $parts[2] ?? '' ) ) );
				$item['subtitle'] = sanitize_text_field( trim( (string) ( $parts[3] ?? '' ) ) );
				$item['content']  = self::join_content( array_slice( $parts, 4 ) );
			} else {
				$bg = trim( (string) ( $parts[1] ?? '#7c3aed' ) );
				if ( preg_match( '/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $bg ) ) {
					$item['bg'] = strtolower( $bg );
				}
				$item['icon']     = sanitize_text_field( trim( (string) ( $parts[2] ?? '' ) ) );
				$item['title']    = sanitize_text_field( trim( (string) ( $parts[3] ?? '' ) ) );
				$item['subtitle'] = sanitize_text_field( trim( (string) ( $parts[4] ?? '' ) ) );
				$item['content']  = self::join_content( array_slice( $parts, 5 ) );
			}
			$out[] = $item;
		}
		return $out;
	}

	/**
	 * @param list<string> $parts
	 */
	private static function join_content( array $parts ): string {
		// Empty segments become newlines (from ||).
		$text = '';
		foreach ( $parts as $i => $p ) {
			$p = (string) $p;
			if ( $i > 0 ) {
				$text .= ( $p === '' ? "\n\n" : ' ' );
			}
			$text .= $p;
		}
		return sanitize_textarea_field( trim( $text ) );
	}

	public function render( Node $node, array $context = array() ): string {
		$s     = $node->settings;
		$items = self::parse_items( (string) ( $s['items'] ?? '' ) );
		$uid   = 'abcc_' . preg_replace( '/[^a-zA-Z0-9_]/', '', $node->id );

		if ( ! $items ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-creative-cards ab-empty">Grade criativa — adicione itens no painel</div>'
				: '';
		}

		$cols_d = max( 1, min( 6, (int) ( $s['columns'] ?? 4 ) ) );
		$cols_t = max( 1, min( 4, (int) ( $s['columns_tablet'] ?? 2 ) ) );
		$cols_m = max( 1, min( 2, (int) ( $s['columns_mobile'] ?? 1 ) ) );
		$gap    = max( 0, min( 48, (int) ( $s['gap'] ?? 16 ) ) );
		$height = max( 80, min( 400, (int) ( $s['height'] ?? 160 ) ) );
		$radius = max( 0, min( 40, (int) ( $s['radius'] ?? 16 ) ) );

		$style = sprintf(
			'--ab-cc-cols:%d;--ab-cc-cols-t:%d;--ab-cc-cols-m:%d;--ab-cc-gap:%dpx;--ab-cc-h:%dpx;--ab-cc-r:%dpx',
			$cols_d,
			$cols_t,
			$cols_m,
			$gap,
			$height,
			$radius
		);

		$open_first = ( $s['open_first'] ?? '0' ) === '1';

		$html  = '<div class="ab-creative-cards" id="' . esc_attr( $uid ) . '" style="' . esc_attr( $style ) . '" data-ab-creative="1">';
		$html .= '<div class="ab-creative-cards__grid">';

		foreach ( $items as $i => $item ) {
			$active = $open_first && $i === 0 ? ' is-active' : '';
			$bg     = esc_attr( $item['bg'] );
			$html  .= '<button type="button" class="ab-creative-card' . $active . '" data-ab-cc-idx="' . esc_attr( (string) $i ) . '" style="--ab-cc-bg:' . $bg . '">';

			if ( $item['type'] === 'image' && $item['image'] !== '' ) {
				$html .= '<span class="ab-creative-card__media"><img src="' . esc_url( $item['image'] ) . '" alt="' . esc_attr( $item['title'] ) . '" loading="lazy"/></span>';
			} else {
				$html .= '<span class="ab-creative-card__solid" style="background:' . $bg . '">';
				if ( $item['icon'] !== '' ) {
					$html .= '<span class="ab-creative-card__icon">' . esc_html( $item['icon'] ) . '</span>';
				}
				if ( $item['title'] !== '' ) {
					$html .= '<span class="ab-creative-card__title">' . esc_html( $item['title'] ) . '</span>';
				}
				if ( $item['subtitle'] !== '' ) {
					$html .= '<span class="ab-creative-card__sub">' . esc_html( $item['subtitle'] ) . '</span>';
				}
				$html .= '</span>';
			}
			$html .= '</button>';
		}
		$html .= '</div>';

		// Content panels (one per item).
		$html .= '<div class="ab-creative-cards__panels">';
		foreach ( $items as $i => $item ) {
			$active = $open_first && $i === 0 ? ' is-open' : '';
			$bg     = esc_attr( $item['bg'] );
			// For image cards, use a default panel color.
			if ( $item['type'] === 'image' ) {
				$bg = '#7cb342';
			}
			$html .= '<div class="ab-creative-panel' . $active . '" data-ab-cc-panel="' . esc_attr( (string) $i ) . '" style="--ab-cc-panel-bg:' . $bg . '">';
			$html .= '<button type="button" class="ab-creative-panel__close" data-ab-cc-close aria-label="Fechar">×</button>';
			$html .= '<div class="ab-creative-panel__caret" aria-hidden="true"></div>';
			if ( $item['title'] !== '' || $item['content'] !== '' ) {
				// Prefer first line of content as heading if structured with Hello Title style
				$lines = preg_split( '/\n+/', $item['content'] ) ?: array();
				$head  = $item['title'];
				$body  = $item['content'];
				if ( $head === '' && count( $lines ) > 0 ) {
					$head = array_shift( $lines );
					$body = implode( "\n\n", $lines );
				}
				if ( $head !== '' ) {
					$html .= '<h3 class="ab-creative-panel__title">' . esc_html( $head ) . '</h3>';
				}
				if ( $body !== '' ) {
					$paras = preg_split( '/\n\n+/', $body ) ?: array( $body );
					foreach ( $paras as $p ) {
						$p = trim( $p );
						if ( $p !== '' ) {
							$html .= '<p class="ab-creative-panel__text">' . esc_html( $p ) . '</p>';
						}
					}
				}
				if ( $item['subtitle'] !== '' && $item['type'] === 'image' ) {
					$html .= '<p class="ab-creative-panel__meta">' . esc_html( $item['subtitle'] ) . '</p>';
				}
			} else {
				$html .= '<p class="ab-creative-panel__text">' . esc_html__( 'Sem conteúdo neste item.', 'auranet-page-theme-builder' ) . '</p>';
			}
			$html .= '</div>';
		}
		$html .= '</div></div>';

		return $html;
	}
}
