// ── INICIO / CIERRE DE DÍA ───────────────────────────

function InicioCierreDia({ tiendaId, setModulo }) {
  const { useState, useEffect } = React;

  const tienda = TIENDAS.find(t=>t.id===tiendaId)||TIENDAS[0];
  const [modo, setModo] = useState(null); // 'inicio' | 'cierre' | null
  const [fechaHoy] = useState(new Date().toLocaleDateString('es-CL',{weekday:'long',day:'numeric',month:'long'}));
  const [responsable, setResponsable] = useState('');
  const [cajaInicial, setCajaInicial] = useState('');
  const [notas, setNotas] = useState('');

  // Checklists editables
  const [checkInicio, setCheckInicio] = useState([
    {id:'ci1',  label:'Seleccionar cuenta activa',                   ok:true},
    {id:'ci2',  label:'Revisar caja inicial y contar billetes',      ok:false},
    {id:'ci3',  label:'Limpiar vitrinas',                            ok:false},
    {id:'ci4',  label:'Ordenar productos en vitrinas',               ok:false},
    {id:'ci5',  label:'Encender luces y TVs',                        ok:false},
    {id:'ci6',  label:'Revisar impresoras (Godex + ticket)',          ok:false},
    {id:'ci7',  label:'Revisar lector de códigos',                   ok:false},
    {id:'ci8',  label:'Revisar conexión a internet',                 ok:false},
    {id:'ci9',  label:'Revisar órdenes de trabajo pendientes',       ok:false},
    {id:'ci10', label:'Revisar productos por entregar hoy',          ok:false},
    {id:'ci11', label:'Revisar stock crítico',                       ok:false},
    {id:'ci12', label:'Revisar pedidos online pendientes',           ok:false},
  ]);

  const [checkCierre, setCheckCierre] = useState([
    {id:'cc1',  label:'Revisar ventas del día',                      ok:false},
    {id:'cc2',  label:'Contar efectivo en caja',                     ok:false},
    {id:'cc3',  label:'Comparar caja física vs sistema',             ok:false},
    {id:'cc4',  label:'Registrar diferencias de caja (si existen)',  ok:false},
    {id:'cc5',  label:'Registrar gastos del día',                    ok:false},
    {id:'cc6',  label:'Registrar retiros',                           ok:false},
    {id:'cc7',  label:'Revisar órdenes de trabajo entregadas',       ok:false},
    {id:'cc8',  label:'Revisar movimientos de inventario',           ok:false},
    {id:'cc9',  label:'Imprimir cierre de caja',                     ok:false},
    {id:'cc10', label:'Apagar impresoras y equipos',                 ok:false},
    {id:'cc11', label:'Guardar productos bajo llave',                ok:false},
    {id:'cc12', label:'Cerrar y asegurar local',                     ok:false},
  ]);

  // Stats del día (simulados)
  const ventasDia   = VENTAS_RECIENTES.filter(v=>v.tienda===tiendaId&&v.fecha==='2026-04-20');
  const totalVentas = ventasDia.reduce((s,v)=>s+v.total,0);
  const otsPend     = ORDENES.filter(o=>o.tiendaOrigen===tiendaId&&o.estado!=='Entregado').length;
  const otListas    = ORDENES.filter(o=>o.tiendaOrigen===tiendaId&&o.estado==='Listo').length;

  // Resumen de caja simulado
  const [efectivoContado, setEfectivoContado] = useState('');
  const efectivoSistema = 177500;
  const diferencia = (parseInt(efectivoContado)||0) - efectivoSistema;

  function toggleCheck(lista, setLista, id) {
    setLista(prev=>prev.map(c=>c.id===id?{...c,ok:!c.ok}:c));
  }

  function imprimirCierre() {
    const win = window.open('','_blank','width=400,height=600');
    if (!win) return;
    const fecha = new Date().toLocaleString('es-CL');
    win.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8">
    <title>Cierre ${tienda.nombre}</title>
    <style>
      body{font-family:'Courier New',monospace;font-size:11px;width:270px;margin:0 auto;padding:8px 4px}
      .c{text-align:center}.b{font-weight:bold}.hr{border:none;border-top:1px dashed #000;margin:4px 0}
      .row{display:flex;justify-content:space-between}
    </style></head><body>
    <div class="c b" style="font-size:15px">NAVARRO</div>
    <div class="c" style="font-size:9px">${tienda.nombre}</div>
    <div class="c" style="font-size:9px">${fecha}</div>
    <hr class="hr">
    <div class="c b">CIERRE DE CAJA</div>
    <hr class="hr">
    <div class="row"><span>Ventas del día</span><span class="b">$${totalVentas.toLocaleString('es-CL')}</span></div>
    <div class="row"><span>Efectivo sistema</span><span>$${efectivoSistema.toLocaleString('es-CL')}</span></div>
    ${efectivoContado?`<div class="row"><span>Efectivo contado</span><span>$${parseInt(efectivoContado).toLocaleString('es-CL')}</span></div>
    <div class="row"><span>Diferencia</span><span class="b" style="color:${diferencia===0?'black':'red'}">${diferencia>=0?'+':''}$${diferencia.toLocaleString('es-CL')}</span></div>`:''}
    <hr class="hr">
    <div class="row"><span>OT pendientes</span><span>${otsPend}</span></div>
    <div class="row"><span>OT listas</span><span>${otListas}</span></div>
    <hr class="hr">
    <div class="row"><span>Responsable</span><span>${responsable||'—'}</span></div>
    ${notas?`<div style="margin-top:4px;font-size:10px">Notas: ${notas}</div>`:''}
    <hr class="hr">
    <div class="c" style="font-size:9px;margin-top:6px">✦ Valle de Colchagua</div>
    </body></html>`);
    win.document.close();
    setTimeout(()=>win.print(),400);
  }

  const S = diaStyles;

  // ── Pantalla de selección ──
  if (!modo) return (
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',
      justifyContent:'center',height:'100%',gap:'20px',padding:'24px'}}>
      <div style={{textAlign:'center',marginBottom:'10px'}}>
        <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'32px',fontWeight:300,
          color:'var(--cream)',marginBottom:'6px'}}>✦ {tienda.nombre}</div>
        <div style={{color:'var(--cream-3)',fontSize:'14px',textTransform:'capitalize'}}>{fechaHoy}</div>
      </div>

      {/* KPIs rápidos */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:'10px',
        width:'100%',maxWidth:'600px'}}>
        {[
          {icon:'💰',label:'Ventas hoy',   val:clp(totalVentas)||'$0'},
          {icon:'🔧',label:'OT pendientes',val:otsPend},
          {icon:'✅',label:'OT listas',    val:otListas,alert:otListas>0},
          {icon:'⚠️',label:'Stock crítico',val:PRODUCTOS.filter(p=>p.stock<=1&&p.tienda===tiendaId).length},
        ].map(k=>(
          <div key={k.label} style={{background:'var(--bg-card)',border:'1px solid var(--border)',
            borderRadius:'12px',padding:'16px',textAlign:'center'}}>
            <div style={{fontSize:'22px',marginBottom:'4px'}}>{k.icon}</div>
            <div style={{color:k.alert?'var(--gold)':'var(--cream)',fontWeight:700,fontSize:'18px'}}>{k.val}</div>
            <div style={{color:'var(--cream-3)',fontSize:'10px',marginTop:'2px'}}>{k.label}</div>
          </div>
        ))}
      </div>

      <div style={{display:'flex',gap:'16px',width:'100%',maxWidth:'600px'}}>
        <button onClick={()=>setModo('inicio')}
          style={{...S.modoBtn, flex:1, borderColor:'rgba(39,174,96,0.4)'}}>
          <div style={{fontSize:'32px',marginBottom:'8px'}}>🌅</div>
          <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'22px',fontWeight:600,
            color:'var(--cream)',marginBottom:'4px'}}>Inicio de Día</div>
          <div style={{color:'var(--cream-3)',fontSize:'12px'}}>Checklist de apertura</div>
        </button>
        <button onClick={()=>setModo('cierre')}
          style={{...S.modoBtn, flex:1, borderColor:'rgba(192,57,43,0.4)'}}>
          <div style={{fontSize:'32px',marginBottom:'8px'}}>🌙</div>
          <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'22px',fontWeight:600,
            color:'var(--cream)',marginBottom:'4px'}}>Cierre de Día</div>
          <div style={{color:'var(--cream-3)',fontSize:'12px'}}>Cuadrar caja y cerrar</div>
        </button>
      </div>
    </div>
  );

  const checkActivo = modo==='inicio' ? checkInicio : checkCierre;
  const setCheck    = modo==='inicio' ? setCheckInicio : setCheckCierre;
  const completadas = checkActivo.filter(c=>c.ok).length;
  const pct         = Math.round(completadas/checkActivo.length*100);

  return (
    <div style={{display:'flex',height:'100%',overflow:'hidden'}}>
      {/* Checklist */}
      <div style={{flex:1,overflowY:'auto',padding:'20px'}}>
        <div style={{display:'flex',alignItems:'center',gap:'12px',marginBottom:'20px'}}>
          <button onClick={()=>setModo(null)} style={inv2Styles.btnSec}>← Volver</button>
          <div>
            <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'24px',fontWeight:600,color:'var(--cream)'}}>
              {modo==='inicio'?'🌅 Inicio de Día':'🌙 Cierre de Día'}
            </div>
            <div style={{color:'var(--cream-3)',fontSize:'12px'}}>{tienda.nombre} · {fechaHoy}</div>
          </div>
        </div>

        {/* Progreso */}
        <div style={{background:'var(--bg-card)',border:'1px solid var(--border)',
          borderRadius:'12px',padding:'16px',marginBottom:'16px'}}>
          <div style={{display:'flex',justifyContent:'space-between',marginBottom:'8px'}}>
            <span style={{color:'var(--cream)',fontSize:'13px',fontWeight:500}}>
              {completadas}/{checkActivo.length} completadas
            </span>
            <span style={{color:pct===100?'#27ae60':'var(--gold)',fontWeight:700,fontSize:'14px'}}>
              {pct}%
            </span>
          </div>
          <div style={{height:'8px',background:'var(--surface)',borderRadius:'4px',overflow:'hidden'}}>
            <div style={{height:'100%',width:`${pct}%`,
              background:pct===100?'#27ae60':'var(--gold)',
              borderRadius:'4px',transition:'width 0.3s'}}/>
          </div>
          {pct===100&&<div style={{marginTop:'8px',color:'#27ae60',fontSize:'12px',fontWeight:500}}>
            ✓ ¡Listo! Todas las tareas completadas
          </div>}
        </div>

        {/* Checklist items */}
        {checkActivo.map((c,i)=>(
          <div key={c.id} onClick={()=>toggleCheck(checkActivo,setCheck,c.id)}
            style={{...S.checkItem,...(c.ok?S.checkItemOk:{})}}>
            <div style={{width:'22px',height:'22px',borderRadius:'50%',flexShrink:0,
              background:c.ok?'#27ae60':'var(--surface)',
              border:`2px solid ${c.ok?'#27ae60':'var(--border)'}`,
              display:'flex',alignItems:'center',justifyContent:'center',
              color:'white',fontSize:'12px',transition:'all 0.2s'}}>
              {c.ok?'✓':''}
            </div>
            <span style={{color:c.ok?'var(--cream-2)':'var(--cream)',fontSize:'13px',
              textDecoration:c.ok?'line-through':'none',flex:1}}>
              {c.label}
            </span>
          </div>
        ))}

        {/* Responsable / notas */}
        <div style={{marginTop:'16px',display:'grid',gridTemplateColumns:'1fr 1fr',gap:'10px'}}>
          <div>
            <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Responsable del turno</div>
            <input style={calcStyles.input} placeholder="Nombre"
              value={responsable} onChange={e=>setResponsable(e.target.value)}/>
          </div>
          <div>
            <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Caja inicial CLP</div>
            <input type="number" style={calcStyles.input} placeholder="0"
              value={cajaInicial} onChange={e=>setCajaInicial(e.target.value)}/>
          </div>
          <div style={{gridColumn:'1/-1'}}>
            <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Notas del turno</div>
            <textarea style={{...calcStyles.input,height:'60px'}}
              placeholder="Observaciones, incidencias, pendientes…"
              value={notas} onChange={e=>setNotas(e.target.value)}/>
          </div>
        </div>
      </div>

      {/* Panel lateral derecho */}
      <div style={{width:'280px',borderLeft:'1px solid var(--border)',padding:'18px',
        overflowY:'auto',flexShrink:0}}>
        <div style={{fontFamily:'Cormorant Garamond,serif',fontSize:'16px',fontWeight:600,
          color:'var(--cream)',marginBottom:'14px'}}>
          {modo==='cierre'?'Cuadre de Caja':'Resumen del Día'}
        </div>

        {modo==='cierre' && (
          <div style={{marginBottom:'16px'}}>
            {[
              {l:'Ventas registradas', v:clp(totalVentas), c:'#27ae60'},
              {l:'Efectivo sistema',   v:clp(efectivoSistema)},
            ].map(r=>(
              <div key={r.l} style={{display:'flex',justifyContent:'space-between',
                padding:'7px 0',borderBottom:'1px solid var(--border)',fontSize:'12px'}}>
                <span style={{color:'var(--cream-3)'}}>{r.l}</span>
                <span style={{color:r.c||'var(--cream)',fontWeight:600}}>{r.v}</span>
              </div>
            ))}
            <div style={{marginTop:'10px',marginBottom:'8px'}}>
              <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'4px'}}>Efectivo contado físicamente</div>
              <input type="number" style={calcStyles.input} placeholder="0"
                value={efectivoContado} onChange={e=>setEfectivoContado(e.target.value)}/>
            </div>
            {efectivoContado && (
              <div style={{padding:'10px',borderRadius:'8px',textAlign:'center',
                background:diferencia===0?'rgba(39,174,96,0.1)':
                  Math.abs(diferencia)<=1000?'rgba(243,156,18,0.1)':'rgba(192,57,43,0.1)',
                border:`1px solid ${diferencia===0?'rgba(39,174,96,0.3)':
                  Math.abs(diferencia)<=1000?'rgba(243,156,18,0.3)':'rgba(192,57,43,0.3)'}`}}>
                <div style={{fontSize:'11px',color:'var(--cream-3)',marginBottom:'2px'}}>
                  {diferencia===0?'Caja cuadrada':diferencia>0?'Sobrante':'Faltante'}
                </div>
                <div style={{fontWeight:700,fontSize:'18px',
                  color:diferencia===0?'#27ae60':Math.abs(diferencia)<=1000?'#f39c12':'#c0392b'}}>
                  {diferencia>=0?'+':''}{clp(diferencia)}
                </div>
              </div>
            )}
          </div>
        )}

        {/* Accesos rápidos del día */}
        <div style={{display:'flex',flexDirection:'column',gap:'6px',marginBottom:'16px'}}>
          {[
            {icon:'📊',label:'Ver reportes del día', mod:'reportes'},
            {icon:'🔧',label:'Órdenes pendientes',   mod:'ordenes'},
            {icon:'📦',label:'Stock crítico',         mod:'inventario'},
          ].map(a=>(
            <button key={a.label} onClick={()=>setModulo&&setModulo(a.mod)}
              style={{...inv2Styles.btnSec,display:'flex',gap:'8px',alignItems:'center',
                padding:'8px 12px',fontSize:'12px',textAlign:'left'}}>
              {a.icon} {a.label}
            </button>
          ))}
        </div>

        {/* Botones acción */}
        {modo==='cierre'&&(
          <button onClick={imprimirCierre}
            style={{...posStyles.cobrarBtn,width:'100%',margin:0,fontSize:'13px',marginBottom:'8px'}}>
            🖨 Imprimir Cierre de Caja
          </button>
        )}
        <button onClick={()=>{
          alert(`✓ ${modo==='inicio'?'Apertura':'Cierre'} registrado correctamente.\n${tienda.nombre} · ${fechaHoy}`);
          setModo(null);
        }} style={{width:'100%',padding:'12px',
          background:modo==='inicio'?'rgba(39,174,96,0.15)':'rgba(192,57,43,0.15)',
          border:`1px solid ${modo==='inicio'?'rgba(39,174,96,0.4)':'rgba(192,57,43,0.4)'}`,
          borderRadius:'10px',cursor:'pointer',fontSize:'13px',fontWeight:600,
          color:modo==='inicio'?'#27ae60':'#c0392b',fontFamily:'Inter,sans-serif'}}>
          ✓ Confirmar {modo==='inicio'?'Apertura':'Cierre'}
        </button>
      </div>
    </div>
  );
}

const diaStyles = {
  modoBtn:{ display:'flex', flexDirection:'column', alignItems:'center', padding:'24px',
    background:'var(--bg-card)', border:'1px solid var(--border)', borderRadius:'16px',
    cursor:'pointer', transition:'all 0.2s', fontFamily:'Inter,sans-serif' },
  checkItem:{ display:'flex', alignItems:'center', gap:'12px', padding:'12px 14px',
    borderRadius:'8px', cursor:'pointer', marginBottom:'5px', transition:'all 0.1s',
    background:'var(--bg-card)', border:'1px solid var(--border)' },
  checkItemOk:{ background:'rgba(39,174,96,0.05)', borderColor:'rgba(39,174,96,0.2)' },
};

Object.assign(window, { InicioCierreDia });
