<?php
/**
 * Plugin Name: Vareon Calculator Suite Lite
 * Plugin URI: https://vareon.dev
 * Description: A collection of lightweight calculators for WordPress.
 * Version: 1.5.0
 * Author: Vareon
 * Author URI: https://vareon.dev
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: vareon-calculator-suite-lite
 * Domain Path: /languages
 * Requires at least: 6.3
 * Tested up to: 6.9
 * Requires PHP: 8.0
 *
 * @package Vareon_Calculator_Suite_Lite
 */

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

if ( defined( 'VAREONCALC_PRO_VER' ) ) {
	add_action(
		'admin_notices',
		function () {
			printf(
				'<div class="notice notice-error"><p><strong>%s</strong> %s</p></div>',
				esc_html__( 'Vareon Calculator Suite Lite:', 'vareon-calculator-suite-lite' ),
				esc_html__( 'Cannot activate Lite version while Pro version is active. Please deactivate Vareon Calculator Suite Pro first.', 'vareon-calculator-suite-lite' )
			);
		}
	);
	return;
}

define( 'VAREONCALC_LITE_VER', '1.5.0' );
define( 'VAREONCALC_LITE_URL', plugin_dir_url( __FILE__ ) );
define( 'VAREONCALC_LITE_DIR', plugin_dir_path( __FILE__ ) );

// Legacy constants for backwards compatibility.
define( 'VAREONCALC_VER', VAREONCALC_LITE_VER );
define( 'VAREONCALC_URL', VAREONCALC_LITE_URL );
define( 'VAREONCALC_DIR', VAREONCALC_LITE_DIR );

require_once VAREONCALC_DIR . 'inc/version.php';
require_once VAREONCALC_DIR . 'inc/upgrade-prompts.php';
require_once VAREONCALC_DIR . 'inc/admin-notices.php';
require_once VAREONCALC_DIR . 'inc/review-cta.php';

require_once VAREONCALC_DIR . 'inc/utils.php';
require_once VAREONCALC_DIR . 'inc/currency-catalog.php';
require_once VAREONCALC_DIR . 'inc/settings.php';
require_once VAREONCALC_DIR . 'inc/preview-endpoint.php';
require_once VAREONCALC_DIR . 'inc/shortcode.php';
require_once VAREONCALC_DIR . 'inc/blocks.php';
require_once VAREONCALC_DIR . 'inc/onboarding.php';
require_once VAREONCALC_DIR . 'inc/privacy.php';

/**
 * Register shared frontend assets.
 */
function vareoncalc_register_assets() {
	$styles_asset = function_exists( 'vareoncalc_get_resolved_asset' )
		? vareoncalc_get_resolved_asset( 'assets/styles.css' )
		: array(
			'url'     => VAREONCALC_URL . 'assets/styles.css',
			'version' => VAREONCALC_VER,
		);
	wp_register_style( 'vareoncalc-style', $styles_asset['url'], array(), $styles_asset['version'] );

	$loader_asset = function_exists( 'vareoncalc_get_resolved_asset' )
		? vareoncalc_get_resolved_asset( 'js/vareoncalc-loader.js' )
		: array(
			'url'     => VAREONCALC_URL . 'js/vareoncalc-loader.js',
			'version' => function_exists( 'vareoncalc_get_asset_version' ) ? vareoncalc_get_asset_version() : VAREONCALC_VER,
		);
	wp_register_script( 'vareoncalc-loader', $loader_asset['url'], array( 'wp-i18n' ), $loader_asset['version'], true );
	wp_script_add_data( 'vareoncalc-loader', 'type', 'module' );
	wp_set_script_translations( 'vareoncalc-loader', 'vareon-calculator-suite-lite', VAREONCALC_DIR . 'languages' );

	$calc_types = function_exists( 'vareoncalc_get_available_calculators' ) ? vareoncalc_get_available_calculators() : array();

	foreach ( $calc_types as $calc_type ) {
		$calc_type = sanitize_key( (string) $calc_type );
		$calc_type = preg_replace( '/[^a-z\\-]/', '', $calc_type );
		if ( empty( $calc_type ) ) {
			continue;
		}

		$calc_asset  = function_exists( 'vareoncalc_get_resolved_asset' )
			? vareoncalc_get_resolved_asset( 'assets/calculators/' . $calc_type . '.css' )
			: array(
				'url'     => VAREONCALC_URL . 'assets/calculators/' . $calc_type . '.css',
				'version' => VAREONCALC_VER,
			);
		$calc_handle = 'vareoncalc-calc-' . $calc_type;
		wp_register_style( $calc_handle, $calc_asset['url'], array( 'vareoncalc-style' ), $calc_asset['version'] );
	}
}
add_action( 'init', 'vareoncalc_register_assets' );


