<?php /* Incluir en todas las páginas: <?php include 'theme.php'; ?> */ ?>
<style id="themeStyle">
:root{
  --t-primary:#1565C0;--t-primary2:#1E88E5;--t-accent:#29B6F6;
  --t-fondo:#EBF5FF;--t-sidebar:#0D1B30;--t-card:#ffffff;
  --t-texto:#0D2A4A;--t-muted:#5A7FA8;--t-borde:#90CAF9;
  --t-sidebar-text:#E8F2FF;--t-nav-active:rgba(41,182,246,.12);
  --t-btn-text:#ffffff;
}
</style>

<!-- FLOTANTE TEMA -->
<div id="themeBtn" onclick="themeToggle()" title="Cambiar tema"
  style="position:fixed;bottom:20px;left:18px;z-index:9998;
         width:46px;height:46px;border-radius:50%;
         background:var(--t-primary);color:#fff;border:3px solid rgba(255,255,255,.25);
         display:flex;align-items:center;justify-content:center;
         font-size:20px;cursor:pointer;
         box-shadow:0 4px 16px rgba(0,0,0,.3);
         transition:transform .2s,box-shadow .2s;
         user-select:none">
  🎨
</div>

<!-- PANEL TEMAS -->
<div id="themePanel"
  style="display:none;position:fixed;bottom:74px;left:14px;z-index:9997;
         background:#fff;border-radius:16px;padding:16px;width:240px;
         box-shadow:0 8px 40px rgba(0,0,0,.2);border:1px solid #e0e0e0;
         animation:themePop .2s cubic-bezier(.16,1,.3,1)">
  <div style="font-family:'Exo 2',sans-serif;font-size:11px;font-weight:800;
              letter-spacing:2px;text-transform:uppercase;color:#888;margin-bottom:12px;
              display:flex;justify-content:space-between;align-items:center">
    <span>🎨 TEMA</span>
    <span onclick="themeToggle()" style="cursor:pointer;font-size:16px;color:#aaa">✕</span>
  </div>
  <div id="themeGrid" style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px"></div>
  <div style="margin-top:12px;padding-top:10px;border-top:1px solid #f0f0f0;
              font-family:'Exo 2',sans-serif;font-size:9px;font-weight:700;
              letter-spacing:1.5px;text-transform:uppercase;color:#aaa;margin-bottom:8px">
    Contraste automático
  </div>
  <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:#555">
    <input type="checkbox" id="autoContraste" onchange="toggleAutoContraste(this.checked)"
           style="width:16px;height:16px;accent-color:var(--t-primary)">
    Ajuste automático de texto
  </label>
</div>

<style>
@keyframes themePop{from{opacity:0;transform:translateY(10px) scale(.96)}to{opacity:1;transform:none}}
#themeBtn:hover{transform:scale(1.1);box-shadow:0 6px 24px rgba(0,0,0,.35)}
.theme-swatch{width:100%;aspect-ratio:1;border-radius:10px;cursor:pointer;border:3px solid transparent;
  transition:transform .15s,border-color .15s;position:relative;overflow:hidden}
