<?php
/**
 * Seeds Niwa's local template idea library.
 *
 * @package Niwa_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Niwa_AI_Template_Seeder {
	const OPTION_VERSION = 'niwa_ai_template_library_seed_version';
	const SEED_VERSION   = 5;

	private $repository;

	public function __construct( Niwa_AI_Template_Repository $repository ) {
		$this->repository = $repository;
	}

	public function register_hooks() {
		add_action( 'init', array( $this, 'maybe_seed' ), 20 );
	}

	public function maybe_seed() {
		$current = intval( get_option( self::OPTION_VERSION, 0 ) );
		if ( $current >= self::SEED_VERSION ) {
			return;
		}

		$order = 0;
		foreach ( $this->seed_templates() as $seed ) {
			$this->repository->upsert_seed_template( $seed, $order++ );
		}
		update_option( self::OPTION_VERSION, self::SEED_VERSION, false );
	}

	public function seed_templates() {
		$asset = NIWA_AI_URL . 'assets/img/template-library/seed/';
		$templates = array(
			array(
				'slug'           => 'image-reveal-menu',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_FEATURED,
				'title'          => 'Image reveal menu',
				'subtitle'       => 'Reveal images on hover with menu',
				'preview_url'    => $asset . 'image-reveal-menu.svg',
				'output_mode'    => 'elementor_widget',
				'prompt'         => 'Build an interactive image reveal menu with a vertical text menu, smooth hover transitions, responsive layout, clean CSS, and shortcode fallback.',
				'preview_prompt' => 'Soft lavender admin-card preview of a hover image reveal menu, vertical menu labels on the left, blurred city/product image on the right, elegant UI mockup, no logos.',
			),
			array(
				'slug'           => 'team-slider-accordion',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_FEATURED,
				'title'          => 'Team slider accordion',
				'subtitle'       => 'Expand cards in image strips',
				'preview_url'    => $asset . 'team-slider-accordion.svg',
				'output_mode'    => 'elementor_widget',
				'prompt'         => 'Create a responsive team slider accordion widget with expandable portrait cards, name/job controls, accessible keyboard focus, CSS transitions, and shortcode fallback.',
				'preview_prompt' => 'Polished UI preview of horizontal portrait cards expanding like an accordion, soft shadows, lavender and neutral colors, no text except tiny UI hints.',
			),
			array(
				'slug'           => 'publishing-activity-widget',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_FEATURED,
				'title'          => 'Publishing activity widget',
				'subtitle'       => 'Visualize site-wide content publishing history',
				'preview_url'    => $asset . 'publishing-activity-widget.svg',
				'output_mode'    => 'admin_snippet',
				'prompt'         => 'Create a WordPress admin dashboard widget that shows site-wide publishing activity for the last 30 days as a heatmap, with CPT filters and lightweight queries.',
				'preview_prompt' => 'Admin analytics card preview with a calendar heatmap grid, pink and lavender activity squares, white dashboard card, clean work-focused UI.',
			),
			array(
				'slug'           => 'custom-post-type',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_FEATURED,
				'title'          => 'Custom post type',
				'subtitle'       => 'Register a new content type via code',
				'preview_url'    => $asset . 'custom-post-type.svg',
				'output_mode'    => 'admin_snippet',
				'prompt'         => 'Generate a safe WordPress custom post type snippet with labels, capabilities, menu icon, REST support, admin columns, and clean unregister notes.',
				'preview_prompt' => 'WordPress admin list preview with sidebar and content table, soft lavender glow, compact custom post type management UI, no brand marks.',
			),
			array(
				'slug'           => 'testimonial-carousel-widget',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_ELEMENTOR_WIDGET,
				'title'          => 'Testimonial carousel widget',
				'subtitle'       => 'Elementor-ready rotating social proof',
				'preview_url'    => $asset . 'testimonial-carousel-widget.svg',
				'output_mode'    => 'elementor_widget',
				'prompt'         => 'Create an Elementor testimonial carousel widget with repeater controls, avatar/image support, rating, responsive slides, and shortcode fallback.',
				'preview_prompt' => 'UI preview of testimonial cards in a carousel, avatars, rating dots, clean white panels on lavender background.',
			),
			array(
				'slug'           => 'pricing-feature-cards',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_ELEMENTOR_WIDGET,
				'title'          => 'Pricing feature cards',
				'subtitle'       => 'Reusable Elementor pricing grid',
				'preview_url'    => $asset . 'pricing-feature-cards.svg',
				'output_mode'    => 'elementor_widget',
				'prompt'         => 'Create an Elementor pricing cards widget with plan repeater, highlighted plan, CTA buttons, feature lists, and shortcode fallback.',
				'preview_prompt' => 'Three modern pricing cards, one highlighted, simple feature rows, lavender accent, clean UI mockup.',
			),
			array(
				'slug'           => 'admin-dashboard-widget',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_WORDPRESS_ADMIN_SNIPPET,
				'title'          => 'Admin dashboard widget',
				'subtitle'       => 'Surface operational metrics in wp-admin',
				'preview_url'    => $asset . 'admin-dashboard-widget.svg',
				'output_mode'    => 'admin_snippet',
				'prompt'         => 'Create a WordPress admin dashboard widget snippet with configurable metrics, capability checks, escaping, and no frontend output.',
				'preview_prompt' => 'WordPress admin dashboard card with compact KPI tiles and small trend lines, quiet professional UI.',
			),
			array(
				'slug'           => 'admin-column-enhancer',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_WORDPRESS_ADMIN_SNIPPET,
				'title'          => 'Admin column enhancer',
				'subtitle'       => 'Add sortable columns to content lists',
				'preview_url'    => $asset . 'admin-column-enhancer.svg',
				'output_mode'    => 'admin_snippet',
				'prompt'         => 'Generate a WordPress admin columns snippet for a selected post type, including sortable meta column support and safe escaping.',
				'preview_prompt' => 'Admin table with highlighted custom columns, tiny filter controls, crisp neutral WordPress-style UI.',
			),
			array(
				'slug'           => 'announcement-bar',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_WEBSITE_SNIPPET,
				'title'          => 'Announcement bar',
				'subtitle'       => 'Site-wide responsive promo strip',
				'preview_url'    => $asset . 'announcement-bar.svg',
				'output_mode'    => 'shortcode',
				'prompt'         => 'Create a responsive announcement bar snippet with text, link, dismiss button, cookie/session persistence, shortcode and optional auto-inject hook.',
				'preview_prompt' => 'Website top announcement bar preview with button and close icon, light lavender background, modern ecommerce UI.',
			),
			array(
				'slug'           => 'faq-accordion',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_WEBSITE_SNIPPET,
				'title'          => 'FAQ accordion',
				'subtitle'       => 'Accessible expandable answers',
				'preview_url'    => $asset . 'faq-accordion.svg',
				'output_mode'    => 'shortcode',
				'prompt'         => 'Create an accessible FAQ accordion shortcode with schema markup option, keyboard support, smooth animation, and customizable colors.',
				'preview_prompt' => 'FAQ accordion preview with stacked rounded rows, one expanded answer, lavender accents, clean website section.',
			),
			array(
				'slug'           => 'product-finder-quiz',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_VISUAL_APP,
				'title'          => 'Product finder quiz',
				'subtitle'       => 'Guide visitors to the right offer',
				'preview_url'    => $asset . 'product-finder-quiz.svg',
				'output_mode'    => 'visual_app',
				'prompt'         => 'Create a visual product finder quiz with multiple steps, scoring, result cards, CTA, shortcode wrapper, and no external dependencies.',
				'preview_prompt' => 'Interactive quiz app preview with step cards, progress indicator, selectable choices, polished lavender UI.',
			),
			array(
				'slug'           => 'quote-calculator',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_VISUAL_APP,
				'title'          => 'Quote calculator',
				'subtitle'       => 'Interactive estimate mini app',
				'preview_url'    => $asset . 'quote-calculator.svg',
				'output_mode'    => 'visual_app',
				'prompt'         => 'Create a shortcode quote calculator with inputs, live estimated total, validation, result summary, and optional lead capture handoff.',
				'preview_prompt' => 'Quote calculator UI preview with sliders, numeric fields, result total card, soft professional colors.',
			),
			array(
				'slug'           => 'habit-tracker',
				'type'           => Niwa_AI_Template_Library_Types::TYPE_VISUAL_APP,
				'title'          => 'Habit tracker',
				'subtitle'       => 'Track daily actions and streaks',
				'preview_url'    => $asset . 'habit-tracker.svg',
				'output_mode'    => 'visual_app',
				'prompt'         => 'Create a responsive visual habit tracker with configurable habits, seven-day check grid, progress percentage, streak counter, reset action, and shortcode fallback.',
				'preview_prompt' => 'Compact weekly habit tracker app preview with progress pill, streak counter, reset button, and clean seven-day grid.',
			),
		);
		return array_map( array( $this, 'enrich_seed_template' ), $templates );
	}

	private function enrich_seed_template( $seed ) {
		$title = isset( $seed['title'] ) ? (string) $seed['title'] : '';
		$type  = isset( $seed['type'] ) ? (string) $seed['type'] : Niwa_AI_Template_Library_Types::TYPE_FEATURED;
		$mode  = isset( $seed['output_mode'] ) ? (string) $seed['output_mode'] : Niwa_AI_Template_Library_Types::default_output_mode_for_type( $type );
		if ( empty( $seed['agent_prompt'] ) ) {
			$seed['agent_prompt'] = 'Use this template when the founder asks Niwa to build "' . $title . '". Read the current page/site context first, adapt copy, colors, spacing, CTA, data and images to the actual business, then choose Elementor insertion when Elementor is active or shortcode fallback when it is not.';
		}
		if ( empty( $seed['manifest'] ) || ! is_array( $seed['manifest'] ) ) {
			$seed['manifest'] = array(
				'version'      => 1,
				'agent_use'    => array( 'discover_context', 'adapt_content', 'build_elementor_or_shortcode', 'verify_output' ),
				'output_mode'  => $mode,
				'fallback'     => 'shortcode',
				'requires_llm' => true,
			);
		}
		if ( empty( $seed['elementor_schema'] ) || ! is_array( $seed['elementor_schema'] ) ) {
			$seed['elementor_schema'] = $this->default_elementor_schema( $seed );
		}
		return $seed;
	}

	private function default_elementor_schema( $seed ) {
		$slug  = isset( $seed['slug'] ) ? (string) $seed['slug'] : '';
		$title = isset( $seed['title'] ) ? (string) $seed['title'] : 'Niwa template';
		if ( false !== strpos( $slug, 'image-reveal' ) ) {
			return array(
				'kind'        => 'image_reveal_menu',
				'title'       => $title,
				'eyebrow'     => 'Explore collections',
				'intro'       => 'Hover or focus an item to reveal the image and story behind each collection.',
				'cta_text'    => 'Explore collection',
				'cta_url'     => '#shop',
				'accent'      => '#d6b46a',
				'items'       => array(
					array(
						'label'       => 'Fresh Truffles',
						'description' => 'Seasonal black and white truffles prepared for premium dishes.',
						'image_url'   => 'https://images.unsplash.com/photo-1604908176997-125f25cc6f3d?auto=format&fit=crop&w=1200&q=80',
					),
					array(
						'label'       => 'Truffle Pantry',
						'description' => 'Oils, creams, salts, and everyday finishing accents.',
						'image_url'   => 'https://images.unsplash.com/photo-1556911220-bff31c812dba?auto=format&fit=crop&w=1200&q=80',
					),
					array(
						'label'       => 'Gift Sets',
						'description' => 'Curated gourmet bundles with a polished retail feel.',
						'image_url'   => 'https://images.unsplash.com/photo-1513885535751-8b9238bd345a?auto=format&fit=crop&w=1200&q=80',
					),
					array(
						'label'       => 'Recipe Pairings',
						'description' => 'Practical serving ideas for pasta, eggs, risotto, and cheese.',
						'image_url'   => 'https://images.unsplash.com/photo-1551218808-94e220e084d2?auto=format&fit=crop&w=1200&q=80',
					),
				),
			);
		}
		if ( false !== strpos( $slug, 'team' ) ) {
			return array(
				'kind'  => 'team_accordion',
				'title' => $title,
				'items' => array(
					array( 'name' => 'Founder', 'role' => 'Strategy' ),
					array( 'name' => 'Designer', 'role' => 'Creative' ),
					array( 'name' => 'Support', 'role' => 'Operations' ),
				),
			);
		}
		if ( false !== strpos( $slug, 'testimonial' ) ) {
			return array(
				'kind'  => 'testimonial_carousel',
				'title' => $title,
				'items' => array(
					array( 'content' => 'Niwa adapted the page quickly and clearly.', 'name' => 'Customer' ),
					array( 'content' => 'The section matched our offer and tone.', 'name' => 'Founder' ),
				),
			);
		}
		if ( false !== strpos( $slug, 'pricing' ) ) {
			return array( 'kind' => 'pricing_cards', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'publishing-activity' ) ) {
			return array( 'kind' => 'publishing_activity_widget', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'custom-post-type' ) ) {
			return array( 'kind' => 'custom_post_type_preview', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'admin-dashboard' ) ) {
			return array( 'kind' => 'admin_dashboard_preview', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'admin-column' ) ) {
			return array( 'kind' => 'admin_column_preview', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'announcement' ) ) {
			return array(
				'kind'     => 'announcement_bar',
				'title'    => $title,
				'message'  => 'Limited seasonal drop is live now.',
				'cta_text' => 'Shop the drop',
				'cta_url'  => '#shop',
			);
		}
		if ( false !== strpos( $slug, 'faq' ) ) {
			return array( 'kind' => 'faq_accordion', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'quiz' ) ) {
			return array( 'kind' => 'product_finder_quiz', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'calculator' ) ) {
			return array( 'kind' => 'quote_calculator', 'title' => $title );
		}
		if ( false !== strpos( $slug, 'habit-tracker' ) || false !== strpos( $slug, 'habit' ) ) {
			return array(
				'kind'     => 'habit_tracker',
				'title'    => $title,
				'eyebrow'  => 'Visual app',
				'intro'    => 'Track daily actions, completion percentage, and current streak in a compact responsive grid.',
				'cta_text' => 'Reset week',
				'items'    => array(
					array( 'label' => 'Plan', 'description' => 'Map the next action.' ),
					array( 'label' => 'Create', 'description' => 'Produce the deliverable.' ),
					array( 'label' => 'Publish', 'description' => 'Ship the update.' ),
					array( 'label' => 'Follow up', 'description' => 'Close the loop.' ),
					array( 'label' => 'Review', 'description' => 'Check quality and results.' ),
				),
			);
		}
		if ( false !== strpos( $slug, 'visual-app' ) ) {
			return array( 'kind' => 'visual_app', 'title' => $title );
		}
		return array( 'kind' => 'content_section', 'title' => $title );
	}
}
