const t = window.t || (k => k);
const History = () => {
  const {history, plans, go, toast} = useApp();
  const [filter, setFilter] = useState('all');
  const [range, setRange] = useState('30');
  const [q, setQ] = useState('');
  const [detail, setDetail] = useState(null);
  const now = Date.now();
  const filtered = history.filter(h => {
    if (filter!=='all' && h.status!==filter) return false;
    if (range!=='all') { const t=new Date(h.when).getTime(); if (now-t > parseInt(range)*86400000) return false; }
    if (q) { const s=q.toLowerCase(); if (!h.planName.toLowerCase().includes(s) && !h.from.toLowerCase().includes(s) && !h.to.toLowerCase().includes(s) && !(h.fpId||'').toLowerCase().includes(s)) return false; }
    return true;
  });
  const groups = {};
  filtered.forEach(h => { const key=h.when.slice(0,10); if (!groups[key]) groups[key]=[]; groups[key].push(h); });
  const sortedKeys = Object.keys(groups).sort((a,b)=>b.localeCompare(a));
  const fmtDay = (iso) => { const d=new Date(iso); const today=new Date();today.setHours(0,0,0,0); const diff=Math.floor((today-d)/86400000); if (diff===0) return t('hist.today'); if (diff===1) return t('hist.yesterday'); if (diff<7) return d.toLocaleDateString('es',{weekday:'long'}).replace(/^./,c=>c.toUpperCase()); return d.toLocaleDateString('es',{weekday:'short',day:'2-digit',month:'short'}).replace(/^./,c=>c.toUpperCase()); };
  const fmtTime = (iso) => new Date(iso).toLocaleTimeString('es',{hour:'2-digit',minute:'2-digit'});
  const okCount = history.filter(h=>h.status==='ok').length;
  const errCount = history.filter(h=>h.status==='error').length;
  return <div className="page fade-in">
    <section className="page-hero">
      <div className="page-hero-grid"/>
      <div className="page-hero-glow"/>
      <div className="page-hero-inner">
        <div style={{display:'flex',alignItems:'flex-end',justifyContent:'space-between',gap:20,flexWrap:'wrap'}}>
          <div>
            <div className="chip chip-accent eyebrow"><Icon name="clock" size={12}/> {t('hist.registry')}</div>
            <h1 className="display">
              <span className="word-rise" style={{animationDelay:'0s'}}>{t('hist.title')}</span>{' '}
              <span className="word-rise underline-swash" style={{animationDelay:'.08s'}}>{t('hist.title2')}</span>
            </h1>
            <p className="sub" style={{marginTop:14}}>{t('hist.subtitle')}</p>
          </div>
          <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
            <div className="card card-glow" style={{padding:'10px 16px',minWidth:90}}>
              <div className="caption" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'.1em',marginBottom:2}}>{t('hist.total')}</div>
              <div className="display" style={{fontSize:24,lineHeight:1}}>{history.length}</div>
            </div>
            <div className="card" style={{padding:'10px 16px',minWidth:90,borderColor:'color-mix(in srgb,var(--ok) 28%,var(--stroke))'}}>
              <div className="caption" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'.1em',marginBottom:2,color:'var(--ok)'}}>{t('hist.accepted')}</div>
              <div className="display" style={{fontSize:24,lineHeight:1,color:'var(--ok)'}}>{okCount}</div>
            </div>
            <div className="card" style={{padding:'10px 16px',minWidth:90,borderColor:'color-mix(in srgb,var(--err) 28%,var(--stroke))'}}>
              <div className="caption" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'.1em',marginBottom:2,color:'var(--err)'}}>{t('hist.failed')}</div>
              <div className="display" style={{fontSize:24,lineHeight:1,color:'var(--err)'}}>{errCount}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
    <div style={{position:'relative',marginBottom:12}}>
      <Icon name="search" size={16} style={{position:'absolute',left:14,top:'50%',transform:'translateY(-50%)',color:'var(--ink-low)'}}/>
      <input className="field" value={q} onChange={e=>setQ(e.target.value)} placeholder={t('hist.search')} style={{paddingLeft:40}}/>
    </div>
    <div style={{display:'flex',gap:6,marginBottom:10,overflowX:'auto',paddingBottom:4,alignItems:'center'}}>
      <span className="caption" style={{marginRight:4,flexShrink:0}}>{t('hist.status')}</span>
      {[{v:'all',l:t('hist.all')},{v:'ok',l:t('hist.accepted')},{v:'error',l:t('hist.failed')}].map(f=><button key={f.v} className={`pill ${filter===f.v?'active':''}`} onClick={()=>setFilter(f.v)}>{f.l}</button>)}
    </div>
    <div style={{display:'flex',gap:6,marginBottom:22,overflowX:'auto',paddingBottom:4,alignItems:'center'}}>
      <span className="caption" style={{marginRight:4,flexShrink:0}}>{t('hist.date')}</span>
      {[{v:'7',l:t('hist.days7')},{v:'30',l:t('hist.days30')},{v:'90',l:t('hist.days90')},{v:'all',l:t('hist.everything')}].map(f=><button key={f.v} className={`pill ${range===f.v?'active':''}`} onClick={()=>setRange(f.v)}>{f.l}</button>)}
    </div>

    <div style={{display:'flex',flexDirection:'column',gap:22}}>
      {sortedKeys.map(key => <div key={key}>
        <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:10}}>
          <div className="hist-day-label">{fmtDay(key)}</div>
          <div className="hr" style={{flex:1,background:'linear-gradient(90deg,rgba(244,162,97,.35),transparent)'}}/>
          <div className="caption" style={{fontSize:11}}>{groups[key].length}</div>
        </div>
        <div style={{display:'flex',flexDirection:'column',gap:8}}>
          {groups[key].map((h,i)=><button key={h.id} onClick={()=>setDetail(h)} className={`hist-row slide-up ${h.status==='ok'?'ok':'err'}`} style={{animationDelay:`${i*.02}s`}}>
            <div className={`chip-dot ${h.status==='ok'?'ok':'err'}`} style={{alignSelf:'center',position:'relative',zIndex:1}}/>
            <div style={{flex:1,minWidth:0,position:'relative',zIndex:1}}>
              <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:2,flexWrap:'wrap'}}>
                <span className="mono" style={{fontWeight:600,fontSize:13.5}}>{h.from} → {h.to}</span>
                <span className="chip chip-accent" style={{fontSize:10,padding:'2px 7px'}}>{RULES_FULL[h.rules]}</span>
                {h.fl && <span className="chip" style={{fontSize:10,padding:'2px 7px'}}>{h.fl}</span>}
                {h.aircraft && <span className="chip" style={{fontSize:10,padding:'2px 7px'}}>{h.aircraft}</span>}
              </div>
              <div className="caption" style={{fontSize:12,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{h.planName}{h.arcid ? ' · '+h.arcid : ''}</div>
            </div>
            <div style={{textAlign:'right',flexShrink:0,position:'relative',zIndex:1}}>
              <div className="mono" style={{fontSize:12,fontWeight:500}}>{fmtTime(h.when)}</div>
              {h.status==='ok'?<div className="caption mono" style={{fontSize:10,color:'var(--accent-ink)'}}>{h.fpId}</div>:<div className="caption" style={{fontSize:10,color:'var(--err)'}}>{t('hist.error')}</div>}
            </div>
            <Icon name="chev_right" size={14} style={{color:'var(--ink-low)',flexShrink:0,position:'relative',zIndex:1}}/>
          </button>)}
        </div>
      </div>)}
      {filtered.length===0 && <div className="card" style={{padding:40,textAlign:'center',color:'var(--ink-dim)'}}>{t('hist.no_results')}</div>}
    </div>

    {detail && <div className="modal-backdrop" onClick={()=>setDetail(null)}><div className="modal" onClick={e=>e.stopPropagation()}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:18,gap:10}}>
        <div><h2 className="display" style={{fontSize:22,marginBottom:2}}>{t('hist.details')}</h2><div className="caption">{new Date(detail.when).toLocaleDateString('es',{weekday:'long',day:'2-digit',month:'long',year:'numeric'})} · {fmtTime(detail.when)}</div></div>
        <button className="btn btn-ghost btn-icon" onClick={()=>setDetail(null)}><Icon name="x" size={16}/></button>
      </div>
      <div style={{padding:12,borderRadius:10,border:`1px solid ${detail.status==='ok'?'var(--ok)':'var(--err)'}`,background:detail.status==='ok'?'rgba(74,124,89,0.06)':'rgba(181,72,63,0.06)',marginBottom:16}}>
        <div style={{display:'flex',alignItems:'center',gap:10}}>
          <div className={`chip-dot ${detail.status==='ok'?'ok':'err'}`}/>
          <div style={{fontSize:13,fontWeight:600}}>{detail.status==='ok'?t('hist.plan_accepted'):t('hist.send_failed')}</div>
          {detail.status==='ok' && <div className="mono" style={{fontSize:12,marginLeft:'auto'}}>{detail.fpId}</div>}
        </div>
        {detail.status==='error' && detail.error && <div className="caption" style={{marginTop:8,color:'var(--err)',fontSize:12}}>{detail.error}</div>}
      </div>
      <div className="route-display" style={{padding:18,background:'var(--bg-inset)',borderRadius:12,marginBottom:16}}>
        <div><div className="icao" style={{fontSize:22}}>{detail.from}</div><div className="caption" style={{fontSize:10,marginTop:2}}>{AIRPORTS[detail.from]||''}</div></div>
        <div className="airport-arrow"><div className="line"/><Icon name="plane" size={14}/><div className="line"/></div>
        <div style={{textAlign:'right'}}><div className="icao" style={{fontSize:22}}>{detail.to}</div><div className="caption" style={{fontSize:10,marginTop:2}}>{AIRPORTS[detail.to]||''}</div></div>
      </div>
      <div className="card" style={{padding:16,marginBottom:16}}>
        {/* Identificacion */}
        <div className="caption" style={{fontSize:10,fontWeight:600,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--ink-dim)',marginBottom:6}}>Identificacion</div>
        {detail.arcid && <div className="kv"><span className="kv-k">ARCID</span><span className="kv-v mono">{detail.arcid}</span></div>}
        <div className="kv"><span className="kv-k">Plan</span><span className="kv-v" style={{maxWidth:240,textAlign:'right',wordBreak:'break-word'}}>{detail.planName}</span></div>
        <div className="kv"><span className="kv-k">Reglas</span><span className="kv-v">{RULES_FULL[detail.rules] || detail.rules}</span></div>
        {detail.flightType && <div className="kv"><span className="kv-k">Tipo vuelo</span><span className="kv-v">{({S:'Regular',N:'No regular',G:'Aviacion general',M:'Militar',X:'Otros'})[detail.flightType] || detail.flightType}</span></div>}
        {detail.flightDate && <div className="kv"><span className="kv-k">Fecha</span><span className="kv-v mono">{detail.flightDate}</span></div>}

        {/* Aeronave */}
        <div className="caption" style={{fontSize:10,fontWeight:600,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--ink-dim)',margin:'14px 0 6px'}}>Aeronave</div>
        <div className="kv"><span className="kv-k">Tipo</span><span className="kv-v mono">{detail.aircraft}</span></div>
        {detail.wake && <div className="kv"><span className="kv-k">Estela</span><span className="kv-v">{detail.wake}</span></div>}
        {detail.reg && <div className="kv"><span className="kv-k">REG</span><span className="kv-v mono">{detail.reg}</span></div>}
        {detail.comEquipment && <div className="kv"><span className="kv-k">Equipo COM</span><span className="kv-v mono">{detail.comEquipment}</span></div>}
        {detail.ssr && <div className="kv"><span className="kv-k">SSR</span><span className="kv-v mono">{detail.ssr}</span></div>}

        {/* Ruta */}
        <div className="caption" style={{fontSize:10,fontWeight:600,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--ink-dim)',margin:'14px 0 6px'}}>Ruta</div>
        {detail.eobt && <div className="kv"><span className="kv-k">EOBT</span><span className="kv-v mono">{detail.eobt}Z</span></div>}
        {detail.speed && <div className="kv"><span className="kv-k">Velocidad</span><span className="kv-v mono">{detail.speed}</span></div>}
        <div className="kv"><span className="kv-k">Nivel</span><span className="kv-v mono">{detail.fl}</span></div>
        <div className="kv"><span className="kv-k">Ruta</span><span className="kv-v mono" style={{maxWidth:240,textAlign:'right',wordBreak:'break-word'}}>{detail.route}</span></div>
        <div className="kv"><span className="kv-k">EET</span><span className="kv-v mono">{detail.dur}</span></div>
        {detail.altn && <div className="kv"><span className="kv-k">ALTN</span><span className="kv-v mono">{detail.altn}</span></div>}
        {detail.altn2 && <div className="kv"><span className="kv-k">ALTN2</span><span className="kv-v mono">{detail.altn2}</span></div>}

        {/* Suplementario */}
        {(detail.endurance || detail.pob || detail.pic || detail.colors || detail.emergencyRadio || detail.survivalEquipment || detail.lifeJackets) && <>
          <div className="caption" style={{fontSize:10,fontWeight:600,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--ink-dim)',margin:'14px 0 6px'}}>Suplementario</div>
          {detail.endurance && <div className="kv"><span className="kv-k">Autonomia</span><span className="kv-v mono">{detail.endurance}</span></div>}
          {detail.pob && <div className="kv"><span className="kv-k">POB</span><span className="kv-v mono">{detail.pob}</span></div>}
          {detail.pic && <div className="kv"><span className="kv-k">PIC</span><span className="kv-v">{detail.pic}</span></div>}
          {detail.colors && <div className="kv"><span className="kv-k">Color/Marcas</span><span className="kv-v">{detail.colors}</span></div>}
          {detail.emergencyRadio && <div className="kv"><span className="kv-k">Radio emergencia</span><span className="kv-v">{detail.emergencyRadio}</span></div>}
          {detail.survivalEquipment && <div className="kv"><span className="kv-k">Equipo supervivencia</span><span className="kv-v">{detail.survivalEquipment}</span></div>}
          {detail.lifeJackets && <div className="kv"><span className="kv-k">Chalecos</span><span className="kv-v">{detail.lifeJackets}</span></div>}
        </>}

        {/* Observaciones */}
        {(detail.rmk || detail.opr) && <>
          <div className="caption" style={{fontSize:10,fontWeight:600,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--ink-dim)',margin:'14px 0 6px'}}>Observaciones</div>
          {detail.rmk && <div className="kv"><span className="kv-k">RMK</span><span className="kv-v" style={{maxWidth:240,textAlign:'right',wordBreak:'break-word'}}>{detail.rmk}</span></div>}
          {detail.opr && <div className="kv"><span className="kv-k">OPR</span><span className="kv-v">{detail.opr}</span></div>}
        </>}
      </div>
      <div style={{display:'flex',gap:8}}>
        <button className="btn btn-ghost" onClick={()=>setDetail(null)} style={{flex:1}}>{t('hist.close')}</button>
        <button className="btn btn-primary" onClick={()=>{
          if (!detail.planId || !plans.find(x => x.id == detail.planId)) { toast(t('hist.plan_deleted')); return; }
          setDetail(null);go('send-flow',{id:detail.planId});
        }} style={{flex:1}}><Icon name="refresh" size={14}/> {t('hist.resend')}</button>
      </div>
    </div></div>}
  </div>;
};
window.History = History;
