<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<section class="panel">
	<div class="actions" style="justify-content:flex-start; margin-top:0; margin-bottom:18px;">
		<a class="btn btn-outline" href="<?php echo site_url('personalizar'); ?>">Regresar</a>
	</div>
	<div style="display:grid; gap:14px;">
		<?php
		$prefs = isset($user_preferences) && is_array($user_preferences) ? $user_preferences : array();
		$sections = array(
			array(
				'key' => 'nombre-producto',
				'icon' => 'ion-pricetag',
				'label' => 'Nombre de Producto',
				'route' => 'personalizar/visor/nombre-producto',
				'fields' => array(
					array('name' => 'visor_product_name_size', 'label' => 'Tamano', 'type' => 'number'),
					array('name' => 'visor_product_name_color', 'label' => 'Color', 'type' => 'color'),
				),
			),
			array(
				'key' => 'precio-divisa',
				'icon' => 'ion-social-usd',
				'label' => 'Precio de Divisa',
				'route' => 'personalizar/visor/precio-divisa',
				'fields' => array(
					array('name' => 'visor_price_divisa_size', 'label' => 'Tamano', 'type' => 'number'),
					array('name' => 'visor_price_divisa_color', 'label' => 'Color', 'type' => 'color'),
				),
			),
			array(
				'key' => 'precio-bolivares',
				'icon' => 'ion-cash',
				'label' => 'Precio Bolivares',
				'route' => 'personalizar/visor/precio-bolivares',
				'fields' => array(
					array('name' => 'visor_price_bs_size', 'label' => 'Tamano', 'type' => 'number'),
					array('name' => 'visor_price_bs_color', 'label' => 'Color', 'type' => 'color'),
				),
			),
			array(
				'key' => 'texto',
				'icon' => 'ion-edit',
				'label' => 'Texto',
				'route' => 'personalizar/visor/texto',
				'fields' => array(
					array('name' => 'visor_text_size', 'label' => 'Tamano', 'type' => 'number'),
					array('name' => 'visor_text_color', 'label' => 'Color', 'type' => 'color'),
				),
			),
			array(
				'key' => 'boton',
				'icon' => 'ion-android-radio-button-on',
				'label' => 'Boton',
				'route' => 'personalizar/visor/boton',
				'fields' => array(
					array('name' => 'visor_button_size', 'label' => 'Tamano', 'type' => 'number'),
					array('name' => 'visor_button_color', 'label' => 'Color', 'type' => 'color'),
				),
			),
			array(
				'key' => 'fondo',
				'icon' => 'ion-android-color-palette',
				'label' => 'Fondo',
				'route' => 'personalizar/visor/fondo',
				'fields' => array(
					array('name' => 'visor_background_color', 'label' => 'Fondo', 'type' => 'color'),
					array('name' => 'visor_box_color', 'label' => 'Cajas', 'type' => 'color'),
				),
			),
		);
		$open_section = isset($_GET['open']) ? (string)$_GET['open'] : $sections[0]['key'];
		foreach ($sections as $index => $section) {
			$section_id = 'visor-pref-section-'.$section['key'];
			$is_open = $section['key'] === $open_section;
		?>
			<div style="border-radius:18px; overflow:hidden; box-shadow: var(--shadow);">
				<button
					type="button"
					class="menu-btn visor-pref-toggle"
					data-target="<?php echo htmlspecialchars($section_id, ENT_QUOTES, 'UTF-8'); ?>"
					data-open-key="<?php echo htmlspecialchars($section['key'], ENT_QUOTES, 'UTF-8'); ?>"
					style="border:0;"
				>
					<span class="menu-icon"><i class="<?php echo htmlspecialchars($section['icon'], ENT_QUOTES, 'UTF-8'); ?>"></i></span>
					<span class="menu-label"><?php echo htmlspecialchars($section['label'], ENT_QUOTES, 'UTF-8'); ?></span>
					<span class="menu-icon" style="text-align:right;"><?php echo $is_open ? '-' : '+'; ?></span>
				</button>
				<div id="<?php echo htmlspecialchars($section_id, ENT_QUOTES, 'UTF-8'); ?>" style="display:<?php echo $is_open ? 'grid' : 'none'; ?>; gap:12px; padding:12px; background:var(--panel);">
					<form method="post" action="<?php echo site_url($section['route']); ?>" autocomplete="off" class="pref-live-form" data-preview-scope="visor" data-section-key="<?php echo htmlspecialchars($section['key'], ENT_QUOTES, 'UTF-8'); ?>" style="display:grid; gap:12px;">
						<input type="hidden" name="return_to" value="personalizar/visor" />
						<input type="hidden" name="open_section" value="<?php echo htmlspecialchars($section['key'], ENT_QUOTES, 'UTF-8'); ?>" />
						<?php foreach ($section['fields'] as $field) { ?>
							<div class="field" style="margin-top:0;">
								<label for="<?php echo htmlspecialchars($field['name'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($field['label'], ENT_QUOTES, 'UTF-8'); ?></label>
								<?php if ($field['type'] === 'color') { ?>
									<div style="display:flex; gap:12px; align-items:center;">
										<input
											id="<?php echo htmlspecialchars($field['name'], ENT_QUOTES, 'UTF-8'); ?>"
											type="color"
											class="pref-live-input"
											name="<?php echo htmlspecialchars($field['name'], ENT_QUOTES, 'UTF-8'); ?>"
											value="<?php echo htmlspecialchars(isset($prefs[$field['name']]) ? $prefs[$field['name']] : '#000000', ENT_QUOTES, 'UTF-8'); ?>"
											style="width:72px; min-width:72px; padding:6px; height:52px;"
										/>
										<input class="pref-color-text" type="text" value="<?php echo htmlspecialchars(isset($prefs[$field['name']]) ? $prefs[$field['name']] : '#000000', ENT_QUOTES, 'UTF-8'); ?>" readonly />
									</div>
								<?php } else { ?>
									<input
										id="<?php echo htmlspecialchars($field['name'], ENT_QUOTES, 'UTF-8'); ?>"
										type="number"
										class="pref-live-input"
										step="0.10"
										min="0.5"
										max="10"
										name="<?php echo htmlspecialchars($field['name'], ENT_QUOTES, 'UTF-8'); ?>"
										value="<?php echo htmlspecialchars(number_format(isset($prefs[$field['name']]) ? (float)$prefs[$field['name']] : 1, 2, '.', ''), ENT_QUOTES, 'UTF-8'); ?>"
									/>
								<?php } ?>
							</div>
						<?php } ?>
						<div class="pref-preview-card" style="padding:14px; border-radius:16px; background:var(--visor-surface); box-shadow: inset 0 0 0 1px rgba(20,41,64,0.08);">
							<div class="pref-preview-title" style="font-size:0.8rem; font-weight:700; text-transform:uppercase; letter-spacing:0.04em; color:#617386; margin-bottom:8px;">Vista previa</div>
							<div class="pref-preview-sample" style="display:grid; gap:10px;">
								<?php if ($section['key'] === 'nombre-producto') { ?>
									<div class="preview-product-name" style="font-size:calc(1rem * <?php echo number_format(isset($prefs['visor_product_name_size']) ? (float)$prefs['visor_product_name_size'] : 1.05, 2, '.', ''); ?>); color:<?php echo htmlspecialchars(isset($prefs['visor_product_name_color']) ? $prefs['visor_product_name_color'] : '#183247', ENT_QUOTES, 'UTF-8'); ?>; font-weight:700;">MEDIA CABALLERO DE VESTIR 1</div>
								<?php } elseif ($section['key'] === 'precio-divisa') { ?>
									<div class="preview-price-divisa" style="font-size:calc(1rem * <?php echo number_format(isset($prefs['visor_price_divisa_size']) ? (float)$prefs['visor_price_divisa_size'] : 4.10, 2, '.', ''); ?>); color:<?php echo htmlspecialchars(isset($prefs['visor_price_divisa_color']) ? $prefs['visor_price_divisa_color'] : '#4d74c3', ENT_QUOTES, 'UTF-8'); ?>; font-weight:700; line-height:1;">5,88</div>
								<?php } elseif ($section['key'] === 'precio-bolivares') { ?>
									<div class="preview-price-bs" style="font-size:calc(1rem * <?php echo number_format(isset($prefs['visor_price_bs_size']) ? (float)$prefs['visor_price_bs_size'] : 1.45, 2, '.', ''); ?>); color:<?php echo htmlspecialchars(isset($prefs['visor_price_bs_color']) ? $prefs['visor_price_bs_color'] : '#617386', ENT_QUOTES, 'UTF-8'); ?>;">BCV: 2.073,93 Bs</div>
								<?php } elseif ($section['key'] === 'texto') { ?>
									<div class="preview-text" style="font-size:calc(1rem * <?php echo number_format(isset($prefs['visor_text_size']) ? (float)$prefs['visor_text_size'] : 1.00, 2, '.', ''); ?>); color:<?php echo htmlspecialchars(isset($prefs['visor_text_color']) ? $prefs['visor_text_color'] : '#617386', ENT_QUOTES, 'UTF-8'); ?>;">Historico (sesion actual)</div>
								<?php } elseif ($section['key'] === 'boton') { ?>
									<div class="preview-button" style="display:inline-flex; align-items:center; justify-content:center; width:max-content; min-width:120px; padding:12px 18px; border-radius:14px; background:<?php echo htmlspecialchars(isset($prefs['visor_button_color']) ? $prefs['visor_button_color'] : '#f47d2b', ENT_QUOTES, 'UTF-8'); ?>; color:#ffffff; font-size:calc(1rem * <?php echo number_format(isset($prefs['visor_button_size']) ? (float)$prefs['visor_button_size'] : 1.00, 2, '.', ''); ?>); font-weight:700;">Consultar</div>
								<?php } else { ?>
									<div class="preview-surface" style="display:grid; gap:10px; padding:12px; border-radius:14px; background:<?php echo htmlspecialchars(isset($prefs['visor_background_color']) ? $prefs['visor_background_color'] : '#f6f7f9', ENT_QUOTES, 'UTF-8'); ?>;">
										<div class="preview-box" style="padding:12px; border-radius:12px; background:<?php echo htmlspecialchars(isset($prefs['visor_box_color']) ? $prefs['visor_box_color'] : '#eef3f8', ENT_QUOTES, 'UTF-8'); ?>; color:#617386;">Caja del visor</div>
									</div>
								<?php } ?>
							</div>
						</div>
						<div class="actions" style="justify-content:space-between; margin-top:4px;">
							<button class="btn btn-outline" type="submit" name="reset_preferences" value="1">Restablecer</button>
							<button class="btn" type="submit">Guardar</button>
						</div>
					</form>
				</div>
			</div>
		<?php } ?>
	</div>