/**
 * Build theme CSS custom properties.
 *
 * @return string CSS output
 */
function vareoncalc_get_theme_css() {
	$opts = get_option( 'vareoncalc_lite_options', array() );

	$theme_preset = $opts['theme_preset'] ?? 'light';

	// Start from the light preset and override as needed below.
	$button_bg    = '#3b82f6';
	$button_text  = '#ffffff';
	$card_bg      = '#ffffff';
	$card_border  = '#e5e7eb';
	$accent       = '#3b82f6';
	$input_bg     = '#f9fafb';
	$input_border = '#d1d5db';
	$panel_bg     = '#f9fafb';
	$panel_border = '#e5e7eb';
	$panel_shadow = '0 1px 3px rgba(0, 0, 0, 0.05)';
	$muted_text   = '#6b7280';

	if ( 'dark' === $theme_preset ) {
		$card_bg      = '#1f2937';
		$card_border  = '#374151';
		$accent       = '#60a5fa';
		$input_bg     = '#1a2434';
		$input_border = '#4b5563';
		$panel_bg     = '#273449';
		$panel_border = '#3b4a5f';
		$panel_shadow = '0 12px 30px rgba(15, 23, 42, 0.45)';
		$muted_text   = '#d1d5db';
	} elseif ( 'modern' === $theme_preset ) {
		$button_bg    = '#1e293b';
		$card_bg      = '#ffffff';
		$card_border  = '#cbd5e1';
		$accent       = '#475569';
		$input_bg     = '#f8fafc';
		$input_border = '#94a3b8';
		$panel_bg     = '#f8fafc';
		$panel_border = '#cbd5e1';
		$panel_shadow = '0 8px 20px rgba(15, 23, 42, 0.08)';
		$muted_text   = '#64748b';
	}

	$text_font_family   = 'system';
	$text_font_weight   = '400';
	$button_font_family = 'system';
	$button_font_weight = '600';

	$button_hover = 'modern' === $theme_preset
		? '#334155'
		: vareoncalc_adjust_brightness( $button_bg, -10 );

	$card_text = vareoncalc_is_light( $card_bg ) ? '#111827' : '#f9fafb';

	$font_stacks = array(
		'system'     => '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
		'inter'      => 'Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'roboto'     => 'Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'opensans'   => '"Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'lato'       => 'Lato, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'montserrat' => 'Montserrat, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'poppins'    => 'Poppins, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'nunito'     => 'Nunito, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'raleway'    => 'Raleway, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
		'worksans'   => '"Work Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
	);

	$text_font_stack   = $font_stacks[ $text_font_family ] ?? $font_stacks['system'];
	$button_font_stack = $font_stacks[ $button_font_family ] ?? $font_stacks['system'];

	$css = "
.vareoncalc-root {
  --vareoncalc-button-bg: {$button_bg};
  --vareoncalc-button-text: {$button_text};
  --vareoncalc-button-hover: {$button_hover};
  --vareoncalc-card-bg: {$card_bg};
  --vareoncalc-card-border: {$card_border};
  --vareoncalc-card-text: {$card_text};
  --vareoncalc-accent: {$accent};
  --vareoncalc-input-bg: {$input_bg};
  --vareoncalc-input-border: {$input_border};
  --vareoncalc-panel-bg: {$panel_bg};
  --vareoncalc-panel-border: {$panel_border};
  --vareoncalc-panel-shadow: {$panel_shadow};
  --vareoncalc-muted-text: {$muted_text};
}

.vareoncalc-card {
  font-family: {$text_font_stack};
}

.vareoncalc-card label,
.vareoncalc-card p,
.vareoncalc-card span {
  font-weight: {$text_font_weight};
}

.vareoncalc-btn {
  font-family: {$button_font_stack};
  font-weight: {$button_font_weight};
}
";

	return $css;
}

