const t = window.t || (k => k);
const Dashboard = () => {
  const {plans, setPlans, go, user, toast, history, confirm} = useApp();
  const [q, setQ] = useState('');

  // Compatibilidad: planes API usan adep/ades/flight_rules/level/eet_total, seed usa from/to/rules/fl/dur
  const pFrom = (p) => p.adep || p.from || '';
  const pTo = (p) => p.ades || p.to || '';
  const pRules = (p) => p.flight_rules || p.rules || '';
  const pLevel = (p) => p.level || p.fl || '';
  const pEet = (p) => {
    if (p.eet_total) return p.eet_total;
    if (p.dur) return (p.dur.h || '00') + ':' + (p.dur.m || '00');
    return '';
  };
  const pDate = (p) => {
    if (p.updated_at) return new Date(p.updated_at * 1000);
    if (p.lastUsed) return new Date(p.lastUsed);
    return new Date();
  };

  const filtered = plans.filter(p => !q || (p.name||'').toLowerCase().includes(q.toLowerCase()) || pFrom(p).includes(q.toUpperCase()) || pTo(p).includes(q.toUpperCase()));
  const sorted = [...filtered].sort((a,b) => (b.favorite?1:0)-(a.favorite?1:0) || pDate(b)-pDate(a));

  const toggleFav = async (id) => {
    const plan = plans.find(x => x.id === id);
    if (!plan) return;
    const newFav = !plan.favorite;
    setPlans(p => p.map(x => x.id === id ? {...x, favorite: newFav ? 1 : 0} : x));
    try { await api.favoritePlan(id, newFav); } catch(e) {}
  };

  const duplicate = async (p) => {
    try {
      const res = await api.duplicatePlan(p.id);
      if (res && res.id) {
        const np = {...p, id: res.id, name: (p.name||'Plan') + ' (copia)', favorite: 0};
        setPlans(x => [np, ...x]);
        toast(t('dash.plan_duplicated'));
      }
    } catch(e) {
      // Fallback local
      const np = {...p, id: 'pl_' + Math.random().toString(36).slice(2,8), name: (p.name||'Plan') + ' (copia)', favorite: false};
      setPlans(x => [np, ...x]);
      toast(t('dash.plan_duplicated'));
    }
  };

  const remove = async (id) => {
    const plan = plans.find(x => x.id === id);
    const ok = await confirm(t('dash.delete_confirm'), {title: plan?.name || t('dash.delete_plan'), yes: t('dash.delete'), no: t('dash.cancel')});
    if (!ok) return;
    setPlans(p => p.filter(x => x.id !== id));
    try { await api.deletePlan(id); } catch(e) {}
    toast(t('dash.plan_deleted'));
  };

  const monthSent = history.filter(h => h.status === 'ok' && new Date(h.when).getMonth() === new Date().getMonth()).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 className="chip chip-accent eyebrow"><Icon name="user" size={12}/> {t('dash.hello')}, {(user.name||'').split(' ')[0]}</div>
        <h1 className="display">
          <span className="word-rise" style={{animationDelay:'0s'}}>{t('dash.your_plans')}</span>{' '}
          <span className="word-rise underline-swash" style={{animationDelay:'.08s'}}>{t('dash.plans_word')}</span>
        </h1>
        <p className="sub" style={{marginTop:14}}>
          <strong style={{color:'var(--ink)',fontWeight:600}}>{plans.length}{user.plan==='free'?'/3':''}</strong> {t('dash.templates')} · <strong style={{color:'var(--ink)',fontWeight:600}}>{monthSent}{user.plan==='free'?'/3':''}</strong> {t('dash.sends_month')}
        </p>
      </div>
    </section>

    <div style={{display:'flex',gap:10,marginBottom:22,flexWrap:'wrap'}}>
      <div style={{position:'relative',flex:1,minWidth:240}}>
        <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('dash.search')} style={{paddingLeft:40}}/>
      </div>
      <button className="btn btn-primary" onClick={()=>{
        if (user.plan === 'free' && plans.length >= 3) {
          toast(t('dash.plan_limit') || 'Has alcanzado el limite de 3 planes. Actualiza a Premium.');
          go('profile');
          return;
        }
        go('plan-editor',{id:null});
      }}><Icon name="plus" size={16}/> {t('dash.new_plan')}</button>
    </div>

    <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(320px,1fr))',gap:14}}>
      {sorted.map((p,i)=>(
        <div key={p.id} className={`plan-card card-hover slide-up ${p.favorite?'fav':''}`} style={{animationDelay:`${i*.03}s`}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:16,gap:8}}>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:3}}>
                <h3 style={{fontSize:15,fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap',letterSpacing:'-.01em',margin:0}}>{p.name}</h3>
                {!history.some(h => h.planId == p.id && h.status === 'ok') && <span className="chip" style={{fontSize:9,padding:'2px 7px',background:'var(--bg-inset)',color:'var(--ink-dim)',border:'1px solid var(--stroke)'}}>{t('dash.draft')}</span>}
                {history.some(h => h.planId == p.id && h.status === 'ok') && <span className="chip" style={{fontSize:9,padding:'2px 7px',color:'var(--ok)'}}>{t('dash.sent')}</span>}
              </div>
              <div className="caption">{pDate(p).toLocaleDateString('es',{day:'2-digit',month:'short'})}</div>
            </div>
            <button onClick={()=>toggleFav(p.id)} className="btn btn-icon btn-subtle" style={{color:p.favorite?'var(--accent)':'var(--ink-low)',background:p.favorite?'var(--accent-soft)':undefined,border:'none'}}>
              <Icon name="star" size={15} stroke={1.8} style={{fill:p.favorite?'var(--accent)':'none'}}/>
            </button>
          </div>

          <div className="route-display" style={{marginBottom:16}}>
            <div><div className="icao">{pFrom(p)}</div><div className="caption" style={{fontSize:10.5,marginTop:2}}>{AIRPORTS[pFrom(p)]||''}</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">{pTo(p)}</div><div className="caption" style={{fontSize:10.5,marginTop:2}}>{AIRPORTS[pTo(p)]||''}</div></div>
          </div>

          <div style={{display:'flex',gap:6,marginBottom:10,flexWrap:'wrap'}}>
            <span className="chip">{RULES_FULL[pRules(p)] || pRules(p)}</span>
            <span className="chip">{pLevel(p)}</span>
            <span className="chip">{pEet(p)}</span>
            {(p.aircraft_type||p.aircraft) && <span className="chip mono">{p.aircraft_type||p.aircraft}</span>}
          </div>
          <div style={{display:'flex',gap:8,marginBottom:16,flexWrap:'wrap',fontSize:11,color:'var(--ink-dim)'}}>
            {(p.arcid||p.reg) && <span className="mono">{p.arcid||p.reg}</span>}
            {p.speed && <span className="mono">{p.speed}</span>}
            {p.eobt && <span className="mono">EOBT {p.eobt}Z</span>}
            {p.flight_date && <span className="mono">{p.flight_date}</span>}
          </div>

          <div style={{display:'flex',gap:6}}>
            <button className="btn btn-accent btn-sm" style={{flex:1}} onClick={()=>go('send-flow',{id:p.id})}><Icon name="send" size={13}/> {t('dash.send')}</button>
            <button className="btn btn-subtle btn-icon" onClick={()=>go('plan-editor',{id:p.id})} title="Editar"><Icon name="edit" size={15}/></button>
            <button className="btn btn-subtle btn-icon" onClick={()=>duplicate(p)} title="Duplicar"><Icon name="copy" size={15}/></button>
            <button className="btn btn-subtle btn-icon" onClick={()=>remove(p.id)} title="Borrar"><Icon name="trash" size={15}/></button>
          </div>
        </div>
      ))}
      {sorted.length===0 && <div className="card" style={{padding:40,textAlign:'center',color:'var(--ink-dim)',gridColumn:'1/-1'}}>{t('dash.no_results')}</div>}
    </div>
  </div>;
};
window.Dashboard = Dashboard;
