const { useState, useRef } = React;

function AddExpenseModal({ travelers, exchangeRate, onAdd, onClose, accent, initial }) {
  const [form, setForm] = useState(() => initial
    ? { desc:initial.desc, amount:String(initial.amount), currency:initial.currency, paidBy:initial.paidBy, date:initial.date }
    : { desc:'', amount:'', currency:'TWD', paidBy: travelers[0]||'',
        date: new Date().toISOString().split('T')[0] });
  const set = (k,v) => setForm(p=>({...p,[k]:v}));
  const num  = parseFloat(form.amount)||0;
  const twd  = form.currency==='VND' ? Math.round(num*exchangeRate) : num;
  const vnd  = form.currency==='TWD' ? Math.round(num/exchangeRate) : num;
  const per  = travelers.length ? Math.round(twd/travelers.length) : 0;

  return (
    <div style={{position:'absolute',inset:0,background:'rgba(0,0,0,0.55)',zIndex:200,display:'flex',alignItems:'flex-end'}}>
      <div style={{background:'#fff',borderRadius:'28px 28px 0 0',padding:'20px 20px 36px',width:'100%',maxHeight:'92%',overflowY:'auto'}}>
        <div style={{width:36,height:4,background:'#E5E7EB',borderRadius:4,margin:'0 auto 18px'}}/>
        <div style={{display:'flex',justifyContent:'space-between',marginBottom:18}}>
          <span style={{fontSize:18,fontWeight:700,display:'flex',alignItems:'center',gap:7}}><i className={initial?"ri-edit-line":"ri-add-circle-line"}></i>{initial?'編輯費用':'新增費用'}</span>
          <button onClick={onClose} style={{background:'#F3F4F6',border:'none',borderRadius:10,width:32,height:32,cursor:'pointer',fontSize:16,display:'flex',alignItems:'center',justifyContent:'center'}}><i className="ri-close-line"></i></button>
        </div>

        {/* Description */}
        <div style={{marginBottom:13}}>
          <div style={{fontSize:12,color:'#6B7280',marginBottom:4}}>費用說明</div>
          <input type="text" value={form.desc} onChange={e=>set('desc',e.target.value)} placeholder="例：午餐、計程車..."
            style={{width:'100%',padding:'11px 14px',border:'1.5px solid #E5E7EB',borderRadius:12,fontSize:14,fontFamily:'Poppins',boxSizing:'border-box',outline:'none'}}/>
        </div>

        {/* Amount + currency toggle */}
        <div style={{marginBottom:11}}>
          <div style={{fontSize:12,color:'#6B7280',marginBottom:4}}>金額</div>
          <div style={{display:'flex',gap:8}}>
            <input type="number" value={form.amount} onChange={e=>set('amount',e.target.value)} placeholder="0"
              style={{flex:1,padding:'11px 14px',border:'1.5px solid #E5E7EB',borderRadius:12,fontSize:18,fontFamily:'Poppins',boxSizing:'border-box',fontWeight:700,outline:'none'}}/>
            <div style={{display:'flex',border:'1.5px solid #E5E7EB',borderRadius:12,overflow:'hidden'}}>
              {['TWD','VND'].map(cur=>(
                <button key={cur} onClick={()=>set('currency',cur)} style={{
                  padding:'11px 14px',border:'none',cursor:'pointer',fontFamily:'Poppins',fontWeight:700,
                  background:form.currency===cur?'#1C1C1E':'#fff',
                  color:form.currency===cur?'#fff':'#9CA3AF',fontSize:13,transition:'all 0.15s'
                }}>{cur}</button>
              ))}
            </div>
          </div>
        </div>

        {/* Conversion preview */}
        {num>0&&(
          <div style={{marginBottom:13,padding:'10px 14px',background:'#F5F5F7',borderRadius:12,display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <span style={{fontSize:13,color:'#6B7280'}}>
              {form.currency==='VND'?`≈ NT$ ${twd.toLocaleString()} TWD`:`≈ ₫ ${vnd.toLocaleString()} VND`}
            </span>
            <span style={{fontSize:13,color:accent,fontWeight:700}}>每人 NT$ {per.toLocaleString()}</span>
          </div>
        )}

        {/* Payer */}
        <div style={{marginBottom:13}}>
          <div style={{fontSize:12,color:'#6B7280',marginBottom:6}}>代墊人</div>
          <div style={{display:'flex',gap:8}}>
            {travelers.map(t=>(
              <button key={t} onClick={()=>set('paidBy',t)} style={{
                flex:1,padding:'10px',border:'none',borderRadius:12,cursor:'pointer',fontFamily:'Poppins',
                background:form.paidBy===t?'#1C1C1E':'#F3F4F6',
                color:form.paidBy===t?'#fff':'#6B7280',
                fontWeight:form.paidBy===t?700:400,fontSize:14,transition:'all 0.15s'
              }}>{t}</button>
            ))}
          </div>
        </div>

        {/* Date */}
        <div style={{marginBottom:22}}>
          <div style={{fontSize:12,color:'#6B7280',marginBottom:4}}>日期</div>
          <input type="date" value={form.date} onChange={e=>set('date',e.target.value)}
            style={{width:'100%',padding:'10px 14px',border:'1.5px solid #E5E7EB',borderRadius:12,fontSize:14,fontFamily:'Poppins',boxSizing:'border-box',outline:'none'}}/>
        </div>

        <button onClick={()=>{if(!form.desc||!num)return;onAdd({id:initial?initial.id:Date.now(),...form,amount:num});onClose();}} style={{
          width:'100%',padding:'14px',background:form.desc&&num?'#1C1C1E':'#D1D5DB',
          color:'#fff',border:'none',borderRadius:16,fontWeight:700,cursor:'pointer',fontSize:15,fontFamily:'Poppins',transition:'all 0.2s'
        }}><i className="ri-check-line"></i>{initial?' 儲存修改':' 確認新增'}</button>
      </div>
    </div>
  );
}

// Swipe-to-delete + tap-to-edit row wrapper
function SwipeRow({ onEdit, onDelete, children }) {
  const REVEAL = 76;
  const [dx, setDx]   = useState(0);
  const startX  = useRef(null);
  const baseX   = useRef(0);
  const dragged = useRef(false);

  const begin = x => { startX.current = x; dragged.current = false; };
  const move  = x => {
    if (startX.current==null) return;
    if (Math.abs(x-startX.current) > 4) dragged.current = true;
    let d = baseX.current + (x - startX.current);
    if (d > 0) d = 0;
    if (d < -REVEAL-24) d = -REVEAL-24;
    setDx(d);
  };
  const end = () => {
    if (startX.current==null) return;
    startX.current = null;
    const opened = dx <= -REVEAL/2;
    baseX.current = opened ? -REVEAL : 0;
    setDx(baseX.current);
  };
  const tap = () => {
    if (dragged.current) return;
    if (baseX.current < 0) { baseX.current = 0; setDx(0); return; }
    onEdit();
  };

  return (
    <div style={{position:'relative',marginBottom:8}}>
      {/* delete background revealed on swipe */}
      <button onClick={onDelete} style={{
        position:'absolute',inset:0,background:'#EF4444',border:'none',borderRadius:16,cursor:'pointer',
        display:'flex',alignItems:'center',justifyContent:'flex-end',gap:5,paddingRight:26,
        color:'#fff',fontSize:14,fontWeight:700,fontFamily:'Poppins'
      }}><i className="ri-delete-bin-line" style={{fontSize:18}}></i>刪除</button>
      {/* foreground card */}
      <div
        onClick={tap}
        onPointerDown={e=>begin(e.clientX)}
        onPointerMove={e=>{ if(startX.current!=null && e.pointerType==='mouse' && e.buttons===0){ end(); return; } move(e.clientX); }}
        onPointerUp={end}
        onPointerCancel={end}
        onPointerLeave={()=>{ if(startX.current!=null) end(); }}
        style={{position:'relative',transform:`translateX(${dx}px)`,
          transition:startX.current==null?'transform 0.22s ease':'none',
          touchAction:'pan-y',cursor:'pointer'}}>
        {children}
      </div>
    </div>
  );
}

function FinanceScreen({ expenses, setExpenses, travelers, exchangeRate, setExchangeRate, accent }) {
  const [tab,      setTab]      = useState('list');
  const [showAdd,  setShowAdd]  = useState(false);
  const [editing,  setEditing]  = useState(null);
  const [refreshing,setRefreshing]=useState(false);
  const [rateErr,  setRateErr]  = useState(null);
  const [lastFetch,setLastFetch]= useState(() => parseInt(localStorage.getItem('rate_last_fetch') || '0', 10));

  const saveExpense   = exp => setExpenses(prev => prev.some(x=>x.id===exp.id) ? prev.map(x=>x.id===exp.id?exp:x) : [...prev, exp]);
  const deleteExpense = id  => setExpenses(prev => prev.filter(x=>x.id!==id));

  const toTWD = e => e.currency==='VND' ? e.amount*exchangeRate : e.amount;
  const total  = expenses.reduce((s,e)=>s+toTWD(e),0);
  const share  = total/(travelers.length||1);

  const people = travelers.map(name=>{
    const paid = expenses.filter(e=>e.paidBy===name).reduce((s,e)=>s+toTWD(e),0);
    return { name, paid, balance: paid-share };
  });

  // Greedy settlement
  const settlements = [];
  const creds = people.filter(p=>p.balance>0.5).map(p=>({...p})).sort((a,b)=>b.balance-a.balance);
  const debts = people.filter(p=>p.balance<-0.5).map(p=>({...p})).sort((a,b)=>a.balance-b.balance);
  let ci=0,di=0;
  while(ci<creds.length&&di<debts.length){
    const amt=Math.min(creds[ci].balance,-debts[di].balance);
    if(amt>0.5) settlements.push({from:debts[di].name,to:creds[ci].name,amount:amt});
    creds[ci].balance-=amt; debts[di].balance+=amt;
    if(creds[ci].balance<0.5)ci++;
    if(-debts[di].balance<0.5)di++;
  }

  const refresh = async () => {
    setRefreshing(true);
    setRateErr(null);
    try {
      const { rate } = await window.fetchLiveRate();
      setExchangeRate(rate);
      const now = Date.now();
      localStorage.setItem('rate_last_fetch', String(now));
      setLastFetch(now);
    } catch (err) {
      console.warn('Refresh rate failed:', err);
      setRateErr(err.message || '更新失敗');
      setTimeout(() => setRateErr(null), 3000);
    } finally {
      setRefreshing(false);
    }
  };

  const fmtTime = ts => ts
    ? new Date(ts).toLocaleString('zh-TW',{month:'numeric',day:'numeric',hour:'2-digit',minute:'2-digit'})
    : '尚未更新';

  return (
    <div style={{height:'100%',display:'flex',flexDirection:'column',background:'#F5F5F7',position:'relative'}}>
      {/* Dark header */}
      <div style={{background:'#1C1C1E',padding:'16px 20px 18px'}}>
        <div style={{fontSize:20,fontWeight:700,color:'#fff',marginBottom:12,display:'flex',alignItems:'center',gap:8}}><i className="ri-wallet-3-line"></i>記帳分帳</div>
        {/* Total */}
        <div style={{background:'rgba(255,255,255,0.08)',borderRadius:20,padding:'14px 18px',marginBottom:10}}>
          <div style={{color:'#6B7280',fontSize:12,marginBottom:4}}>旅程總花費</div>
          <div style={{color:'#fff',fontSize:28,fontWeight:700,letterSpacing:-0.5}}>NT$ {Math.round(total).toLocaleString()}</div>
          <div style={{color:'#9CA3AF',fontSize:13,marginTop:4}}>每人均攤 NT$ {Math.round(share).toLocaleString()}</div>
        </div>
        {/* Exchange rate */}
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',background:'rgba(255,255,255,0.06)',borderRadius:16,padding:'10px 14px'}}>
          <div>
            <div style={{color:'#6B7280',fontSize:10,marginBottom:2,display:'flex',alignItems:'center',gap:4}}><i className="ri-exchange-line"></i>即時匯率</div>
            <div style={{color:'#fff',fontSize:13,fontWeight:600}}>1 TWD = {Math.round(1/exchangeRate).toLocaleString()} VND</div>
            <div style={{color:'#6B7280',fontSize:11}}>1 VND = {exchangeRate.toFixed(5)} TWD</div>
            <div style={{color: rateErr ? '#EF4444' : '#6B7280', fontSize:10, marginTop:3}}>
              {rateErr ? `⚠ ${rateErr}` : `更新於 ${fmtTime(lastFetch)}`}
            </div>
          </div>
          <button onClick={refresh} disabled={refreshing} style={{
            background:'rgba(255,255,255,0.1)',border:'1px solid rgba(255,255,255,0.15)',
            borderRadius:12,padding:'7px 13px',color:'#fff',cursor:'pointer',fontSize:12,fontFamily:'Poppins'
          }}>{refreshing?'更新中...':<><i className="ri-refresh-line"></i>{' 更新'}</>}</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{background:'#fff',display:'flex',borderBottom:'1px solid #F0F0F0'}}>
        {[['list','明細'],['split','分帳'],['settle','結算']].map(([key,label])=>(
          <button key={key} onClick={()=>setTab(key)} style={{
            flex:1,padding:'12px 0',border:'none',background:'none',cursor:'pointer',fontFamily:'Poppins',
            fontSize:14,fontWeight:tab===key?700:400,
            color:tab===key?accent:'#6B7280',
            borderBottom:tab===key?`2px solid ${accent}`:'2px solid transparent',transition:'all 0.2s'
          }}>{label}</button>
        ))}
      </div>

      {/* Content */}
      <div style={{flex:1,overflowY:'auto',padding:'10px 16px 100px'}}>

        {/* 明細 */}
        {tab==='list'&&(
          <>
            {expenses.length===0&&(
              <div style={{textAlign:'center',padding:'40px',color:'#9CA3AF'}}>
                <i className="ri-receipt-line" style={{fontSize:36,marginBottom:8,display:'block',color:'#D1D5DB'}}></i><div>尚無費用記錄</div>
              </div>
            )}
            {expenses.map(e=>{
              const t=toTWD(e);
              return (
                <SwipeRow key={e.id} onEdit={()=>setEditing(e)} onDelete={()=>deleteExpense(e.id)}>
                <div style={{background:'#fff',borderRadius:16,padding:'14px 16px',boxShadow:'0 1px 6px rgba(0,0,0,0.05)'}}>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start'}}>
                    <div style={{flex:1}}>
                      <div style={{fontSize:15,fontWeight:700,color:'#1C1C1E',marginBottom:5}}>{e.desc}</div>
                      <div style={{display:'flex',gap:7,alignItems:'center',flexWrap:'wrap'}}>
                        <span style={{fontSize:11,color:'#9CA3AF'}}>{e.date}</span>
                        <span style={{fontSize:12,color:'#6B7280',background:'#F3F4F6',borderRadius:8,padding:'2px 8px',display:'inline-flex',alignItems:'center',gap:3}}><i className="ri-user-line"></i>{e.paidBy}</span>
                        <span style={{fontSize:11,color:'#9CA3AF'}}>{travelers.length}人均分</span>
                      </div>
                    </div>
                    <div style={{textAlign:'right',flexShrink:0,paddingLeft:10}}>
                      <div style={{fontSize:15,fontWeight:700,color:'#1C1C1E'}}>
                        {e.currency==='VND'?`₫ ${e.amount.toLocaleString()}`:`NT$ ${e.amount.toLocaleString()}`}
                      </div>
                      {e.currency==='VND'&&<div style={{fontSize:11,color:'#9CA3AF',marginTop:2}}>≈ NT$ {Math.round(t).toLocaleString()}</div>}
                    </div>
                  </div>
                </div>
                </SwipeRow>
              );
            })}
          </>
        )}

        {/* 分帳 */}
        {tab==='split'&&people.map(p=>{
          const pos=p.balance>0;
          return (
            <div key={p.name} style={{background:'#fff',borderRadius:18,padding:'16px',marginBottom:10,boxShadow:'0 1px 6px rgba(0,0,0,0.05)'}}>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:12}}>
                <div style={{display:'flex',alignItems:'center',gap:10}}>
                  <div style={{width:42,height:42,borderRadius:'50%',background:'#1C1C1E',display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',fontSize:18,fontWeight:700}}>{p.name[0]}</div>
                  <span style={{fontSize:17,fontWeight:700}}>{p.name}</span>
                </div>
                <div style={{padding:'4px 13px',borderRadius:12,background:pos?'#D1FAE5':'#FEE2E2',color:pos?'#059669':'#EF4444',fontSize:14,fontWeight:700}}>
                  {pos?`+NT$ ${Math.round(p.balance).toLocaleString()}`:`-NT$ ${Math.round(-p.balance).toLocaleString()}`}
                </div>
              </div>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8}}>
                {[{l:'已墊付',v:`NT$ ${Math.round(p.paid).toLocaleString()}`},{l:'應付金額',v:`NT$ ${Math.round(share).toLocaleString()}`}].map(s=>(
                  <div key={s.l} style={{background:'#F5F5F7',borderRadius:12,padding:'10px 12px'}}>
                    <div style={{fontSize:11,color:'#6B7280',marginBottom:2}}>{s.l}</div>
                    <div style={{fontSize:14,fontWeight:700,color:'#1C1C1E'}}>{s.v}</div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}

        {/* 結算 */}
        {tab==='settle'&&(
          <div>
            <div style={{fontSize:13,color:'#6B7280',marginBottom:12,padding:'0 4px'}}>建議結算方式（均分）</div>
            {settlements.length===0?(
              <div style={{background:'#fff',borderRadius:18,padding:'28px',textAlign:'center',boxShadow:'0 1px 6px rgba(0,0,0,0.05)'}}>
                <i className="ri-checkbox-circle-line" style={{fontSize:36,marginBottom:8,display:'block',color:'#10B981'}}></i>
                <div style={{fontSize:16,fontWeight:700,color:'#1C1C1E'}}>帳目已平衡！</div>
                <div style={{fontSize:13,color:'#9CA3AF',marginTop:4}}>花費均等，無需結算</div>
              </div>
            ):settlements.map((s,i)=>(
              <div key={i} style={{background:'#fff',borderRadius:18,padding:'16px 18px',marginBottom:10,boxShadow:'0 1px 6px rgba(0,0,0,0.05)'}}>
                <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:12}}>
                  <div style={{width:36,height:36,borderRadius:'50%',background:'#FEE2E2',display:'flex',alignItems:'center',justifyContent:'center',color:'#EF4444',fontWeight:700,fontSize:16}}>{s.from[0]}</div>
                  <div style={{flex:1,fontSize:14}}>
                    <span style={{fontWeight:700}}>{s.from}</span>
                    <span style={{color:'#6B7280'}}> 需付給 </span>
                    <span style={{fontWeight:700}}>{s.to}</span>
                  </div>
                  <div style={{width:36,height:36,borderRadius:'50%',background:'#D1FAE5',display:'flex',alignItems:'center',justifyContent:'center',color:'#059669',fontWeight:700,fontSize:16}}>{s.to[0]}</div>
                </div>
                <div style={{background:'#FFF7ED',borderRadius:14,padding:'12px',textAlign:'center'}}>
                  <div style={{fontSize:22,fontWeight:700,color:accent}}>NT$ {Math.round(s.amount).toLocaleString()}</div>
                  <div style={{fontSize:12,color:'#9CA3AF',marginTop:3}}>≈ ₫ {Math.round(s.amount/exchangeRate).toLocaleString()}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* FAB */}
      <button onClick={()=>setShowAdd(true)} style={{
        position:'absolute',right:18,bottom:96,width:52,height:52,
        borderRadius:'50%',background:accent,border:'none',cursor:'pointer',
        boxShadow:`0 4px 18px ${accent}60`,color:'#fff',fontSize:26,
        display:'flex',alignItems:'center',justifyContent:'center',zIndex:10
      }}>+</button>

      {(showAdd||editing)&&(
        <AddExpenseModal
          travelers={travelers} exchangeRate={exchangeRate} accent={accent} initial={editing}
          onAdd={saveExpense} onClose={()=>{setShowAdd(false);setEditing(null);}}
        />
      )}
    </div>
  );
}

window.FinanceScreen = FinanceScreen;