/**
 * Adjust hex color brightness
 *
 * @param string $hex     Hex color code.
 * @param int    $percent Percent to adjust (-100 to 100).
 * @return string Adjusted hex color.
 */
function vareoncalc_adjust_brightness( $hex, $percent ) {
	$hex = str_replace( '#', '', $hex );
	$r   = hexdec( substr( $hex, 0, 2 ) );
	$g   = hexdec( substr( $hex, 2, 2 ) );
	$b   = hexdec( substr( $hex, 4, 2 ) );

	$r = max( 0, min( 255, $r + ( $r * $percent / 100 ) ) );
	$g = max( 0, min( 255, $g + ( $g * $percent / 100 ) ) );
	$b = max( 0, min( 255, $b + ( $b * $percent / 100 ) ) );

	return sprintf( '#%02x%02x%02x', $r, $g, $b );
}

/**
 * Check if hex color is light
 *
 * @param string $hex Hex color code.
 * @return bool True if light, false if dark.
 */
function vareoncalc_is_light( $hex ) {
	$hex = str_replace( '#', '', $hex );
	$r   = hexdec( substr( $hex, 0, 2 ) );
	$g   = hexdec( substr( $hex, 2, 2 ) );
	$b   = hexdec( substr( $hex, 4, 2 ) );

	$brightness = ( $r * 299 + $g * 587 + $b * 114 ) / 1000;
	return $brightness > 155;
}

/**
 * Get all JS translations for frontend calculators
 *
 * @return array Associative array of translated strings
 */
