<?php
$roulette = new \Plugin\NexoraRoulette\NexoraRoulette();

if(isset($_POST['save_appearance'])) {
    try {
        $roulette->saveAppearance($_POST);
        message('success', 'Personalización de Ruleta Nexora guardada para '.$roulette->getRealmLabel().'.');
    } catch(Throwable $e) {
        message('error', $e->getMessage());
    }
}

$appearance = $roulette->appearanceSettings();
$presets = \Plugin\NexoraRoulette\NexoraRoulette::appearancePresets();
$prizes = $roulette->getPrizes(true);
$activeCount = count($prizes);
$segmentAngle = $activeCount > 0 ? (360 / $activeCount) : 0;
?>
<style>
.nxr-admin-appearance .panel-heading strong{font-size:14px}.nxr-admin-appearance .form-section-title{margin:0 0 14px;font-size:15px;font-weight:700}.nxr-admin-appearance .help-block{font-size:12px}.nxr-color-row{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}.nxr-color-field{padding:10px;border:1px solid #ddd;border-radius:6px;background:#fafafa}.nxr-color-field label{display:block;font-size:11px;margin-bottom:6px}.nxr-color-field input[type=color]{width:100%;height:38px;border:0;padding:0;background:transparent}.nxr-appearance-preview{position:sticky;top:20px;background:#080b11;border-radius:18px;padding:18px;color:#f3f5f8;overflow:hidden;box-shadow:0 16px 50px rgba(0,0,0,.25)}.nxr-preview-head{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}.nxr-preview-head span{font-size:9px;letter-spacing:.14em;color:#f0d18b;font-weight:700}.nxr-preview-head h3{font-size:20px;color:#fff;margin:4px 0}.nxr-preview-wallet{text-align:right}.nxr-preview-wallet b{display:block;color:#f0d18b;font-size:18px}.nxr-preview-wheel-wrap{width:min(340px,100%);aspect-ratio:1;margin:18px auto;position:relative;display:grid;place-items:center}.nxr-preview-wheel{position:absolute;inset:0;border-radius:50%;border:8px solid #202936;box-shadow:0 0 0 2px rgba(215,169,74,.5),0 14px 38px rgba(0,0,0,.45);background:conic-gradient(#18212d 0 45deg,#111822 45deg 90deg,#18212d 90deg 135deg,#111822 135deg 180deg,#18212d 180deg 225deg,#111822 225deg 270deg,#18212d 270deg 315deg,#111822 315deg 360deg)}.nxr-preview-wheel:after{content:"";position:absolute;inset:1px;border-radius:50%;background:repeating-conic-gradient(from 0deg,transparent 0 44deg,rgba(255,255,255,.18) 44deg 45deg);pointer-events:none}.nxr-preview-pointer{position:absolute;top:-4px;left:50%;z-index:4;transform:translateX(-50%);width:0;height:0;border-left:15px solid transparent;border-right:15px solid transparent;border-top:30px solid #f0d18b}.nxr-preview-core{position:relative;z-index:3;width:112px;height:112px;border-radius:50%;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;background:radial-gradient(circle at 30% 25%,#334052,#101722 70%);border:2px solid #d7a94a;box-shadow:0 0 0 6px rgba(0,0,0,.28)}.nxr-preview-core b{font-size:24px;letter-spacing:.12em;color:#f0d18b}.nxr-preview-core small{font-size:8px;letter-spacing:.08em}.nxr-preview-button{width:80%;margin:0 auto;padding:12px 16px;border-radius:12px;text-align:center;background:linear-gradient(180deg,#f0ca75,#c98f2d 55%,#8d5817);color:#17120b;font-weight:800}.nxr-preview-meta{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:14px}.nxr-preview-meta div{padding:9px;border-radius:10px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.06)}.nxr-preview-meta span{display:block;color:#9ba6b5;font-size:9px}.nxr-preview-meta b{font-size:12px}.nxr-symmetric-note{border:1px solid rgba(46,153,93,.25);background:rgba(46,153,93,.08);padding:12px;border-radius:8px;color:#2e7d50}.nxr-range-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.nxr-check-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 18px}.nxr-check-grid label{font-weight:400}@media(max-width:1100px){.nxr-color-row{grid-template-columns:repeat(2,1fr)}.nxr-appearance-preview{position:relative;top:auto}}@media(max-width:650px){.nxr-color-row,.nxr-range-grid,.nxr-check-grid{grid-template-columns:1fr}}
</style>

<div class="nxr-admin-appearance">
<h1 class="page-header">Personalización de Ruleta <small><?php echo htmlspecialchars($roulette->getRealmLabel(),ENT_QUOTES,'UTF-8'); ?></small></h1>

<div class="alert alert-info">
    <strong>Separación visual/económica:</strong> desde V1.2.0 todos los segmentos de la rueda se muestran con el mismo tamaño. El <strong>peso</strong> de cada premio continúa determinando la probabilidad real en servidor; la geometría visual ya no revela ni altera esa probabilidad.
</div>

<div class="row">
<div class="col-lg-8">
<form method="post" id="nxrAppearanceForm">

<div class="panel panel-default">
<div class="panel-heading"><strong>Identidad visual</strong></div>
<div class="panel-body">
    <div class="nxr-symmetric-note" style="margin-bottom:16px">
        <strong>Modo visual: Simétrico</strong><br>
        <?php if($activeCount > 0) { ?>Hay <?php echo number_format($activeCount); ?> premios activos: cada sector ocupará aproximadamente <strong><?php echo number_format($segmentAngle,2); ?>°</strong>.<?php } else { ?>Cuando existan premios activos, la rueda dividirá automáticamente los 360° en sectores idénticos.<?php } ?>
    </div>

    <div class="row">
        <div class="col-sm-6"><div class="form-group">
            <label>Preset</label>
            <select class="form-control" name="appearance_preset" id="nxrAppearancePreset">
                <?php foreach($presets as $key=>$preset) { ?>
                    <option value="<?php echo htmlspecialchars($key,ENT_QUOTES,'UTF-8'); ?>" <?php echo $appearance['appearance_preset']===$key?'selected':''; ?>><?php echo htmlspecialchars($preset['label'],ENT_QUOTES,'UTF-8'); ?></option>
                <?php } ?>
            </select>
            <span class="help-block">El preset rellena una base. Los colores pueden ajustarse después.</span>
        </div></div>
        <div class="col-sm-6"><div class="form-group">
            <label>Paleta de segmentos</label>
            <select class="form-control" name="segment_palette" id="nxrSegmentPalette">
                <option value="harmonic" <?php echo $appearance['segment_palette']==='harmonic'?'selected':''; ?>>Armónica oscura — recomendada</option>
                <option value="rarity" <?php echo $appearance['segment_palette']==='rarity'?'selected':''; ?>>Rareza por segmento</option>
            </select>
            <span class="help-block">Armónica mantiene la rueda elegante y usa la rareza como señal secundaria.</span>
        </div></div>
    </div>

    <div class="nxr-color-row">
        <div class="nxr-color-field"><label>Acento principal</label><input type="color" name="accent_color" id="nxrAccent" value="<?php echo htmlspecialchars($appearance['accent_color'],ENT_QUOTES,'UTF-8'); ?>"></div>
        <div class="nxr-color-field"><label>Acento claro</label><input type="color" name="accent_soft_color" id="nxrAccentSoft" value="<?php echo htmlspecialchars($appearance['accent_soft_color'],ENT_QUOTES,'UTF-8'); ?>"></div>
        <div class="nxr-color-field"><label>Color secundario</label><input type="color" name="secondary_color" id="nxrSecondary" value="<?php echo htmlspecialchars($appearance['secondary_color'],ENT_QUOTES,'UTF-8'); ?>"></div>
        <div class="nxr-color-field"><label>Panel</label><input type="color" name="panel_color" id="nxrPanelColor" value="<?php echo htmlspecialchars($appearance['panel_color'],ENT_QUOTES,'UTF-8'); ?>"></div>
        <div class="nxr-color-field"><label>Fondo</label><input type="color" name="background_color" id="nxrBackgroundColor" value="<?php echo htmlspecialchars($appearance['background_color'],ENT_QUOTES,'UTF-8'); ?>"></div>
    </div>
</div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><strong>Textos del sistema</strong></div>
<div class="panel-body">
    <div class="form-group"><label>Etiqueta superior</label><input class="form-control" maxlength="80" name="hero_kicker" id="nxrHeroKicker" value="<?php echo htmlspecialchars($appearance['hero_kicker'],ENT_QUOTES,'UTF-8'); ?>"></div>
    <div class="form-group"><label>Descripción</label><textarea class="form-control" rows="3" maxlength="280" name="hero_description" id="nxrHeroDescription"><?php echo htmlspecialchars($appearance['hero_description'],ENT_QUOTES,'UTF-8'); ?></textarea></div>
    <div class="row">
        <div class="col-sm-6"><div class="form-group"><label>Texto del centro</label><input class="form-control" maxlength="32" name="center_label" id="nxrCenterLabel" value="<?php echo htmlspecialchars($appearance['center_label'],ENT_QUOTES,'UTF-8'); ?>"></div></div>
        <div class="col-sm-6"><div class="form-group"><label>CTA principal</label><input class="form-control" maxlength="24" name="spin_cta_label" id="nxrSpinCtaLabel" value="<?php echo htmlspecialchars($appearance['spin_cta_label'],ENT_QUOTES,'UTF-8'); ?>"></div></div>
    </div>
</div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><strong>Geometría</strong></div>
<div class="panel-body">
    <div class="nxr-range-grid">
        <div class="form-group">
            <label>Tamaño máximo de la rueda</label>
            <div class="input-group"><input type="number" min="480" max="720" step="10" class="form-control" name="wheel_size" id="nxrWheelSize" value="<?php echo (int)$appearance['wheel_size']; ?>"><span class="input-group-addon">px</span></div>
        </div>
        <div class="form-group">
            <label>Separación visual entre segmentos</label>
            <div class="input-group"><input type="number" min="1" max="7" class="form-control" name="segment_gap" id="nxrSegmentGap" value="<?php echo (int)$appearance['segment_gap']; ?>"><span class="input-group-addon">px</span></div>
        </div>
    </div>
    <div class="checkbox"><label><input type="checkbox" name="show_segment_labels" value="1" <?php echo !empty($appearance['show_segment_labels'])?'checked':''; ?>> Mostrar nombres dentro de la rueda</label></div>
    <span class="help-block">El orden alrededor de la rueda usa el campo <strong>Orden visual</strong> de cada premio. El peso ya no modifica la geometría.</span>
</div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><strong>Movimiento y aterrizaje</strong></div>
<div class="panel-body">
    <div class="row">
        <div class="col-sm-4"><div class="form-group"><label>Duración</label><div class="input-group"><input type="number" min="3500" max="8000" step="100" class="form-control" name="spin_duration_ms" id="nxrSpinDuration" value="<?php echo (int)$appearance['spin_duration_ms']; ?>"><span class="input-group-addon">ms</span></div></div></div>
        <div class="col-sm-4"><div class="form-group"><label>Vueltas mínimas</label><input type="number" min="5" max="15" class="form-control" name="turns_min" id="nxrTurnsMin" value="<?php echo (int)$appearance['turns_min']; ?>"></div></div>
        <div class="col-sm-4"><div class="form-group"><label>Vueltas máximas</label><input type="number" min="5" max="18" class="form-control" name="turns_max" id="nxrTurnsMax" value="<?php echo (int)$appearance['turns_max']; ?>"></div></div>
    </div>
    <div class="nxr-check-grid">
        <label><input type="checkbox" name="pointer_bounce" value="1" <?php echo !empty($appearance['pointer_bounce'])?'checked':''; ?>> Impacto del puntero al detener</label>
        <label><input type="checkbox" name="landing_pulse" value="1" <?php echo !empty($appearance['landing_pulse'])?'checked':''; ?>> Pulso del núcleo al aterrizar</label>
        <label><input type="checkbox" name="winner_glow" value="1" <?php echo !empty($appearance['winner_glow'])?'checked':''; ?>> Glow del segmento ganador</label>
        <label><input type="checkbox" name="dim_non_winners" value="1" <?php echo !empty($appearance['dim_non_winners'])?'checked':''; ?>> Reducir sectores no ganadores al final</label>
    </div>
</div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><strong>Nexora Sound Identity</strong> <span class="label label-primary">V1.8.1</span></div>
<div class="panel-body">
    <div class="alert alert-info" style="margin-bottom:16px">
        <strong>Audio sincronizado con el resultado real:</strong> los sonidos acompañan el giro confirmado por servidor. No se generan falsos casi-premios ni señales que alteren la probabilidad percibida.
    </div>
    <div class="row">
        <div class="col-sm-4"><div class="form-group">
            <label>Perfil sonoro</label>
            <select class="form-control" name="sound_profile" id="nxrSoundProfile">
                <option value="nexora" <?php echo $appearance['sound_profile']==='nexora'?'selected':''; ?>>Nexora — recomendado</option>
                <option value="minimal" <?php echo $appearance['sound_profile']==='minimal'?'selected':''; ?>>Minimal</option>
                <option value="silent" <?php echo $appearance['sound_profile']==='silent'?'selected':''; ?>>Silencioso</option>
            </select>
            <span class="help-block">Nexora utiliza samples OGG propios + Web Audio. Minimal conserva señales discretas. Silencioso desactiva toda la identidad sonora.</span>
        </div></div>
        <div class="col-sm-4"><div class="form-group">
            <label>Volumen general</label>
            <div class="input-group"><input type="number" min="0" max="100" class="form-control" name="sound_volume" id="nxrSoundVolume" value="<?php echo (int)$appearance['sound_volume']; ?>"><span class="input-group-addon">%</span></div>
            <span class="help-block">El jugador todavía puede silenciar localmente desde la ruleta.</span>
        </div></div>
        <div class="col-sm-4"><div class="form-group">
            <label>Intensidad cinematográfica</label>
            <div class="input-group"><input type="number" min="0" max="100" class="form-control" name="sound_intensity" id="nxrSoundIntensity" value="<?php echo (int)$appearance['sound_intensity']; ?>"><span class="input-group-addon">%</span></div>
            <span class="help-block">Controla capas y presencia; no cambia la duración ni el resultado del giro.</span>
        </div></div>
    </div>
    <div class="row">
        <div class="col-sm-6"><div class="form-group">
            <label>Retardo de revelación</label>
            <div class="input-group"><input type="number" min="200" max="1200" step="20" class="form-control" name="reveal_delay_ms" id="nxrRevealDelay" value="<?php echo (int)$appearance['reveal_delay_ms']; ?>"><span class="input-group-addon">ms</span></div>
            <span class="help-block">Pausa entre la parada exacta y la aparición del premio.</span>
        </div></div>
        <div class="col-sm-6"><div class="form-group">
            <label>Arquitectura</label>
            <p class="form-control-static"><strong>Samples OGG precargados + fallback procedimental</strong></p>
            <span class="help-block">Si un sample aún no está listo o Web Audio no está disponible, la ruleta conserva señales procedimentales y toda la animación visual.</span>
        </div></div>
    </div>
    <hr style="margin:10px 0 16px">
    <div class="nxr-check-grid">
        <label><input type="checkbox" name="sound_enabled" value="1" <?php echo !empty($appearance['sound_enabled'])?'checked':''; ?>> Audio de Ruleta Nexora</label>
        <label><input type="checkbox" name="sound_spin_start" value="1" <?php echo !empty($appearance['sound_spin_start'])?'checked':''; ?>> Golpe + carga al iniciar giro</label>
        <label><input type="checkbox" name="segment_ticks" value="1" <?php echo !empty($appearance['segment_ticks'])?'checked':''; ?>> Tick físico por cruce de sector</label>
        <label><input type="checkbox" name="sound_landing" value="1" <?php echo !empty($appearance['sound_landing'])?'checked':''; ?>> Impacto al aterrizar</label>
        <label><input type="checkbox" name="rarity_stinger" value="1" <?php echo !empty($appearance['rarity_stinger'])?'checked':''; ?>> Firma sonora según rareza</label>
        <label><input type="checkbox" name="sound_wc" value="1" <?php echo !empty($appearance['sound_wc'])?'checked':''; ?>> Firma de WCoinC</label>
        <label><input type="checkbox" name="sound_fragments" value="1" <?php echo !empty($appearance['sound_fragments'])?'checked':''; ?>> Firma de Fragmento NXR</label>
        <label><input type="checkbox" name="sound_reentry" value="1" <?php echo !empty($appearance['sound_reentry'])?'checked':''; ?>> Firma de Reentrada / giro adicional</label>
        <label><input type="checkbox" name="show_segment_icons" value="1" <?php echo !empty($appearance['show_segment_icons'])?'checked':''; ?>> Iconos dentro de los segmentos</label>
        <label><input type="checkbox" name="premium_reveal" value="1" <?php echo !empty($appearance['premium_reveal'])?'checked':''; ?>> Revelación premium del ganador</label>
    </div>
    <span class="help-block" style="margin-top:12px">El perfil <strong>Nexora</strong> está calibrado para mantener claridad: los ticks informan movimiento; WC, Fragmentos y Reentrada tienen identidad propia; y Raro/Épico/Legendario reciben firmas más profundas sin simular resultados que no ocurrieron.</span>
</div>
</div>

<div class="panel panel-default">
<div class="panel-heading"><strong>Bloques visibles</strong></div>
<div class="panel-body">
    <div class="nxr-check-grid">
        <label><input type="checkbox" name="show_stats" value="1" <?php echo !empty($appearance['show_stats'])?'checked':''; ?>> Métricas superiores</label>
        <label><input type="checkbox" name="show_pool" value="1" <?php echo !empty($appearance['show_pool'])?'checked':''; ?>> Panel lateral de pool</label>
        <label><input type="checkbox" name="show_history" value="1" <?php echo !empty($appearance['show_history'])?'checked':''; ?>> Trazabilidad de la cuenta</label>
    </div>
    <span class="help-block">Las probabilidades y la actividad reciente siguen gobernadas desde Configuración.</span>
</div>
</div>

<button class="btn btn-success btn-lg" type="submit" name="save_appearance" value="1"><i class="fa fa-save"></i> Guardar personalización</button>
<a class="btn btn-default btn-lg" target="_blank" href="<?php echo __BASE_URL__.'roulette/'; ?>"><i class="fa fa-external-link"></i> Abrir ruleta</a>
</form>
</div>

<div class="col-lg-4">
<div class="nxr-appearance-preview" id="nxrAppearancePreview">
    <div class="nxr-preview-head">
        <div><span id="nxrPreviewKicker"><?php echo htmlspecialchars($appearance['hero_kicker'],ENT_QUOTES,'UTF-8'); ?></span><h3>Ruleta Nexora</h3></div>
        <div class="nxr-preview-wallet"><span>WCoinC</span><b>8,857,403</b></div>
    </div>
    <div class="nxr-preview-wheel-wrap" id="nxrPreviewWheelWrap">
        <div class="nxr-preview-pointer" id="nxrPreviewPointer"></div>
        <div class="nxr-preview-wheel" id="nxrPreviewWheel"></div>
        <div class="nxr-preview-core" id="nxrPreviewCore"><b>NXR</b><small id="nxrPreviewCenterLabel"><?php echo htmlspecialchars($appearance['center_label'],ENT_QUOTES,'UTF-8'); ?></small></div>
    </div>
    <div class="nxr-preview-button" id="nxrPreviewButton"><?php echo htmlspecialchars($appearance['spin_cta_label'],ENT_QUOTES,'UTF-8'); ?><br><small>500 WCoinC</small></div>
    <div class="nxr-preview-meta"><div><span>SEGMENTOS</span><b><?php echo $activeCount>0?number_format($activeCount):'8'; ?> iguales</b></div><div><span>GIRO</span><b id="nxrPreviewDuration"><?php echo number_format((int)$appearance['spin_duration_ms']/1000,1); ?> s</b></div></div>
</div>
</div>
</div>
</div>

<script>
(function(){
    var presets=<?php echo json_encode($presets,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); ?>;
    var preset=document.getElementById('nxrAppearancePreset');
    var accent=document.getElementById('nxrAccent');
    var accentSoft=document.getElementById('nxrAccentSoft');
    var secondary=document.getElementById('nxrSecondary');
    var panel=document.getElementById('nxrPanelColor');
    var background=document.getElementById('nxrBackgroundColor');
    var preview=document.getElementById('nxrAppearancePreview');
    var wheel=document.getElementById('nxrPreviewWheel');
    var core=document.getElementById('nxrPreviewCore');
    var pointer=document.getElementById('nxrPreviewPointer');
    var button=document.getElementById('nxrPreviewButton');
    var kicker=document.getElementById('nxrPreviewKicker');
    var center=document.getElementById('nxrPreviewCenterLabel');
    var duration=document.getElementById('nxrSpinDuration');
    var durationView=document.getElementById('nxrPreviewDuration');
    var wheelSize=document.getElementById('nxrWheelSize');
    var wheelWrap=document.getElementById('nxrPreviewWheelWrap');
    var cta=document.getElementById('nxrSpinCtaLabel');

    function shade(hex,percent){
        var n=parseInt(hex.slice(1),16),amt=Math.round(2.55*percent),r=(n>>16)+amt,g=(n>>8&255)+amt,b=(n&255)+amt;
        return '#'+(0x1000000+(r<255?r<1?0:r:255)*0x10000+(g<255?g<1?0:g:255)*0x100+(b<255?b<1?0:b:255)).toString(16).slice(1);
    }
    function updatePreview(){
        var a=accent.value,soft=accentSoft.value,sec=secondary.value,p=panel.value,bg=background.value;
        preview.style.background='radial-gradient(circle at top right,'+sec+'33,transparent 28%),linear-gradient(180deg,'+p+','+bg+')';
        preview.style.borderColor=a+'55';
        pointer.style.borderTopColor=soft;
        core.style.borderColor=a;
        core.querySelector('b').style.color=soft;
        button.style.background='linear-gradient(180deg,'+soft+','+a+' 55%,'+shade(a,-35)+')';
        var d1=shade(p,8),d2=shade(p,-5);
        wheel.style.background='conic-gradient('+d1+' 0 45deg,'+d2+' 45deg 90deg,'+d1+' 90deg 135deg,'+d2+' 135deg 180deg,'+d1+' 180deg 225deg,'+d2+' 225deg 270deg,'+d1+' 270deg 315deg,'+d2+' 315deg 360deg)';
        wheel.style.boxShadow='0 0 0 2px '+a+'88,0 14px 38px rgba(0,0,0,.45)';
        kicker.textContent=document.getElementById('nxrHeroKicker').value || 'ECONOMÍA DE RECOMPENSAS';
        center.textContent=document.getElementById('nxrCenterLabel').value || 'RULETA NEXORA';
        button.firstChild.nodeValue=(cta.value || 'GIRAR');
        durationView.textContent=((parseInt(duration.value,10)||5200)/1000).toFixed(1)+' s';
        var size=parseInt(wheelSize.value,10)||620;
        wheelWrap.style.maxWidth=Math.max(280,Math.min(340,size*.55))+'px';
    }
    preset.addEventListener('change',function(){
        var p=presets[this.value]; if(!p)return;
        accent.value=p.accent_color; accentSoft.value=p.accent_soft_color; secondary.value=p.secondary_color; panel.value=p.panel_color; background.value=p.background_color; updatePreview();
    });
    [accent,accentSoft,secondary,panel,background,document.getElementById('nxrHeroKicker'),document.getElementById('nxrCenterLabel'),duration,wheelSize,cta].forEach(function(el){if(el)el.addEventListener('input',updatePreview);});
    updatePreview();
})();
</script>
