const t = window.t || (k => k);
const SendFlow = () => {
  const {plans, setHistory, go, route, user, toast, history} = useApp();
  const p = plans.find(x => x.id === route.params?.id);
  const [stage, setStage] = useState('credentials');
  const [progress, setProgress] = useState(0);
  const [result, setResult] = useState(null);
  const [icaroUser, setIcaroUser] = useState('');
  const [icaroPass, setIcaroPass] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');
  const [showPass, setShowPass] = useState(false);

  const doSubmit = async () => {
    if (!icaroUser.trim() || !icaroPass.trim()) {
      setErrorMsg(t('send.fill_creds'));
      return;
    }
    const numId = parseInt(p.id, 10);
    if (isNaN(numId) || numId <= 0) {
      setErrorMsg(t('send.not_saved'));
      return;
    }
    setErrorMsg('');
    setStage('sending');
    setProgress(0);
    setSubmitting(true);

    // Progress animation
    let tick = 0;
    const iv = setInterval(() => { tick += 2; setProgress(Math.min(tick, 95)); }, 100);

    try {
      const res = await api.submitFpl(p.id, icaroUser.trim().toUpperCase(), icaroPass.trim().toUpperCase());
      clearInterval(iv);
      setProgress(100);
      setTimeout(() => {
        setResult({ok: true, ref: res.ref, raw: res.raw});
        setStage('done');
        setSubmitting(false);
        setHistory(prev => [{
          id: 'sub_' + (res.submission_id || Date.now()),
          planId: p.id,
          planName: p.name || (p.adep + ' - ' + p.ades),
          from: p.adep, to: p.ades,
          when: new Date().toISOString(),
          status: 'ok', fpId: res.ref,
          error: null, durationMs: 0,
          // Identificacion
          arcid: p.arcid || '',
          rules: p.flight_rules || '', flightType: p.flight_type || '',
          flightDate: p.flight_date || '',
          // Aeronave
          aircraft: p.aircraft_type || '', wake: p.wake || '',
          reg: p.reg || '', comEquipment: p.com_equipment || '',
          ssr: p.ssr || '',
          // Ruta
          eobt: p.eobt || '', speed: p.speed || '',
          fl: p.level || '', route: p.route || '',
          dur: p.eet_total || '', durMin: 0,
          altn: p.altn || '', altn2: p.altn2 || '',
          // Suplementario
          endurance: p.endurance || '',
          pob: String(p.persons_on_board||''),
          pic: p.pic_name || '', colors: p.colors || '',
          emergencyRadio: p.emergency_radio || '',
          survivalEquipment: p.survival_equipment || '',
          lifeJackets: p.life_jacket_type || '',
          // Observaciones
          rmk: p.rmk || '', opr: p.opr || '',
        }, ...prev]);
      }, 400);
    } catch (e) {
      clearInterval(iv);
      setProgress(0);
      console.error('=== ENAIRE SUBMIT ERROR ===', JSON.stringify(e, null, 2));
      const errMap = {trial_date_limit: t('send.trial_date_limit') || 'En periodo de prueba solo puedes programar vuelos en los próximos 7 días.', free_limit_reached: t('send.free_limit') || 'Has alcanzado el límite de envíos gratuitos.'};
      setResult({ok: false, err: errMap[e.error] || e.error || 'Error desconocido', detail: e.detail, debug: e.debug, raw: e.raw});
      setStage('error');
      setSubmitting(false);
    }
  };

  if (!p) return <div className="page"><button className="btn btn-ghost" onClick={() => go('dashboard')}>{t('send.back')}</button></div>;

  // Stage: CREDENTIALS — pedir usuario y contrasena ENAIRE
  if (stage === 'credentials') return <div className="page fade-in">
    <header style={{display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24}}>
      <button className="btn btn-ghost btn-icon" onClick={() => go('dashboard')}><Icon name="chev_left" size={16}/></button>
      <h1 className="display" style={{fontSize: 'clamp(20px,5vw,28px)'}}>{t('send.title')}</h1>
    </header>

    {/* Route header — full width */}
    <div className="card" style={{padding: 26, marginBottom: 18}}>
      <div className="route-display" style={{marginBottom: 0}}>
        <div><div className="icao" style={{fontSize: 28}}>{p.adep || p.from}</div><div className="caption" style={{fontSize: 11, marginTop: 2}}>{AIRPORTS[p.adep || p.from] || ''}</div></div>
        <div className="airport-arrow"><div className="line"/><Icon name="plane" size={16}/><div className="line"/></div>
        <div style={{textAlign: 'right'}}><div className="icao" style={{fontSize: 28}}>{p.ades || p.to}</div><div className="caption" style={{fontSize: 11, marginTop: 2}}>{AIRPORTS[p.ades || p.to] || ''}</div></div>
      </div>
      <div style={{display:'flex',gap:8,marginTop:14,flexWrap:'wrap',justifyContent:'center'}}>
        <span className="chip chip-accent">{RULES_FULL[p.flight_rules || p.rules] || p.flight_rules || '—'}</span>
        {(p.level || p.fl) && <span className="chip">{p.level || p.fl}</span>}
        {(p.aircraft_type || p.aircraft) && <span className="chip mono">{p.aircraft_type || p.aircraft}</span>}
        {(p.eet_total) && <span className="chip">{p.eet_total}</span>}
        {(p.flight_date) && <span className="chip mono">{p.flight_date}</span>}
      </div>
    </div>

    {/* Grid de secciones — 2 col desktop, 1 col movil */}
    <div className="send-grid">

      {/* Identificacion */}
      <div className="card" style={{padding: 20}}>
        <div className="caption" style={{fontSize: 10, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-dim)', marginBottom: 10}}>{t('sec.identification')}</div>
        {(p.arcid) && <div className="kv"><span className="kv-k">{t('field.arcid')}</span><span className="kv-v mono">{p.arcid}</span></div>}
        <div className="kv"><span className="kv-k">{t('field.rules')}</span><span className="kv-v">{RULES_FULL[p.flight_rules || p.rules] || p.flight_rules || p.rules || '—'}</span></div>
        {(p.flight_type) && <div className="kv"><span className="kv-k">{t('field.flight_type')}</span><span className="kv-v">{({S:t('ftype.S'),N:t('ftype.N'),G:t('ftype.G'),M:t('ftype.M'),X:t('ftype.X')})[p.flight_type] || p.flight_type}</span></div>}
        {(p.flight_date) && <div className="kv"><span className="kv-k">{t('field.date')}</span><span className="kv-v mono">{p.flight_date}</span></div>}
      </div>

      {/* Aeronave */}
      <div className="card" style={{padding: 20}}>
        <div className="caption" style={{fontSize: 10, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-dim)', marginBottom: 10}}>{t('sec.aircraft')}</div>
        {(p.aircraft_type || p.aircraft) && <div className="kv"><span className="kv-k">{t('field.type')}</span><span className="kv-v mono">{p.aircraft_type || p.aircraft}</span></div>}
        {(p.wake) && <div className="kv"><span className="kv-k">{t('field.wake')}</span><span className="kv-v">{p.wake}</span></div>}
        {(p.reg) && <div className="kv"><span className="kv-k">{t('field.reg')}</span><span className="kv-v mono">{p.reg}</span></div>}
        {(p.com_equipment) && <div className="kv"><span className="kv-k">{t('field.com_equipment')}</span><span className="kv-v mono">{p.com_equipment}</span></div>}
        {(p.ssr) && <div className="kv"><span className="kv-k">{t('field.ssr')}</span><span className="kv-v mono">{p.ssr}</span></div>}
      </div>

      {/* Ruta */}
      <div className="card" style={{padding: 20}}>
        <div className="caption" style={{fontSize: 10, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-dim)', marginBottom: 10}}>{t('sec.route')}</div>
        <div className="kv"><span className="kv-k">{t('field.eobt')}</span><span className="kv-v mono">{p.eobt || (p.obt ? p.obt.h + ':' + p.obt.m : '—')}Z</span></div>
        {(p.speed) && <div className="kv"><span className="kv-k">{t('field.speed')}</span><span className="kv-v mono">{p.speed}</span></div>}
        {(p.level || p.fl) && <div className="kv"><span className="kv-k">{t('field.level')}</span><span className="kv-v mono">{p.level || p.fl}</span></div>}
        <div className="kv"><span className="kv-k">{t('field.route')}</span><span className="kv-v mono" style={{textAlign: 'right', wordBreak: 'break-word'}}>{p.route || 'DCT'}</span></div>
        <div className="kv"><span className="kv-k">{t('field.eet')}</span><span className="kv-v mono">{p.eet_total || (p.dur ? p.dur.h + ':' + p.dur.m : '—')}</span></div>
        {(p.altn) && <div className="kv"><span className="kv-k">{t('field.altn')}</span><span className="kv-v mono">{p.altn}</span></div>}
        {(p.altn2) && <div className="kv"><span className="kv-k">{t('field.altn2')}</span><span className="kv-v mono">{p.altn2}</span></div>}
      </div>

      {/* Suplementario */}
      {(p.endurance || p.persons_on_board || p.pic_name || p.colors || p.emergency_radio || p.survival_equipment) &&
      <div className="card" style={{padding: 20}}>
        <div className="caption" style={{fontSize: 10, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-dim)', marginBottom: 10}}>{t('sec.supplementary')}</div>
        {(p.endurance) && <div className="kv"><span className="kv-k">{t('field.endurance')}</span><span className="kv-v mono">{p.endurance}</span></div>}
        {(p.persons_on_board) && <div className="kv"><span className="kv-k">{t('field.pob')}</span><span className="kv-v mono">{p.persons_on_board}</span></div>}
        {(p.pic_name) && <div className="kv"><span className="kv-k">{t('field.pic')}</span><span className="kv-v">{p.pic_name}</span></div>}
        {(p.colors) && <div className="kv"><span className="kv-k">{t('field.colors')}</span><span className="kv-v">{p.colors}</span></div>}
        {(p.emergency_radio) && <div className="kv"><span className="kv-k">{t('field.emergency_radio')}</span><span className="kv-v">{p.emergency_radio}</span></div>}
        {(p.survival_equipment) && <div className="kv"><span className="kv-k">{t('field.survival')}</span><span className="kv-v">{p.survival_equipment}</span></div>}
        {(p.life_jacket_type) && <div className="kv"><span className="kv-k">{t('field.jackets')}</span><span className="kv-v">{p.life_jacket_type}</span></div>}
        {(p.dinghies_number) && <div className="kv"><span className="kv-k">Balsas</span><span className="kv-v">{p.dinghies_number}{p.dinghies_capacity ? ' x'+p.dinghies_capacity : ''}{p.dinghies_covered ? ' (cubierta)' : ''}{p.dinghies_color ? ' '+p.dinghies_color : ''}</span></div>}
      </div>}

      {/* Observaciones */}
      {(p.rmk || p.opr || p.sts) &&
      <div className="card" style={{padding: 20}}>
        <div className="caption" style={{fontSize: 10, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-dim)', marginBottom: 10}}>{t('sec.remarks')}</div>
        {(p.rmk) && <div className="kv"><span className="kv-k">{t('field.rmk')}</span><span className="kv-v" style={{textAlign: 'right', wordBreak: 'break-word'}}>{p.rmk}</span></div>}
        {(p.opr) && <div className="kv"><span className="kv-k">{t('field.opr')}</span><span className="kv-v">{p.opr}</span></div>}
        {(p.sts) && <div className="kv"><span className="kv-k">{t('field.sts')}</span><span className="kv-v">{p.sts}</span></div>}
      </div>}

    </div>

    {/* Credenciales ENAIRE */}
    <div className="card" style={{padding: 'clamp(18px,4vw,26px)', marginBottom: 18, borderColor: 'color-mix(in srgb, var(--accent) 40%, var(--stroke))', background: 'color-mix(in srgb, var(--accent-soft) 30%, var(--panel))'}}>
      <div style={{display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16}}>
        <div style={{width: 36, height: 36, borderRadius: 10, background: 'var(--accent-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0}}>
          <Icon name="shield" size={18} style={{color: 'var(--accent)'}}/>
        </div>
        <div>
          <h3 style={{fontSize: 14, fontWeight: 600, letterSpacing: '-.01em'}}>{t('send.creds_title')}</h3>
          <div className="caption" style={{fontSize: 11}}>{t('send.creds_subtitle')}</div>
        </div>
      </div>
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 12}}>
        <div>
          <label className="label">{t('send.user_enaire')}</label>
          <input className="field mono" value={icaroUser} onChange={e => setIcaroUser(e.target.value.toUpperCase())} placeholder="Ej: EFLEMU" autoComplete="off"/>
        </div>
        <div>
          <label className="label">{t('send.pass_enaire')}</label>
          <div style={{position: 'relative'}}>
            <input className="field" type={showPass ? 'text' : 'password'} value={icaroPass} onChange={e => setIcaroPass(e.target.value)} placeholder="Tu contraseña de Ícaro" autoComplete="off" style={{paddingRight: 42}}/>
            <button type="button" onClick={() => setShowPass(!showPass)} style={{position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', padding: 4, color: 'var(--ink-low)', background: 'none', border: 'none', cursor: 'pointer'}} title={showPass ? t('send.hide_pass') : t('send.show_pass')}>
              <Icon name={showPass ? 'eye_off' : 'eye'} size={16}/>
            </button>
          </div>
        </div>
      </div>
      {errorMsg && <div style={{marginTop: 12, padding: '10px 14px', background: 'rgba(181,72,63,.1)', borderRadius: 8, color: 'var(--err)', fontSize: 13}}>{errorMsg}</div>}
    </div>

    <button className="send-btn" onClick={doSubmit} disabled={submitting}>
      <Icon name="send" size={16}/> {t('send.submit')}
    </button>
  </div>;

  // Stage: SENDING
  if (stage === 'sending') return <div className="page" style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '70vh'}}>
    <div className="spinner" style={{width: 48, height: 48, borderWidth: 3, marginBottom: 24}}/>
    <h2 className="display" style={{fontSize: 28, marginBottom: 6}}>{t('send.sending')}</h2>
    <p className="caption" style={{marginBottom: 24}}>{p.adep || p.from} -> {p.ades || p.to} · {RULES_FULL[p.flight_rules || p.rules] || ''}</p>
    <div className="prog" style={{width: 240, marginBottom: 8}}><div style={{width: progress + '%'}}/></div>
    <div className="caption mono">{progress}%</div>
  </div>;

  // Stage: DONE
  if (stage === 'done') {
    const isFree = user.plan === 'free';
    const monthSent = history.filter(h => h.status === 'ok' && new Date(h.when).getMonth() === new Date().getMonth()).length;
    return <div className="page" style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '70vh', textAlign: 'center'}}>
    <div className="check-circle"><Icon name="check" size={32} stroke={2.5}/></div>
    <h1 className="display" style={{fontSize: 36, marginTop: 22, marginBottom: 8}}>{t('send.accepted')}</h1>
    <p style={{color: 'var(--ink-dim)', marginBottom: 24}}>{t('send.confirmed')}</p>
    <div className="card" style={{padding: 18, marginBottom: 16, minWidth: 240}}>
      <div className="caption" style={{marginBottom: 4}}>{t('send.ref')}</div>
      <div className="mono" style={{fontSize: 22, fontWeight: 600, letterSpacing: '.04em'}}>{result.ref || '—'}</div>
    </div>
    {/* Usage counter */}
    <div style={{marginBottom:24,padding:'10px 20px',borderRadius:10,background: isFree ? 'color-mix(in srgb, var(--warn) 10%, var(--panel))' : 'var(--bg-inset)',border:'1px solid var(--stroke)',display:'flex',alignItems:'center',gap:10}}>
      {isFree ? <>
        <span style={{fontWeight:700,fontSize:16,color: monthSent >= 3 ? 'var(--err)' : 'var(--warn)'}}>{monthSent}/3</span>
        <span className="caption">{t('send.monthly_sends') || 'envíos este mes'}</span>
        {monthSent >= 3 && <span className="chip" style={{background:'var(--err)',color:'#fff',fontSize:9}}>Límite</span>}
      </> : <>
        <span style={{fontWeight:700,fontSize:16,color:'var(--accent)'}}>{monthSent}</span>
        <span className="caption">{t('send.monthly_sends') || 'envíos este mes'} · <span style={{color:'var(--ok)'}}>∞ ilimitados</span></span>
      </>}
    </div>
    <div style={{display: 'flex', gap: 10}}>
      <button className="btn btn-ghost" onClick={() => go('history')}>{t('send.history')}</button>
      <button className="btn btn-primary" onClick={() => go('dashboard')}>{t('send.done')}</button>
    </div>
  </div>;
  }

  // Stage: ERROR
  return <div className="page" style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '70vh', textAlign: 'center'}}>
    <div style={{width: 56, height: 56, borderRadius: '50%', background: 'transparent', border: '1px solid var(--err)', color: 'var(--err)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 22}}><Icon name="x" size={28} stroke={2}/></div>
    <h1 className="display" style={{fontSize: 32, marginBottom: 8}}>{t('send.failed')}</h1>
    <p style={{color: 'var(--ink-dim)', marginBottom: 12, maxWidth: 420}}>{result?.err}</p>
    {result?.detail && <p className="mono caption" style={{marginBottom: 12, maxWidth: 500, wordBreak: 'break-word'}}>{result.detail}</p>}
    {result?.debug && <details style={{marginBottom: 20, maxWidth: 500, textAlign: 'left'}}><summary className="caption" style={{cursor: 'pointer'}}>Debug</summary><pre className="mono" style={{fontSize: 11, marginTop: 8, padding: 12, background: 'var(--bg-inset)', borderRadius: 8, overflow: 'auto', maxHeight: 200}}>{result.debug}</pre></details>}
    <div style={{display: 'flex', gap: 10}}>
      <button className="btn btn-ghost" onClick={() => go('dashboard')}>{t('send.back')}</button>
      <button className="btn btn-primary" onClick={() => { setStage('credentials'); setProgress(0); setResult(null); }}>
        <Icon name="refresh" size={14}/> {t('send.retry')}
      </button>
    </div>
  </div>;
};
window.SendFlow = SendFlow;
