const IfrTable = () => {
  const {go, setPlans, toast, user} = useApp();
  const [q, setQ] = useState('');
  const [rules, setRules] = useState('all');
  const [expanded, setExpanded] = useState(null);
  const filtered = IFR_ROUTES.filter(r => { if (rules!=='all' && r.rules!==rules) return false; if (!q) return true; const s=q.toUpperCase(); return r.from.includes(s)||r.to.includes(s)||r.route.toUpperCase().includes(s); });
  const RULES_SHORT = {Z:'Z',Y:'Y',I:'IFR',V:'VFR'};
  const RULES_COLOR = {Z:'#C15F3C',Y:'#8B3A62',I:'#4A7C59',V:'#3E6FA8'};
  const createFromRoute = async (r) => {
    const plan = {
      name: r.from + ' - ' + r.to,
      message_type: 'FPL',
      arcid: 'ECOBE',
      flight_rules: r.rules || 'I',
      flight_type: 'S',
      aircraft_count: 1,
      aircraft_type: 'C172',
      wake: 'L',
      com_equipment: 'SGY',
      ssr: 'C',
      adep: r.from,
      ades: r.to,
      flight_date: '',
      eobt: '08:00',
      speed: 'N0110',
      level: r.fl || 'F100',
      route: r.route || 'DCT',
      eet_total: r.dur || '01:30',
      altn: 'LEVC',
      altn2: 'LEMT',
      reg: 'ECOBE',
      opr: 'EUROPEANFLYER',
      rmk: 'VUELO DE ESCUELA',
      endurance: '05:00',
      persons_on_board: 2,
      pic_name: user?.name || '',
      colors: 'BLANCA',
      emergency_radio: 'E',
      life_jacket_type: 'F',
    };
    try {
      const res = await api.createPlan(plan);
      if (res && res.id) plan.id = res.id;
    } catch(e) {
      plan.id = 'pl_' + Math.random().toString(36).slice(2,8);
    }
    setPlans(p => [plan, ...p]);
    toast('Plan creado desde ruta');
    // Small delay so React processes setPlans before PlanEditor mounts
    setTimeout(() => go('plan-editor', {id: plan.id}), 50);
  };
  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 className="chip chip-accent eyebrow"><Icon name="map" size={12}/> European Flyers · Tablas publicadas</div>
        <h1 className="display">
          <span className="word-rise" style={{animationDelay:'0s'}}>Rutas</span>{' '}
          <span className="word-rise underline-swash" style={{animationDelay:'.08s'}}>IFR</span>
        </h1>
        <p className="sub" style={{marginTop:14}}>{filtered.length} de {IFR_ROUTES.length} rutas · elige origen y destino y rellenamos el resto.</p>
      </div>
    </section>

    <div style={{display:'flex',gap:10,marginBottom:14,flexWrap:'wrap'}}>
      <div style={{position:'relative',flex:1,minWidth:200}}>
        <Icon name="search" size={15} style={{position:'absolute',left:12,top:'50%',transform:'translateY(-50%)',color:'var(--ink-low)'}}/>
        <input className="field" value={q} onChange={e=>setQ(e.target.value)} placeholder="ICAO o waypoint…" style={{paddingLeft:36,height:38}}/>
      </div>
      <div style={{display:'flex',gap:4,flexShrink:0}}>
        {[{v:'all',l:'Todas'},{v:'Z',l:'Z'},{v:'Y',l:'Y'},{v:'I',l:'IFR'},{v:'V',l:'VFR'}].map(f=>
          <button key={f.v} className={`pill ${rules===f.v?'active':''}`} style={{padding:'6px 12px',fontSize:12}} onClick={()=>setRules(f.v)}>{f.l}</button>
        )}
      </div>
    </div>

    <div className="ifr-table">
      <div className="ifr-head">
        <div>ADEP</div>
        <div></div>
        <div>ADES</div>
        <div style={{textAlign:'center'}}>Tipo</div>
        <div style={{textAlign:'right'}}>FL</div>
        <div style={{textAlign:'right'}}>ETE</div>
        <div></div>
      </div>
      {filtered.map((r,i)=>{
        const isOpen = expanded===i;
        return <React.Fragment key={i}>
          <div className={`ifr-compact ${isOpen?'open':''}`} onClick={()=>setExpanded(isOpen?null:i)}>
            <div className="icao-sm">{r.from}</div>
            <Icon name="arrow_right" size={13} style={{color:'var(--ink-low)'}}/>
            <div className="icao-sm">{r.to}</div>
            <div style={{textAlign:'center'}}><span className="rule-dot" style={{background:RULES_COLOR[r.rules]}}/><span className="mono" style={{fontSize:11,fontWeight:600,color:RULES_COLOR[r.rules]}}>{RULES_SHORT[r.rules]}</span></div>
            <div className="mono" style={{textAlign:'right',fontSize:11,color:'var(--ink-dim)'}}>{r.fl||'—'}</div>
            <div className="mono" style={{textAlign:'right',fontSize:11,color:'var(--ink-dim)'}}>{r.dur||'—'}</div>
            <Icon name="chev_right" size={13} style={{color:'var(--ink-low)',transition:'transform .2s',transform:isOpen?'rotate(90deg)':'none'}}/>
          </div>
          {isOpen && <div className="ifr-detail">
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:14,flexWrap:'wrap',marginBottom:12}}>
              <div style={{flex:1,minWidth:200}}>
                <div className="caption" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'.1em',marginBottom:4}}>Ruta</div>
                <div className="mono" style={{fontSize:12.5,wordBreak:'break-word',lineHeight:1.5,color:'var(--ink-2)'}}>{r.route}</div>
              </div>
              <div style={{display:'flex',gap:14}}>
                <div><div className="caption" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'.1em'}}>Origen</div><div style={{fontSize:12.5}}>{AIRPORTS[r.from]||r.from}</div></div>
                <div><div className="caption" style={{fontSize:10,textTransform:'uppercase',letterSpacing:'.1em'}}>Destino</div><div style={{fontSize:12.5}}>{AIRPORTS[r.to]||r.to}</div></div>
              </div>
            </div>
            {r.notes && <div className="ifr-note"><Icon name="info" size={12}/> {r.notes}</div>}
            <button className="btn btn-accent btn-sm" onClick={e=>{e.stopPropagation();createFromRoute(r)}} style={{marginTop:4}}><Icon name="plus" size={13}/> Crear plan con esta ruta</button>
          </div>}
        </React.Fragment>;
      })}
      {filtered.length===0 && <div style={{padding:40,textAlign:'center',color:'var(--ink-dim)',fontSize:13}}>Sin resultados</div>}
    </div>
  </div>;
};
window.IfrTable = IfrTable;