.theme-swatch:hover{transform:scale(1.08)}
.theme-swatch.active{border-color:#333;box-shadow:0 0 0 2px #fff,0 0 0 4px #333}
.theme-swatch .sw-dot{position:absolute;bottom:3px;right:3px;width:8px;height:8px;
  border-radius:50%;background:rgba(255,255,255,.6)}
</style>

<script>
const TEMAS = {
  azul:      {n:'Azul',       p:'#1565C0',p2:'#1E88E5',ac:'#29B6F6',f:'#EBF5FF',sb:'#0D1B30',card:'#fff',tx:'#0D2A4A',mu:'#5A7FA8',br:'#90CAF9',sbt:'#E8F2FF'},
  cielo:     {n:'Cielo',      p:'#0288D1',p2:'#03A9F4',ac:'#81D4FA',f:'#E1F5FE',sb:'#01579B',card:'#fff',tx:'#01579B',mu:'#4FC3F7',br:'#81D4FA',sbt:'#E1F5FE'},
  morado:    {n:'Morado',     p:'#6A1B9A',p2:'#8E24AA',ac:'#CE93D8',f:'#F3E5F5',sb:'#2D0060',card:'#fff',tx:'#2D0060',mu:'#AB47BC',br:'#CE93D8',sbt:'#F3E5F5'},
  rosa:      {n:'Rosa',       p:'#C2185B',p2:'#E91E63',ac:'#F48FB1',f:'#FCE4EC',sb:'#5D0038',card:'#fff',tx:'#5D0038',mu:'#EC407A',br:'#F48FB1',sbt:'#FCE4EC'},
  naranja:   {n:'Naranja',    p:'#E65100',p2:'#F57C00',ac:'#FFCC80',f:'#FFF3E0',sb:'#4E1A00',card:'#fff',tx:'#4E1A00',mu:'#FFA726',br:'#FFCC80',sbt:'#FFF3E0'},
  cafe:      {n:'Café',       p:'#4E342E',p2:'#6D4C41',ac:'#BCAAA4',f:'#EFEBE9',sb:'#1B0000',card:'#fff',tx:'#1B0000',mu:'#795548',br:'#BCAAA4',sbt:'#EFEBE9'},
  gris:      {n:'Gris',       p:'#455A64',p2:'#607D8B',ac:'#B0BEC5',f:'#ECEFF1',sb:'#1C313A',card:'#fff',tx:'#1C313A',mu:'#78909C',br:'#B0BEC5',sbt:'#ECEFF1'},
  negro:     {n:'Oscuro',     p:'#37474F',p2:'#546E7A',ac:'#80CBC4',f:'#1a1a2e',sb:'#0a0a0a',card:'#16213e',tx:'#E8EAED',mu:'#9AA0A6',br:'#2D3748',sbt:'#E8EAED'},
  verde:     {n:'Verde',      p:'#2E7D32',p2:'#388E3C',ac:'#81C784',f:'#E8F5E9',sb:'#0A3D0A',card:'#fff',tx:'#0A3D0A',mu:'#66BB6A',br:'#A5D6A7',sbt:'#E8F5E9'},
};

// Calcular luminancia y contraste
function luminancia(hex){
  const r=parseInt(hex.slice(1,3),16)/255,g=parseInt(hex.slice(3,5),16)/255,b=parseInt(hex.slice(5,7),16)/255;
  const f=v=>v<=.03928?v/12.92:Math.pow((v+.055)/1.055,2.4);
  return .2126*f(r)+.7152*f(g)+.0722*f(b);
}
function contrasteTexto(bg){
  const l=luminancia(bg);
  return l>.35?'#111111':'#FFFFFF';
}

function aplicarTema(id){
  const t=TEMAS[id];if(!t)return;
  const r=document.documentElement;
  r.style.setProperty('--t-primary',t.p);
  r.style.setProperty('--t-primary2',t.p2);
  r.style.setProperty('--t-accent',t.ac);
  r.style.setProperty('--t-fondo',t.f);
  r.style.setProperty('--t-sidebar',t.sb);
  r.style.setProperty('--t-card',t.card);
  r.style.setProperty('--t-texto',t.tx);
  r.style.setProperty('--t-muted',t.mu);
  r.style.setProperty('--t-borde',t.br);
  r.style.setProperty('--t-sidebar-text',t.sbt);
  // Auto contraste botón tema
  document.getElementById('themeBtn').style.background=t.p;
  document.getElementById('themeBtn').style.color=contrasteTexto(t.p);
  // Aplicar a elementos del DOM
  aplicarAlDOM(t);
  localStorage.setItem('procein_tema',id);
  document.querySelectorAll('.theme-swatch').forEach(s=>{
    s.classList.toggle('active',s.dataset.id===id);
  });
}

function aplicarAlDOM(t){
  // 1. CSS variables — cubren todos los módulos que usan var()
  const r=document.documentElement;
  r.style.setProperty('--azul',t.p);
  r.style.setProperty('--azul2',t.p2);
  r.style.setProperty('--acento',t.ac);
  r.style.setProperty('--fondo',t.f);
  r.style.setProperty('--borde',t.br);
  r.style.setProperty('--texto',t.tx);
  r.style.setProperty('--muted',t.mu);
  r.style.setProperty('--t-primary',t.p);
  r.style.setProperty('--t-primary2',t.p2);
  r.style.setProperty('--t-accent',t.ac);
  r.style.setProperty('--t-fondo',t.f);
  r.style.setProperty('--t-sidebar',t.sb);
  r.style.setProperty('--t-card',t.card);
  r.style.setProperty('--t-texto',t.tx);
  r.style.setProperty('--t-borde',t.br);

  // 2. Fondo body y sidebar
  if(document.body) document.body.style.background=t.f;
  const sb=document.querySelector('.sidebar');
  if(sb) sb.style.background=t.sb;

  // 3. Topbar
  const topbar=document.querySelector('.topbar');
  if(topbar){topbar.style.background=t.card;topbar.style.borderColor=t.br;}

  // 4. Cards / panels
  document.querySelectorAll('.section,.table-panel,.stat-card,.ant-modal,.card,.partida,.orden-info,.tk-wrap,.contrato,.verify-card').forEach(el=>{
    el.style.background=t.card;el.style.borderColor=t.br;
  });

  // 5. Welcome card
  const wc=document.querySelector('.welcome-card');
  if(wc) wc.style.background=`linear-gradient(135deg,${t.p} 0%,${t.p2} 60%,${t.ac} 100%)`;

  // 6. Texto principal con color del tema
  document.querySelectorAll('.topbar-title,.section-title,.table-title,.stat-num,.badge-folio,.folio-tag,.topbar-title em').forEach(el=>{
    el.style.color=t.p;
  });

  // 7. Section headers
  document.querySelectorAll('.section-header,.partida-header').forEach(el=>{
    el.style.background=`linear-gradient(90deg,${t.f},${t.card})`;
    el.style.borderColor=t.br;
  });

  // 8. Botones primarios
  document.querySelectorAll('.btn-submit,.ant-btn-pri,.btn-nueva-orden,.ant-btn-add,.btn-validar').forEach(el=>{
    el.style.background=`linear-gradient(135deg,${t.p},${t.p2})`;
    el.style.color='#ffffff';
  });

  // 9. Sidebar accents
  document.querySelectorAll('.sidebar-logo-text span,.user-role').forEach(el=>{
    el.style.color=t.ac;
  });
  document.querySelectorAll('.sub-item.active').forEach(el=>{
    el.style.color=t.ac;el.style.borderLeftColor=t.ac;
  });

  // 10. Botón tema flotante
  const tbtn=document.getElementById('themeBtn');
  if(tbtn){tbtn.style.background=t.p;tbtn.style.color=contrasteTexto(t.p);}

  // 11. AUTO CONTRASTE — solo fondo de página y sidebar
  const auto=localStorage.getItem('procein_autocontraste')==='1';
  if(auto){
    // Fondo de página: si es oscuro → texto claro en body
    const txFondo = luminancia(t.f) > 0.35 ? '#111111' : '#ffffff';
    document.body.style.color = txFondo;

    // Sidebar siempre claro (fondo oscuro)
    document.querySelectorAll('.user-name,.nav-label').forEach(el=>{
      el.style.color='#E8F2FF';
    });
    // NUNCA tocar td, th ni elementos con fondo propio
  } else {
    // Desactivado: limpiar todos los overrides
    document.body.style.color='';
    document.querySelectorAll('.user-name,.nav-label').forEach(el=>{
      el.style.color='';
    });
  }
}

function toggleAutoContraste(on){
  localStorage.setItem('procein_autocontraste',on?'1':'0');
  const id=localStorage.getItem('procein_tema')||'azul';
  aplicarTema(id);
}

function themeToggle(){
  const p=document.getElementById('themePanel');
  p.style.display=p.style.display==='none'?'block':'none';
}
// Cerrar al click fuera
document.addEventListener('click',function(e){
  const panel=document.getElementById('themePanel');
  const btn=document.getElementById('themeBtn');
  if(panel&&btn&&!panel.contains(e.target)&&!btn.contains(e.target)){
    panel.style.display='none';
  }
});

// Construir swatches
function buildSwatches(){
  const grid=document.getElementById('themeGrid');
  if(!grid)return;
  grid.innerHTML='';
  const actual=localStorage.getItem('procein_tema')||'azul';
  Object.entries(TEMAS).forEach(([id,t])=>{
    const div=document.createElement('div');
    div.className='theme-swatch'+(id===actual?' active':'');
    div.dataset.id=id;
    div.title=t.n;
    div.style.background=`linear-gradient(135deg,${t.p},${t.p2},${t.ac})`;
    div.innerHTML=`<div class="sw-dot"></div>
      <div style="position:absolute;bottom:0;left:0;right:0;background:rgba(0,0,0,.35);
                  color:#fff;font-size:8px;font-family:'Exo 2',sans-serif;font-weight:700;
                  padding:2px;text-align:center;letter-spacing:.5px">${t.n}</div>`;
    div.onclick=()=>aplicarTema(id);
    grid.appendChild(div);
  });
  // Checkbox auto contraste
  const chk=document.getElementById('autoContraste');
  if(chk) chk.checked=localStorage.getItem('procein_autocontraste')==='1';
}

// Aplicar tema guardado al cargar
window.addEventListener('DOMContentLoaded',()=>{
  buildSwatches();
  const saved=localStorage.getItem('procein_tema')||'azul';
  aplicarTema(saved);
});
</script>
