const Profile = () => {
  const {user, setUser, logout, toast, go, tweaks, setTweaks} = useApp();
  const t = window.t || (k => k);
  const [editProfile, setEditProfile] = useState(false);
  const [editPass, setEditPass] = useState(false);
  const [prof, setProf] = useState({name: user.name || '', license: user.license || '', phone: user.phone || ''});
  const [pw, setPw] = useState({current: '', new1: '', new2: ''});
  const [busy, setBusy] = useState(false);
  const [tickets, setTickets] = useState([]);
  const [ticketMsg, setTicketMsg] = useState('');
  const [loadingTickets, setLoadingTickets] = useState(false);
  const [expandedTk, setExpandedTk] = useState({});

  // Refresh user data + load tickets on mount
  useEffect(() => {
    api.me().then(r => {
      if (r && r.user) {
        setUser(u => ({...u, ...r.user}));
        try { localStorage.setItem('ap_user', JSON.stringify({...user, ...r.user})); } catch(e){}
      }
    }).catch(() => {});
    api.supportMine().then(d => setTickets(d.tickets || [])).catch(() => {});
  }, []);

  // Stripe redirect handling
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const stripe = params.get('stripe');
    if (stripe === 'success') {
      toast(t('prof.upgrade_ok') || 'Plan actualizado correctamente');
      // Refresh user data to get updated plan from backend
      api.me().then(r => {
        if (r && r.user) {
          setUser(u => ({...u, ...r.user}));
          try { localStorage.setItem('ap_user', JSON.stringify({...user, ...r.user})); } catch(e){}
        }
      }).catch(() => {});
    }
    if (stripe === 'cancel') { toast(t('prof.upgrade_cancel') || 'Pago cancelado'); }
    if (stripe) window.history.replaceState({}, '', window.location.pathname);
  }, []);

  const handleUpgrade = async () => {
    setBusy(true);
    try {
      const r = await api.stripeCheckout();
      if (r && r.url) window.location.href = r.url;
    } catch(e) { toast(t('common.error') + ': ' + (e.error || t('common.unknown'))); }
    setBusy(false);
  };

  const handleManageSub = async () => {
    setBusy(true);
    try {
      const r = await api.stripePortal();
      if (r && r.url) window.location.href = r.url;
    } catch(e) { toast(t('common.error') + ': ' + (e.error || t('common.unknown'))); }
    setBusy(false);
  };

  const saveProfile = async () => {
    if (!prof.name.trim()) { toast(t('prof.name_required')); return; }
    setBusy(true);
    try {
      const r = await api.updateProfile(prof);
      if (r && r.user) {
        setUser(u => ({...u, name: r.user.name, license: r.user.license, phone: r.user.phone}));
        try { const stored = JSON.parse(localStorage.getItem('ap_user')||'{}'); localStorage.setItem('ap_user', JSON.stringify({...stored, name: r.user.name, license: r.user.license, phone: r.user.phone})); } catch(e){}
      }
      setEditProfile(false);
      toast(t('prof.profile_updated'));
    } catch(e) { toast(t('common.error') + ': ' + (e.error || t('common.unknown'))); }
    setBusy(false);
  };

  const savePassword = async () => {
    if (!pw.current) { toast(t('prof.enter_current')); return; }
    if (pw.new1.length < 8) { toast(t('prof.pass_min8')); return; }
    if (pw.new1 !== pw.new2) { toast(t('prof.pass_mismatch')); return; }
    setBusy(true);
    try {
      await api.changePassword({current: pw.current, new: pw.new1});
      setEditPass(false);
      setPw({current: '', new1: '', new2: ''});
      toast(t('prof.pass_updated'));
    } catch(e) {
      toast(e.error === 'current_password_wrong' ? t('prof.pass_wrong') : t('common.error') + ': ' + (e.error || t('common.unknown')));
    }
    setBusy(false);
  };

  const sendTicket = async () => {
    if (!ticketMsg.trim()) { toast(t('prof.support_empty')); return; }
    setBusy(true);
    try {
      await api.supportSend(ticketMsg);
      setTicketMsg('');
      toast(t('prof.support_sent'));
      // Reload tickets
      api.supportMine().then(d => setTickets(d.tickets || [])).catch(() => {});
    } catch(e) { toast(t('common.error') + ': ' + (e.error || t('common.unknown'))); }
    setBusy(false);
  };

  const planLabel = user.is_trialing ? 'Premium (prueba 7 días)' : user.plan === 'premium' ? 'Premium' : user.plan === 'gifted' ? 'Premium (cortesía)' : user.plan === 'admin' ? 'Admin' : 'Free';
  const isPremium = user.plan === 'premium' || user.plan === 'gifted' || user.plan === 'admin';

  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('prof.your_account')}</div>
        <h1 className="display">
          <span className="word-rise" style={{animationDelay:'0s'}}>{t('prof.title')}</span>{' '}
          <span className="word-rise underline-swash" style={{animationDelay:'.08s'}}>{t('prof.title2')}</span>
        </h1>
        <p className="sub" style={{marginTop:14}}>{t('prof.subtitle')}</p>
      </div>
    </section>

    {/* Datos personales */}
    <div className="card" style={{padding:22,marginBottom:14}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
        <div style={{display:'flex',alignItems:'center',gap:14}}>
          <div style={{width:52,height:52,borderRadius:14,background:'var(--accent-soft)',color:'var(--accent)',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--serif)',fontSize:22,fontWeight:500,border:'1px solid var(--stroke)'}}>{(user.name||'?')[0]}</div>
          <div>
            <div style={{fontSize:17,fontWeight:600}}>{user.name}</div>
            <div className="caption">{user.email}</div>
            {user.license && <div className="caption">{user.license}</div>}
          </div>
        </div>
        {!editProfile && <button className="btn btn-ghost btn-sm" onClick={()=>setEditProfile(true)}><Icon name="edit" size={13}/> {t('prof.edit')}</button>}
      </div>
      {editProfile && <div style={{display:'grid',gap:12,marginTop:8}}>
        <div><label className="label">{t('prof.name')}</label><input className="field" value={prof.name} onChange={e=>setProf({...prof,name:e.target.value})}/></div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
          <div><label className="label">{t('prof.license')}</label>
            <Select value={prof.license} onChange={v=>setProf({...prof,license:v})} options={[
              {value:'PPL',label:'PPL'},{value:'CPL',label:'CPL'},{value:'ATPL',label:'ATPL'},{value:'LAPL',label:'LAPL'}
            ]}/>
          </div>
          <div><label className="label">{t('prof.phone')}</label><input className="field" value={prof.phone} onChange={e=>setProf({...prof,phone:e.target.value})} placeholder="+34..."/></div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-ghost" onClick={()=>setEditProfile(false)} style={{flex:1}}>{t('prof.cancel')}</button>
          <button className="btn btn-primary" onClick={saveProfile} disabled={busy} style={{flex:1}}>{t('prof.save')}</button>
        </div>
      </div>}
    </div>

    {/* Cambiar contrasena */}
    <div className="card" style={{padding:22,marginBottom:14}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
        <div style={{display:'flex',alignItems:'center',gap:8}}><Icon name="lock" size={15} style={{color:'var(--ink-dim)'}}/><h3 className="h3">{t('prof.password')}</h3></div>
        {!editPass && <button className="btn btn-ghost btn-sm" onClick={()=>setEditPass(true)}><Icon name="edit" size={13}/> {t('prof.change')}</button>}
      </div>
      {editPass && <div style={{display:'grid',gap:12,marginTop:14}}>
        <div><label className="label">{t('prof.current_pass')}</label><input type="password" className="field" value={pw.current} onChange={e=>setPw({...pw,current:e.target.value})}/></div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12}}>
          <div><label className="label">{t('prof.new_pass')}</label><input type="password" className="field" value={pw.new1} onChange={e=>setPw({...pw,new1:e.target.value})} placeholder="8+ caracteres"/></div>
          <div><label className="label">{t('prof.repeat_pass')}</label><input type="password" className="field" value={pw.new2} onChange={e=>setPw({...pw,new2:e.target.value})}/></div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-ghost" onClick={()=>{setEditPass(false);setPw({current:'',new1:'',new2:''});}} style={{flex:1}}>{t('prof.cancel')}</button>
          <button className="btn btn-primary" onClick={savePassword} disabled={busy} style={{flex:1}}>{t('prof.update')}</button>
        </div>
      </div>}
    </div>

    {/* Suscripcion */}
    <div className="card" style={{padding:22,marginBottom:14}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
        <h3 className="h3">{t('prof.subscription')}</h3>
        <span className={`chip ${isPremium?'chip-accent':''}`}>{planLabel}</span>
      </div>
      {isPremium ? <>
        <div style={{padding:16,borderRadius:12,background:'var(--bg-inset)',textAlign:'center',marginBottom:12}}>
          <div className="display" style={{fontSize:34,color:'var(--accent)'}}>{'\u221E'}</div>
          <div className="caption" style={{marginTop:4}}>{user.is_trialing ? 'Periodo de prueba — 7 días gratis' : t('prof.unlimited')}</div>
          <div style={{display:'flex',gap:12,justifyContent:'center',marginTop:10,flexWrap:'wrap'}}>
            <div style={{textAlign:'center'}}><div style={{fontSize:18,fontWeight:700,color:'var(--accent)'}}>∞</div><div className="caption" style={{fontSize:10}}>Planes</div></div>
            <div style={{textAlign:'center'}}><div style={{fontSize:18,fontWeight:700,color:'var(--accent)'}}>∞</div><div className="caption" style={{fontSize:10}}>Envíos</div></div>
            <div style={{textAlign:'center'}}><div style={{fontSize:18,fontWeight:700,color:'var(--ok)'}}>✓</div><div className="caption" style={{fontSize:10}}>Soporte</div></div>
          </div>
        </div>
        {user.plan === 'gifted' && <div className="caption" style={{textAlign:'center',marginBottom:8,color:'var(--accent)'}}>
          {user.plan_until ? `Cortesía hasta ${new Date(user.plan_until * 1000).toLocaleDateString('es',{day:'2-digit',month:'long',year:'numeric'})}` : 'Cortesía vitalicia ♾'}
        </div>}
        {user.plan === 'premium' && user.has_subscription && <div style={{textAlign:'center',marginBottom:12}}>
          <button className="btn btn-ghost btn-sm" onClick={handleManageSub} disabled={busy}><Icon name="edit" size={13}/> {t('prof.manage_sub') || 'Gestionar suscripción'}</button>
        </div>}
      </> : <>
        <div style={{padding:18,borderRadius:12,background:'var(--bg-inset)',textAlign:'center',marginBottom:12}}>
          <div style={{display:'flex',gap:16,justifyContent:'center',marginBottom:12}}>
            <div style={{textAlign:'center'}}><div style={{fontSize:18,fontWeight:700,color:'var(--ink-dim)'}}>3</div><div className="caption" style={{fontSize:10}}>Planes</div></div>
            <div style={{textAlign:'center'}}><div style={{fontSize:18,fontWeight:700,color:'var(--ink-dim)'}}>3</div><div className="caption" style={{fontSize:10}}>Envíos/mes</div></div>
            <div style={{textAlign:'center'}}><div style={{fontSize:18,fontWeight:700,color:'var(--err)'}}>✗</div><div className="caption" style={{fontSize:10}}>Soporte</div></div>
          </div>
        </div>
        <div style={{padding:18,borderRadius:12,background:'color-mix(in srgb, var(--accent-soft) 40%, var(--panel))',border:'1px solid color-mix(in srgb, var(--accent) 30%, var(--stroke))',textAlign:'center',marginBottom:12}}>
          <div style={{fontSize:15,fontWeight:600,marginBottom:6}}>{t('prof.go_premium')}</div>
          <div className="caption" style={{marginBottom:12}}>{t('prof.premium_desc')}</div>
          <button className="btn btn-primary" onClick={handleUpgrade} disabled={busy} style={{padding:'10px 28px'}}><Icon name="bolt" size={14}/> {t('prof.upgrade_btn')}</button>
        </div>
      </>}
      <div style={{display:'flex',justifyContent:'space-between',fontSize:13}}>
        <div><div className="caption">{t('prof.member_since')}</div><div>{user.created_at ? new Date(user.created_at*1000).toLocaleDateString('es',{day:'2-digit',month:'short',year:'numeric'}) : user.memberSince || '—'}</div></div>
        {isPremium && user.plan_until && <div style={{textAlign:'right'}}><div className="caption">{t('prof.renewal')}</div><div>{new Date(user.plan_until*1000).toLocaleDateString('es',{day:'2-digit',month:'short',year:'numeric'})}</div></div>}
      </div>
    </div>

    {/* Idioma */}
    <div className="card" style={{padding:22,marginBottom:14}}>
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:14}}>
        <Icon name="settings" size={16} style={{color:'var(--ink-dim)'}}/>
        <h3 className="h3">{t('settings.language')}</h3>
      </div>
      <div style={{display:'flex',gap:8}}>
        {[{v:'es',l:'Español'},{v:'en',l:'English'}].map(l=><button key={l.v} className={`btn btn-sm ${tweaks.lang===l.v?'btn-primary':'btn-ghost'}`} style={{flex:1,padding:'10px 0'}} onClick={()=>{setTweaks(tw=>({...tw,lang:l.v}));window.location.reload();}}>{l.l}</button>)}
      </div>
    </div>

    {/* ENAIRE note */}
    <div className="card" style={{padding:22,marginBottom:14}}>
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10}}>
        <Icon name="shield" size={16} style={{color:'var(--accent)'}}/>
        <h3 className="h3">{t('prof.enaire_title')}</h3>
      </div>
      <p className="caption" style={{lineHeight:1.55}}>{t('prof.enaire_note')}</p>
    </div>

    {/* Soporte */}
    {isPremium && <div className="card" style={{padding:22,marginBottom:14}}>
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10}}>
        <Icon name="send" size={16} style={{color:'var(--accent)'}}/>
        <h3 className="h3">{t('prof.support')}</h3>
      </div>
      {(() => {
        const openTicket = tickets.find(tk => tk.status !== 'closed');
        const closedTickets = tickets.filter(tk => tk.status === 'closed');
        const msgs = openTicket?.messages || [];

        const replyToTicket = async () => {
          if (!ticketMsg.trim() || !openTicket) return;
          setBusy(true);
          try {
            await api.supportReply(openTicket.id, ticketMsg);
            setTicketMsg('');
            api.supportMine().then(d => setTickets(d.tickets || [])).catch(() => {});
          } catch(e) { toast(t('common.error') + ': ' + (e.error || t('common.unknown'))); }
          setBusy(false);
        };

        return <>
          {!openTicket ? <>
            <p className="caption" style={{marginBottom:12}}>{t('prof.support_desc')}</p>
            <textarea className="field" rows={3} value={ticketMsg} onChange={e=>setTicketMsg(e.target.value)} placeholder={t('prof.support_placeholder')} style={{resize:'vertical',minHeight:60,marginBottom:10}}/>
            <button className="btn btn-primary btn-sm" onClick={sendTicket} disabled={busy || !ticketMsg.trim()}><Icon name="send" size={13}/> {t('prof.support_send')}</button>
          </> : <>
            {/* Chat messages */}
            <div style={{display:'flex',flexDirection:'column',gap:8,marginBottom:12,maxHeight:400,overflowY:'auto',padding:'4px 0'}}>
              {msgs.map((m, i) => <div key={m.id || i} style={{
                alignSelf: m.sender === 'user' ? 'flex-end' : 'flex-start',
                maxWidth: '85%',
                padding: '10px 14px',
                borderRadius: m.sender === 'user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                background: m.sender === 'user' ? 'var(--accent-soft)' : 'var(--bg-inset)',
                border: '1px solid var(--stroke)',
                fontSize: 13, lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word'
              }}>
                {m.sender === 'admin' && <div style={{fontWeight:600,fontSize:11,color:'var(--accent)',marginBottom:3}}>AeroPlan</div>}
                {m.body}
                <div className="caption" style={{fontSize:10,marginTop:4,textAlign:'right'}}>{new Date(m.created_at * 1000).toLocaleString()}</div>
              </div>)}
            </div>
            {/* Reply input */}
            <div style={{display:'flex',gap:8,alignItems:'flex-end'}}>
              <textarea className="field" rows={2} value={ticketMsg} onChange={e=>setTicketMsg(e.target.value)} placeholder={t('prof.support_placeholder')} style={{flex:1,resize:'vertical',minHeight:40,fontSize:13}}/>
              <button className="btn btn-primary btn-sm" style={{padding:'8px 14px',flexShrink:0}} onClick={replyToTicket} disabled={busy || !ticketMsg.trim()}><Icon name="send" size={13}/></button>
            </div>
          </>}
          {closedTickets.length > 0 && <div style={{marginTop:14}}>
            <div className="caption" style={{fontSize:12,marginBottom:8}}>{t('prof.prev_tickets')} ({closedTickets.length})</div>
            <div style={{display:'grid',gap:8}}>
              {closedTickets.map(tk => {
                const msgs = tk.messages || [];
                const isOpen = !!expandedTk[tk.id];
                const firstMsg = msgs[0];
                return <div key={tk.id} style={{borderRadius:10,border:'1px solid var(--stroke)',overflow:'hidden',opacity:.8}}>
                  {/* Collapsible header */}
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'10px 14px',background:'var(--bg-inset)',cursor:'pointer',gap:8}} onClick={()=>setExpandedTk(s=>({...s,[tk.id]:!isOpen}))}>
                    <div style={{minWidth:0,flex:1}}>
                      <span className="caption" style={{fontSize:11}}>{t('prof.ticket')} #{tk.id} · {msgs.length} {msgs.length===1?'mensaje':'mensajes'}</span>
                      {!isOpen && firstMsg && <div className="caption" style={{fontSize:11,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis',marginTop:2}}>{firstMsg.body}</div>}
                    </div>
                    <div style={{display:'flex',alignItems:'center',gap:6,flexShrink:0}}>
                      <span className="caption" style={{fontSize:10}}>{new Date(tk.created_at * 1000).toLocaleDateString()}</span>
                      <Icon name={isOpen?'chevron-up':'chevron-down'} size={13} style={{color:'var(--ink-dim)'}}/>
                    </div>
                  </div>
                  {/* Expanded chat */}
                  {isOpen && <div style={{display:'flex',flexDirection:'column',gap:6,padding:12,maxHeight:250,overflowY:'auto'}}>
                    {msgs.map((m, i) => <div key={m.id || i} style={{
                      alignSelf: m.sender === 'user' ? 'flex-end' : 'flex-start',
                      maxWidth: '85%', padding: '8px 12px',
                      borderRadius: m.sender === 'user' ? '12px 12px 4px 12px' : '12px 12px 12px 4px',
                      background: m.sender === 'user' ? 'var(--accent-soft)' : 'var(--bg-inset)',
                      border: '1px solid var(--stroke)',
                      fontSize: 12, lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word'
                    }}>
                      {m.sender === 'admin' && <div style={{fontWeight:600,fontSize:10,color:'var(--accent)',marginBottom:2}}>AeroPlan</div>}
                      {m.body}
                      <div className="caption" style={{fontSize:9,marginTop:3,textAlign:'right'}}>{new Date(m.created_at * 1000).toLocaleString()}</div>
                    </div>)}
                  </div>}
                </div>;
              })}
            </div>
          </div>}
        </>;
      })()}
    </div>}

    {/* Support upgrade prompt for free users */}
    {!isPremium && <div className="card" style={{padding:22,marginBottom:14,background:'color-mix(in srgb, var(--accent-soft) 40%, var(--panel))',border:'1px solid color-mix(in srgb, var(--accent) 30%, var(--stroke))'}}>
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10}}>
        <Icon name="send" size={16} style={{color:'var(--accent)'}}/>
        <h3 className="h3">{t('prof.support')}</h3>
      </div>
      <p className="caption" style={{marginBottom:12}}>{t('prof.support_premium_only') || 'El soporte personalizado es exclusivo para usuarios Premium.'}</p>
      <button className="btn btn-primary btn-sm" onClick={handleUpgrade} disabled={busy}><Icon name="bolt" size={13}/> {t('prof.upgrade_btn')}</button>
    </div>}

    <button className="btn btn-ghost" style={{width:'100%',color:'var(--err)'}} onClick={logout}><Icon name="logout" size={14}/> {t('prof.logout')}</button>
  </div>;
};
window.Profile = Profile;