function vareoncalc_get_js_translations() {
	return array(
		// Common UI strings.
		'poweredBy'               => __( 'Powered by', 'vareon-calculator-suite-lite' ),
		'calculatorError'         => __( 'Vareon Calculator error', 'vareon-calculator-suite-lite' ),
		'calculate'               => __( 'Calculate', 'vareon-calculator-suite-lite' ),
		'reset'                   => __( 'Reset', 'vareon-calculator-suite-lite' ),
		'loading'                 => __( 'Loading...', 'vareon-calculator-suite-lite' ),

		// Common validation messages.
		'fieldRequired'           => __( 'This field is required.', 'vareon-calculator-suite-lite' ),
		'invalidNumber'           => __( 'Please enter a valid number.', 'vareon-calculator-suite-lite' ),
		'valueTooLow'             => __( 'Value is too low.', 'vareon-calculator-suite-lite' ),
		'valueTooHigh'            => __( 'Value is too high.', 'vareon-calculator-suite-lite' ),
		'cannotBeNegative'        => __( 'Value cannot be negative.', 'vareon-calculator-suite-lite' ),

		// Loan calculator.
		'loanAmount'              => __( 'Loan Amount', 'vareon-calculator-suite-lite' ),
		'apr'                     => __( 'APR', 'vareon-calculator-suite-lite' ),
		'aprHelp'                 => __( 'Annual Percentage Rate — the yearly interest rate charged by your lender, including fees.', 'vareon-calculator-suite-lite' ),
		'term'                    => __( 'Term', 'vareon-calculator-suite-lite' ),
		'aprRequired'             => __( 'APR is required.', 'vareon-calculator-suite-lite' ),
		'aprCannotBeNegative'     => __( 'APR cannot be negative.', 'vareon-calculator-suite-lite' ),
		'aprMustBeLessThan100'    => __( 'APR must be less than 100%.', 'vareon-calculator-suite-lite' ),
		'monthlyPayment'          => __( 'Monthly Payment', 'vareon-calculator-suite-lite' ),
		'totalInterest'           => __( 'Total Interest', 'vareon-calculator-suite-lite' ),
		'totalAmountPaid'         => __( 'Total Amount Paid', 'vareon-calculator-suite-lite' ),
		'termTooLarge'            => __( 'Term is too large to calculate accurately.', 'vareon-calculator-suite-lite' ),

		// BMI calculator.
		'height'                  => __( 'Height', 'vareon-calculator-suite-lite' ),
		'heightCm'                => __( 'Height (cm)', 'vareon-calculator-suite-lite' ),
		'weight'                  => __( 'Weight', 'vareon-calculator-suite-lite' ),
		'weightKg'                => __( 'Weight (kg)', 'vareon-calculator-suite-lite' ),
		'weightLbs'               => __( 'Weight (lbs)', 'vareon-calculator-suite-lite' ),
		'bmi'                     => __( 'BMI', 'vareon-calculator-suite-lite' ),
		'category'                => __( 'Category', 'vareon-calculator-suite-lite' ),
		'underweight'             => __( 'Underweight', 'vareon-calculator-suite-lite' ),
		'normalWeight'            => __( 'Normal weight', 'vareon-calculator-suite-lite' ),
		'overweight'              => __( 'Overweight', 'vareon-calculator-suite-lite' ),
		'obese'                   => __( 'Obese', 'vareon-calculator-suite-lite' ),
		'pleaseEnterHeight'       => __( 'Please enter a height.', 'vareon-calculator-suite-lite' ),
		'feetMustBeBetween'       => __( 'Feet must be between 0 and 8.', 'vareon-calculator-suite-lite' ),
		'inchesMustBeBetween'     => __( 'Inches must be between 0 and 11.9.', 'vareon-calculator-suite-lite' ),
		'heightOutOfRange'        => __( 'Height seems out of range. Please check your input.', 'vareon-calculator-suite-lite' ),
		'unableToCalculateBmi'    => __( 'Unable to calculate BMI.', 'vareon-calculator-suite-lite' ),
		'inchesCannotBeNegative'  => __( 'Inches cannot be negative.', 'vareon-calculator-suite-lite' ),

		// BMI tips.
		'tipUnderweight'          => __( 'Consider consulting a healthcare provider about healthy weight gain strategies.', 'vareon-calculator-suite-lite' ),
		'tipNormal'               => __( 'Great! Maintain your healthy weight through balanced nutrition and regular exercise.', 'vareon-calculator-suite-lite' ),
		'tipOverweight'           => __( 'Consider incorporating more physical activity and reviewing your diet with a healthcare professional.', 'vareon-calculator-suite-lite' ),
		'tipObese'                => __( 'Consult with a healthcare provider about creating a safe and effective weight management plan.', 'vareon-calculator-suite-lite' ),

		// Mortgage calculator.
		'homePrice'               => __( 'Home Price', 'vareon-calculator-suite-lite' ),
		'downPayment'             => __( 'Down Payment', 'vareon-calculator-suite-lite' ),
		'interestRate'            => __( 'Interest Rate', 'vareon-calculator-suite-lite' ),
		'loanTerm'                => __( 'Loan Term', 'vareon-calculator-suite-lite' ),
		'estimatedMonthlyPayment' => __( 'Estimated Monthly Payment', 'vareon-calculator-suite-lite' ),
		'loanPrincipal'           => __( 'Loan Principal', 'vareon-calculator-suite-lite' ),

		// Tip calculator.
		'billAmount'              => __( 'Bill Amount', 'vareon-calculator-suite-lite' ),
		'tipPercent'              => __( 'Tip %', 'vareon-calculator-suite-lite' ),
		'splitBetween'            => __( 'Split Between', 'vareon-calculator-suite-lite' ),
		'people'                  => __( 'people', 'vareon-calculator-suite-lite' ),
		'tipAmount'               => __( 'Tip Amount', 'vareon-calculator-suite-lite' ),
		'totalWithTip'            => __( 'Total (with tip)', 'vareon-calculator-suite-lite' ),
		'perPerson'               => __( 'Per Person', 'vareon-calculator-suite-lite' ),

		// Percentage calculator.
		'whatIs'                  => __( 'What is', 'vareon-calculator-suite-lite' ),
		'of'                      => __( 'of', 'vareon-calculator-suite-lite' ),
		'result'                  => __( 'Result', 'vareon-calculator-suite-lite' ),
		'isWhatPercentOf'         => __( 'is what % of', 'vareon-calculator-suite-lite' ),
		'percentOf'               => __( '% of', 'vareon-calculator-suite-lite' ),
		'is'                      => __( 'is', 'vareon-calculator-suite-lite' ),

		// Discount calculator.
		'originalPrice'           => __( 'Original Price', 'vareon-calculator-suite-lite' ),
		'discount'                => __( 'Discount', 'vareon-calculator-suite-lite' ),
		'discountAmount'          => __( 'Discount Amount', 'vareon-calculator-suite-lite' ),
		'finalPrice'              => __( 'Final Price', 'vareon-calculator-suite-lite' ),
		'youSave'                 => __( 'You save', 'vareon-calculator-suite-lite' ),

		// Savings calculator.
		'initialDeposit'          => __( 'Initial Deposit', 'vareon-calculator-suite-lite' ),
		'monthlyContribution'     => __( 'Monthly Contribution', 'vareon-calculator-suite-lite' ),
		'annualInterestRate'      => __( 'Annual Interest Rate', 'vareon-calculator-suite-lite' ),
		'years'                   => __( 'Years', 'vareon-calculator-suite-lite' ),
		'futureValue'             => __( 'Future Value', 'vareon-calculator-suite-lite' ),
		'totalContributions'      => __( 'Total Contributions', 'vareon-calculator-suite-lite' ),
		'interestEarned'          => __( 'Interest Earned', 'vareon-calculator-suite-lite' ),

		// ROI calculator.
		'initialInvestment'       => __( 'Initial Investment', 'vareon-calculator-suite-lite' ),
		'finalValue'              => __( 'Final Value', 'vareon-calculator-suite-lite' ),
		'roi'                     => __( 'ROI', 'vareon-calculator-suite-lite' ),
		'netProfit'               => __( 'Net Profit', 'vareon-calculator-suite-lite' ),

		// Age calculator.
		'birthDate'               => __( 'Birth Date', 'vareon-calculator-suite-lite' ),
		'calculateAgeTo'          => __( 'Calculate Age To', 'vareon-calculator-suite-lite' ),
		'today'                   => __( 'Today', 'vareon-calculator-suite-lite' ),
		'age'                     => __( 'Age', 'vareon-calculator-suite-lite' ),
		'nextBirthday'            => __( 'Next Birthday', 'vareon-calculator-suite-lite' ),
		'daysUntilBirthday'       => __( 'days until birthday', 'vareon-calculator-suite-lite' ),
		'totalDaysLived'          => __( 'Total Days Lived', 'vareon-calculator-suite-lite' ),
		'days'                    => __( 'days', 'vareon-calculator-suite-lite' ),
		'yearsOld'                => __( 'years old', 'vareon-calculator-suite-lite' ),
		'months'                  => __( 'months', 'vareon-calculator-suite-lite' ),

		// Fuel cost calculator.
		'distance'                => __( 'Distance', 'vareon-calculator-suite-lite' ),
		'fuelEfficiency'          => __( 'Fuel Efficiency', 'vareon-calculator-suite-lite' ),
		'fuelPrice'               => __( 'Fuel Price', 'vareon-calculator-suite-lite' ),
		'estimatedFuelCost'       => __( 'Estimated Fuel Cost', 'vareon-calculator-suite-lite' ),
		'fuelNeeded'              => __( 'Fuel Needed', 'vareon-calculator-suite-lite' ),

		// GPA calculator.
		'course'                  => __( 'Course', 'vareon-calculator-suite-lite' ),
		'grade'                   => __( 'Grade', 'vareon-calculator-suite-lite' ),
		'credits'                 => __( 'Credits', 'vareon-calculator-suite-lite' ),
		'addCourse'               => __( 'Add Course', 'vareon-calculator-suite-lite' ),
		'removeCourse'            => __( 'Remove', 'vareon-calculator-suite-lite' ),
		'gpa'                     => __( 'GPA', 'vareon-calculator-suite-lite' ),
		'totalCredits'            => __( 'Total Credits', 'vareon-calculator-suite-lite' ),

		// Grade calculator.
		'currentGrade'            => __( 'Current Grade', 'vareon-calculator-suite-lite' ),
		'desiredGrade'            => __( 'Desired Grade', 'vareon-calculator-suite-lite' ),
		'finalWeight'             => __( 'Final Weight', 'vareon-calculator-suite-lite' ),
		'neededOnFinal'           => __( 'Needed on Final', 'vareon-calculator-suite-lite' ),

		// Unit converter.
		'from'                    => __( 'From', 'vareon-calculator-suite-lite' ),
		'to'                      => __( 'To', 'vareon-calculator-suite-lite' ),
		'value'                   => __( 'Value', 'vareon-calculator-suite-lite' ),
		'convertedValue'          => __( 'Converted Value', 'vareon-calculator-suite-lite' ),
		'selectCategory'          => __( 'Select Category', 'vareon-calculator-suite-lite' ),
		'length'                  => __( 'Length', 'vareon-calculator-suite-lite' ),
		'mass'                    => __( 'Mass', 'vareon-calculator-suite-lite' ),
		'temperature'             => __( 'Temperature', 'vareon-calculator-suite-lite' ),
		'volume'                  => __( 'Volume', 'vareon-calculator-suite-lite' ),

		// Credit card payoff.
		'balance'                 => __( 'Balance', 'vareon-calculator-suite-lite' ),
		'monthlyPaymentAmount'    => __( 'Monthly Payment', 'vareon-calculator-suite-lite' ),
		'timeToPayoff'            => __( 'Time to Payoff', 'vareon-calculator-suite-lite' ),
		'totalInterestPaid'       => __( 'Total Interest Paid', 'vareon-calculator-suite-lite' ),

		// Measurement toggle.
		'metric'                  => __( 'Metric', 'vareon-calculator-suite-lite' ),
		'imperial'                => __( 'Imperial', 'vareon-calculator-suite-lite' ),

		// Common units.
		'kg'                      => __( 'kg', 'vareon-calculator-suite-lite' ),
		'lbs'                     => __( 'lbs', 'vareon-calculator-suite-lite' ),
		'cm'                      => __( 'cm', 'vareon-calculator-suite-lite' ),
		'ft'                      => __( 'ft', 'vareon-calculator-suite-lite' ),
		'in'                      => __( 'in', 'vareon-calculator-suite-lite' ),
		'yrs'                     => __( 'yrs', 'vareon-calculator-suite-lite' ),

		// Placeholders.
		'egNumber'                => __( 'e.g.', 'vareon-calculator-suite-lite' ),
	);
}