</section>
<script>
document.addEventListener('DOMContentLoaded', function () {
	var getContrastColor = function (hex) {
		hex = (hex || '').replace('#', '');
		if (hex.length === 3) {
			hex = hex.split('').map(function (char) { return char + char; }).join('');
		}
		if (!/^[0-9a-fA-F]{6}$/.test(hex)) {
			return '#ffffff';
		}
		var r = parseInt(hex.slice(0, 2), 16);
		var g = parseInt(hex.slice(2, 4), 16);
		var b = parseInt(hex.slice(4, 6), 16);
		var luminance = ((r * 299) + (g * 587) + (b * 114)) / 1000;
		return luminance >= 160 ? '#183247' : '#ffffff';
	};

	var syncColorText = function (form) {
		form.querySelectorAll('input[type="color"]').forEach(function (colorInput) {
			var textInput = colorInput.parentElement ? colorInput.parentElement.querySelector('.pref-color-text') : null;
			if (textInput) {
				textInput.value = colorInput.value;
			}
		});
	};

	var updateVisorPreview = function (form) {
		syncColorText(form);
		var sectionKey = form.getAttribute('data-section-key');
		if (sectionKey === 'nombre-producto') {
			var sample = form.querySelector('.preview-product-name');
			if (sample) {
				sample.style.fontSize = 'calc(1rem * ' + (form.querySelector('[name="visor_product_name_size"]').value || '1') + ')';
				sample.style.color = form.querySelector('[name="visor_product_name_color"]').value || '#183247';
			}
		} else if (sectionKey === 'precio-divisa') {
			var sampleDivisa = form.querySelector('.preview-price-divisa');
			if (sampleDivisa) {
				sampleDivisa.style.fontSize = 'calc(1rem * ' + (form.querySelector('[name="visor_price_divisa_size"]').value || '1') + ')';
				sampleDivisa.style.color = form.querySelector('[name="visor_price_divisa_color"]').value || '#4d74c3';
			}
		} else if (sectionKey === 'precio-bolivares') {
			var sampleBs = form.querySelector('.preview-price-bs');
			if (sampleBs) {
				sampleBs.style.fontSize = 'calc(1rem * ' + (form.querySelector('[name="visor_price_bs_size"]').value || '1') + ')';
				sampleBs.style.color = form.querySelector('[name="visor_price_bs_color"]').value || '#617386';
			}
		} else if (sectionKey === 'texto') {
			var sampleText = form.querySelector('.preview-text');
			if (sampleText) {
				sampleText.style.fontSize = 'calc(1rem * ' + (form.querySelector('[name="visor_text_size"]').value || '1') + ')';
				sampleText.style.color = form.querySelector('[name="visor_text_color"]').value || '#617386';
			}
		} else if (sectionKey === 'boton') {
			var sampleButton = form.querySelector('.preview-button');
			if (sampleButton) {
				var bg = form.querySelector('[name="visor_button_color"]').value || '#f47d2b';
				sampleButton.style.fontSize = 'calc(1rem * ' + (form.querySelector('[name="visor_button_size"]').value || '1') + ')';
				sampleButton.style.background = bg;
				sampleButton.style.color = getContrastColor(bg);
			}
		} else if (sectionKey === 'fondo') {
			var surface = form.querySelector('.preview-surface');
			var box = form.querySelector('.preview-box');
			if (surface) {
				surface.style.background = form.querySelector('[name="visor_background_color"]').value || '#f6f7f9';
			}
			if (box) {
				box.style.background = form.querySelector('[name="visor_box_color"]').value || '#eef3f8';
				box.style.color = getContrastColor(form.querySelector('[name="visor_box_color"]').value || '#eef3f8');
			}
		}
	};

	var toggles = document.querySelectorAll('.visor-pref-toggle');
	var closeOthers = function (currentToggle) {
		toggles.forEach(function (toggle) {
			if (toggle === currentToggle) {
				return;
			}
			var targetId = toggle.getAttribute('data-target');
			var body = document.getElementById(targetId);
			if (!body) {
				return;
			}
			body.style.display = 'none';
			var indicators = toggle.querySelectorAll('.menu-icon');
			var lastIndicator = indicators.length ? indicators[indicators.length - 1] : null;
			if (lastIndicator) {
				lastIndicator.textContent = '+';
			}
		});
	};

	toggles.forEach(function (toggle) {
		toggle.addEventListener('click', function () {
			var targetId = toggle.getAttribute('data-target');
			var body = document.getElementById(targetId);
			if (!body) {
				return;
			}

			var isOpen = body.style.display !== 'none';
			if (!isOpen) {
				closeOthers(toggle);
			}
			body.style.display = isOpen ? 'none' : 'grid';
			var indicators = toggle.querySelectorAll('.menu-icon');
			var lastIndicator = indicators.length ? indicators[indicators.length - 1] : null;
			if (lastIndicator) {
				lastIndicator.textContent = isOpen ? '+' : '-';
			}
		});
	});

	document.querySelectorAll('.pref-live-form[data-preview-scope="visor"]').forEach(function (form) {
		form.querySelectorAll('.pref-live-input').forEach(function (input) {
			input.addEventListener('input', function () {
				updateVisorPreview(form);
			});
			input.addEventListener('change', function () {
				updateVisorPreview(form);
			});
		});
		updateVisorPreview(form);
	});
});
</script>