/**
 * Localize shared loader config.
 */
function vareoncalc_enqueue_loader_config() {
	$branding_default = vareoncalc_get_branding_enabled_default() ? 1 : 0;
	$dev_nonce        = function_exists( 'vareoncalc_get_dev_nonce' ) ? vareoncalc_get_dev_nonce() : '';

	wp_localize_script(
		'vareoncalc-loader',
		'VAREONCALC_CFG',
		array(
			'branding'          => (bool) vareoncalc_get_option( 'branding', $branding_default ),
			'proEnabled'        => vareoncalc_is_pro(),
			'version'           => VAREONCALC_VER,
			'assetVersion'      => function_exists( 'vareoncalc_get_asset_version' ) ? vareoncalc_get_asset_version() : VAREONCALC_VER,
			'useMinifiedAssets' => function_exists( 'vareoncalc_should_use_minified_assets' ) ? vareoncalc_should_use_minified_assets() : ! ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ),
			'edition'           => vareoncalc_get_version(),
			'layout'            => vareoncalc_get_option( 'calculator_layout', 'compact' ),
			'pluginUrl'         => VAREONCALC_URL,
			'devNonce'          => $dev_nonce,
			'customThemes'      => array(),
			'formatting'        => array(
				'currencyCode'      => vareoncalc_get_option( 'currency_code', 'USD' ),
				'currencySymbol'    => vareoncalc_get_option( 'currency_symbol', '$' ),
				'currencyPosition'  => vareoncalc_get_option( 'currency_position', 'before' ),
				'currencySpacing'   => vareoncalc_get_option( 'currency_spacing', 'none' ),
				'currencyDecimals'  => (int) vareoncalc_get_option( 'currency_decimals', 2 ),
				'numberDecimals'    => (int) vareoncalc_get_option( 'number_decimals', 2 ),
				'percentDecimals'   => (int) vareoncalc_get_option( 'percent_decimals', 1 ),
				'thousandSeparator' => vareoncalc_get_option( 'thousand_separator', 'comma' ),
				'decimalSeparator'  => vareoncalc_get_option( 'decimal_separator', 'dot' ),
			),
			'measurement'       => array(
				'system' => vareoncalc_get_option( 'measurement_system', 'mixed' ),
			),
			'accessibility'     => array(),
			'i18n'              => vareoncalc_get_js_translations(),
		)
	);
}

/**
 * Enqueue frontend calculator assets (on-demand).
 *
 * This function should be called from shortcode/block render callbacks
 * so assets are only loaded when a calculator is actually present on the page.
 *
 * @param string|null $type Calculator type to enqueue styles for.
 * @return void
 */
function vareoncalc_enqueue_frontend_assets( $type = null ) {
	static $base_enqueued  = false;
	static $enqueued_calcs = array();

	if ( ! $base_enqueued ) {
		$base_enqueued = true;

		wp_enqueue_style( 'vareoncalc-style' );

		$theme_css = vareoncalc_get_theme_css();
		if ( ! empty( $theme_css ) ) {
			wp_add_inline_style( 'vareoncalc-style', wp_strip_all_tags( $theme_css ) );
		}

		wp_enqueue_script( 'vareoncalc-loader' );
		if ( function_exists( 'vareoncalc_enqueue_importmap_bridge' ) ) {
			vareoncalc_enqueue_importmap_bridge();
		}
		vareoncalc_enqueue_loader_config();
	}

	if ( empty( $type ) ) {
		return;
	}

	$type = sanitize_key( (string) $type );
	$type = preg_replace( '/[^a-z\\-]/', '', $type );

	if ( empty( $type ) || ( function_exists( 'vareoncalc_is_calculator_available' ) && ! vareoncalc_is_calculator_available( $type ) ) ) {
		return;
	}

	$calc_handle = 'vareoncalc-calc-' . $type;
	if ( empty( $enqueued_calcs[ $calc_handle ] ) && wp_style_is( $calc_handle, 'registered' ) ) {
		wp_enqueue_style( $calc_handle );
		$enqueued_calcs[ $calc_handle ] = true;
	}
}

add_action(
	'enqueue_block_editor_assets',
	function () {
		wp_enqueue_script( 'vareoncalc-loader' );
		if ( function_exists( 'vareoncalc_enqueue_importmap_bridge' ) ) {
			vareoncalc_enqueue_importmap_bridge();
		}
		vareoncalc_enqueue_loader_config();
	}
);

add_action( 'wp_footer', 'vareoncalc_print_importmap', 1 );
add_action( 'admin_footer', 'vareoncalc_print_importmap', 1 );

add_action(
	'enqueue_block_editor_assets',
	function () {
		$theme_css = vareoncalc_get_theme_css();
		if ( ! empty( $theme_css ) ) {
			$editor_style_handle = 'vareoncalc-block-editor-style';
			if ( wp_style_is( $editor_style_handle, 'registered' ) || wp_style_is( $editor_style_handle, 'enqueued' ) ) {
				wp_add_inline_style( $editor_style_handle, wp_strip_all_tags( $theme_css ) );
			}
		}
	},
	20
);

/**
 * Seed default options on activation.
 */
function vareoncalc_lite_activate() {
	if ( ! get_option( 'vareoncalc_lite_options' ) ) {
		update_option( 'vareoncalc_lite_options', vareoncalc_default_options() );
	}

	if ( function_exists( 'vareoncalc_set_activation_redirect' ) ) {
		vareoncalc_set_activation_redirect();
	}
}
register_activation_hook( __FILE__, 'vareoncalc_lite_activate' );
