/* ===== Portfolio — holdings, optimisation, rebalance, tax harvest ===== */
const ALLOC_COLOR = { Equity:'#d4af5c', Debt:'#7fa8d9', Gold:'#b48ad9' };

function ScreenPortfolio({ openFund }) {
  const p = portfolioStats();
  const segs = ['Equity','Debt','Gold'].map(k=>({ label:k, val:p.allocAbs[k], color:ALLOC_COLOR[k] }));
  const actions = (p.regular.length?1:0) + (p.laggards.length?1:0) + (Math.abs(p.drift.Equity)>5?1:0) + (p.losers.length?1:0);
  const score = Math.max(40, Math.round(100 - p.regular.length*4 - p.laggards.length*5 - (Math.abs(p.drift.Equity)>5?8:0) - 6));

  return (
    <div className="scroll" style={{ padding:'4px 16px 96px' }}>
      <div className="row" style={{ justifyContent:'space-between', padding:'14px 2px 4px' }}>
        <div className="eyebrow">Portfolio</div>
        <div className="row" style={{ gap:6 }}>
          <span className="tag" style={{ background:'var(--surface-2)', color:'var(--dim)' }}>XIRR 16.2%</span>
        </div>
      </div>

      {/* value hero + allocation */}
      <div className="card" style={{ padding:'18px 18px 16px', marginTop:6, position:'relative', overflow:'hidden',
        background:'linear-gradient(160deg,#1a1d20,#121417 75%)' }}>
        <div style={{ position:'absolute', right:-50, top:-50, width:150, height:150, borderRadius:'50%', background:'var(--gold-glow)', filter:'blur(8px)' }}/>
        <div className="row" style={{ justifyContent:'space-between', alignItems:'center' }}>
          <div>
            <div className="eyebrow">Current value</div>
            <div className="serif tnum" style={{ fontSize:34, lineHeight:1.05, marginTop:7, whiteSpace:'nowrap' }}>{fmtINR(p.current,2)}</div>
            <div className="row" style={{ gap:7, marginTop:9 }}>
              <span className="tag" style={{ background:'var(--green-dim)', color:'var(--green)' }}>
                <Icon name="arrowUp" size={11} color="var(--green)"/> {fmtINR(p.gain,1)} · {p.gainPct.toFixed(1)}%
              </span>
            </div>
            <div style={{ fontSize:11, color:'var(--faint)', marginTop:8 }} className="mono">invested {fmtINR(p.invested,2)}</div>
          </div>
          <Donut segments={segs} size={96} stroke={14}>
            <div className="serif" style={{ fontSize:17 }}>{FUNDS.length}</div>
            <div className="eyebrow" style={{ fontSize:7.5, marginTop:1 }}>funds</div>
          </Donut>
        </div>
        <div className="row" style={{ gap:16, marginTop:16 }}>
          {segs.map(s=>(
            <div key={s.label} className="row" style={{ gap:6 }}>
              <i style={{ width:8, height:8, borderRadius:2.5, background:s.color }}/>
              <span style={{ fontSize:11, color:'var(--dim)' }}>{s.label}</span>
              <span className="tnum" style={{ fontSize:11.5, fontWeight:700 }}>{p.alloc[s.label].toFixed(0)}%</span>
            </div>
          ))}
        </div>
      </div>

      {/* optimisation summary */}
      <div style={{ marginTop:14, borderRadius:20, padding:'15px 16px',
        background:'linear-gradient(120deg,rgba(212,175,92,.16),rgba(212,175,92,.03))', border:'1px solid rgba(212,175,92,.28)',
        display:'flex', alignItems:'center', gap:14 }}>
        <Ring pct={score/100} size={62} stroke={6} color="var(--gold)">
          <div className="serif tnum" style={{ fontSize:17, color:'var(--gold-bright)' }}>{score}</div>
        </Ring>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:14, fontWeight:700 }}>Portfolio health · {actions} fixes</div>
          <div style={{ fontSize:11.5, color:'var(--dim)', marginTop:3, lineHeight:1.45 }}>
            Recover <b style={{ color:'var(--gold-bright)' }}>{fmtINR(p.annualLeak+p.taxSaved,0)}</b> this year ·
            <b style={{ color:'var(--gold-bright)' }}> {fmtINR(p.leak20,1)}</b> over 20 yrs
          </div>
        </div>
      </div>

      <SectionTitle>Optimise</SectionTitle>

      {/* A — switch to direct */}
      <OptCard icon="swap" iconColor="var(--gold)" title="Move to Direct plans"
        amount={fmtINR(p.annualLeak,0)} amountSub="/yr leaking">
        <div style={{ fontSize:11.5, color:'var(--dim)', lineHeight:1.5, marginBottom:12 }}>
          {p.regular.length} funds are in <b style={{ color:'var(--text)' }}>Regular</b> plans paying distributor commission. Same fund, Direct plan, lower expense ratio.
        </div>
        {p.regular.map((f,i)=>{
          const leak = f.current*(f.erReg-f.erDir)/100;
          return (
            <div key={f.id} className="row" style={{ justifyContent:'space-between', padding:'9px 0',
              borderTop:i>0?'1px solid var(--line)':'none' }}>
              <div style={{ minWidth:0, flex:1 }}>
                <div style={{ fontSize:12.5, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{f.name}</div>
                <div style={{ fontSize:10.5, color:'var(--faint)', marginTop:2 }} className="mono">ER {f.erReg.toFixed(2)}% → {f.erDir.toFixed(2)}%</div>
              </div>
              <div style={{ textAlign:'right' }}>
                <div className="tnum" style={{ fontSize:12.5, fontWeight:700, color:'var(--red)' }}>−{fmtINR(leak,0)}/yr</div>
                <div style={{ fontSize:10, color:'var(--faint)' }}>{fmtINR(f.current,1)}</div>
              </div>
            </div>
          );
        })}
        <div style={{ fontSize:11, color:'var(--gold-bright)', marginTop:10, marginBottom:2, fontWeight:600 }} className="mono">≈ {fmtINR(p.leak20,1)} kept over 20 years</div>
        <OptCTA label="Switch all to Direct" act={{ title:'Switch '+p.regular.length+' funds to Direct', body:'We initiate a switch from Regular to Direct plans of the same funds. Same portfolio, lower expense ratio — exit load &amp; tax on the switch are shown before you confirm.', impact:'Keeps ~'+fmtINR(p.leak20,1)+' over 20 years', cta:'Review &amp; switch', icon:'swap', color:'var(--gold)' }}/>
      </OptCard>

      {/* B — rebalance */}
      <OptCard icon="scale" iconColor="var(--blue)" title="Rebalance to target"
        amount={Math.abs(p.drift.Equity).toFixed(0)+'%'} amountSub="off target" amountColor="var(--blue)">
        <div style={{ fontSize:11.5, color:'var(--dim)', lineHeight:1.5, marginBottom:13 }}>
          A strong equity run pushed you above your glide path. Trim equity into debt &amp; gold to lock in gains and cut risk.
        </div>
        {['Equity','Debt','Gold'].map(k=>{
          const cur = p.alloc[k], tgt = TARGET_ALLOC[k], move = (tgt-cur)/100*p.current;
          return (
            <div key={k} style={{ marginBottom:12 }}>
              <div className="row" style={{ justifyContent:'space-between', marginBottom:5 }}>
                <span style={{ fontSize:12, color:'var(--dim)' }}>{k}</span>
                <span className="tnum" style={{ fontSize:11.5, fontWeight:700 }}>
                  {cur.toFixed(0)}% → <span style={{ color:ALLOC_COLOR[k] }}>{tgt}%</span>
                </span>
              </div>
              <div style={{ position:'relative', height:6, borderRadius:4, background:'rgba(243,239,231,.08)' }}>
                <div style={{ position:'absolute', left:0, width:Math.min(100,cur)+'%', height:'100%', borderRadius:4, background:ALLOC_COLOR[k], opacity:.45 }}/>
                <div style={{ position:'absolute', left:'calc('+Math.min(100,tgt)+'% - 1px)', top:-2, width:2, height:10, background:'var(--text)' }}/>
              </div>
              <div style={{ fontSize:10.5, color: move<0?'var(--red)':'var(--green)', marginTop:4 }} className="mono">
                {move<0?'sell ':'buy '}{fmtINR(Math.abs(move),1)}
              </div>
            </div>
          );
        })}
        <OptCTA label="Auto-rebalance" act={{ title:'Rebalance to target', body:'Places the buy/sell orders above to bring Equity, Debt &amp; Gold back to your glide path. Tax-aware: redemptions prefer units held over a year first.', impact:'Locks in gains, cuts portfolio risk', cta:'Place orders', icon:'scale', color:'var(--blue)' }}/>
      </OptCard>

      {/* C — underperformers */}
      <OptCard icon="trendDown" iconColor="var(--red)" title={`Review ${p.laggards.length} laggards`}
        amount={p.laggards.length+''} amountSub="trailing" amountColor="var(--red)">
        {p.laggards.map((f,i)=>(
          <div key={f.id} style={{ padding:'10px 0', borderTop:i>0?'1px solid var(--line)':'none' }}>
            <div className="row" style={{ justifyContent:'space-between' }}>
              <span style={{ fontSize:13, fontWeight:600 }}>{f.name}</span>
              <span className="tag" style={{ background:'var(--red-dim)', color:'var(--red)' }}>−{(f.catRet3y-f.ret3y).toFixed(1)}%</span>
            </div>
            <div style={{ fontSize:11, color:'var(--dim)', marginTop:4 }} className="mono">
              3Y {f.ret3y.toFixed(1)}% · {f.cat} avg {f.catRet3y.toFixed(1)}%
            </div>
            <div style={{ fontSize:11, color:'var(--gold-bright)', marginTop:5 }}>→ consider a low-cost Direct {f.cat} index fund</div>
          </div>
        ))}
        <OptCTA label="Compare alternatives" act={{ title:'Compare alternatives', body:'See low-cost Direct index funds and top-quartile peers in each lagging category, side by side with 3Y/5Y returns and expense ratios.', impact:'Find a better fit for '+p.laggards.length+' funds', cta:'View comparison', icon:'trendDown', color:'var(--red)' }}/>
      </OptCard>

      {/* D — tax-loss harvesting */}
      <OptCard icon="leaf" iconColor="var(--green)" title="Harvest tax losses"
        amount={fmtINR(p.taxSaved,0)} amountSub="tax saved" amountColor="var(--green)">
        {p.losers.map(f=>(
          <div key={f.id} className="row" style={{ justifyContent:'space-between', marginBottom:11 }}>
            <div>
              <div style={{ fontSize:13, fontWeight:600 }}>{f.name}</div>
              <div style={{ fontSize:10.5, color:'var(--faint)', marginTop:2 }} className="mono">held {f.heldMo} mo · {f.heldMo>=12?'LTCG':'STCG'}</div>
            </div>
            <div className="tnum" style={{ fontSize:13, fontWeight:700, color:'var(--red)' }}>−{fmtINR(f.invested-f.current,0)}</div>
          </div>
        ))}
        <div style={{ fontSize:11.5, color:'var(--dim)', lineHeight:1.5, padding:'10px 12px', borderRadius:12, background:'var(--bg)', border:'1px solid var(--line)' }}>
          Book <b style={{ color:'var(--text)' }}>{fmtINR(p.lossAvail,0)}</b> of losses to offset realised gains → save <b style={{ color:'var(--green)' }}>{fmtINR(p.taxSaved,0)}</b> tax. Re-buy to keep your position.
          <div style={{ marginTop:7, color:'var(--faint)' }}>Tip: also realise up to ₹1.25L of gains tax-free this year to reset your cost basis.</div>
        </div>
        <OptCTA label="Harvest now" act={{ title:'Harvest tax losses', body:'Books '+fmtINR(p.lossAvail,0)+' of unrealised losses to offset your realised gains, then re-buys to keep your position intact.', impact:'Saves ~'+fmtINR(p.taxSaved,0)+' in tax this year', cta:'Harvest &amp; re-buy', icon:'leaf', color:'var(--green)' }}/>
      </OptCard>

      {/* holdings */}
      <SectionTitle action="Sort">Holdings · {FUNDS.length}</SectionTitle>
      <div className="card" style={{ overflow:'hidden' }}>
        {FUNDS.map((f,i)=>{
          const g = (f.current-f.invested)/f.invested*100;
          const lag = assetClass(f.cat)==='Equity' && f.ret3y < f.catRet3y - 1.5;
          return (
            <button key={f.id} onClick={()=>openFund(f)} style={{ ...plainBtn, width:'100%' }}>
              <div className="row" style={{ gap:12, padding:'12px 14px', textAlign:'left',
                borderBottom:i<FUNDS.length-1?'1px solid var(--line)':'none' }}>
                <div style={{ width:34, height:34, borderRadius:10, flexShrink:0, background:ALLOC_COLOR[assetClass(f.cat)]+'22',
                  display:'flex', alignItems:'center', justifyContent:'center', color:ALLOC_COLOR[assetClass(f.cat)], fontWeight:700, fontSize:13 }}>{f.cat[0]}</div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div className="row" style={{ gap:6 }}>
                    <span style={{ fontSize:13.5, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{f.name}</span>
                  </div>
                  <div className="row" style={{ gap:6, marginTop:3 }}>
                    <span className="tag" style={{ background: f.plan==='Regular'?'rgba(212,175,92,.14)':'var(--green-dim)', color: f.plan==='Regular'?'var(--gold)':'var(--green)' }}>{f.plan}</span>
                    <span style={{ fontSize:10.5, color:'var(--faint)' }}>{f.cat}</span>
                    {lag && <Icon name="alert" size={12} color="var(--red)"/>}
                  </div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div className="tnum" style={{ fontSize:13.5, fontWeight:700 }}>{fmtINR(f.current,1)}</div>
                  <div className="tnum" style={{ fontSize:11, fontWeight:600, color:g>=0?'var(--green)':'var(--red)', marginTop:2 }}>{g>=0?'+':''}{g.toFixed(1)}%</div>
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function OptCard({ icon, iconColor, title, amount, amountSub, amountColor, children }) {
  return (
    <div className="card" style={{ padding:16, marginBottom:12 }}>
      <div className="row" style={{ justifyContent:'space-between', marginBottom:13 }}>
        <div className="row" style={{ gap:11 }}>
          <div style={{ width:36, height:36, borderRadius:11, flexShrink:0, background:iconColor+'1f',
            display:'flex', alignItems:'center', justifyContent:'center' }}>
            <Icon name={icon} size={19} color={iconColor}/>
          </div>
          <div style={{ fontSize:14.5, fontWeight:700, alignSelf:'center' }}>{title}</div>
        </div>
        <div style={{ textAlign:'right' }}>
          <div className="serif tnum" style={{ fontSize:19, color:amountColor||'var(--gold-bright)', lineHeight:1 }}>{amount}</div>
          {amountSub && <div style={{ fontSize:9.5, color:'var(--faint)', marginTop:3 }} className="mono">{amountSub}</div>}
        </div>
      </div>
      {children}
    </div>
  );
}

function OptCTA({ label, act }) {
  const fire = () => window.dispatchEvent(new CustomEvent('maxfi-act', { detail: act || { title: label } }));
  return (
    <button onClick={fire} style={{ width:'100%', marginTop:14, padding:'11px', borderRadius:12, border:'1px solid var(--line-2)',
      background:'var(--surface-2)', color:'var(--gold-bright)', fontSize:13, fontWeight:700, cursor:'pointer',
      fontFamily:'var(--font-sans)', display:'flex', alignItems:'center', justifyContent:'center', gap:6 }}>
      {label} <Icon name="arrowR" size={15} color="var(--gold-bright)"/>
    </button>
  );
}

Object.assign(window, { ScreenPortfolio, OptCard, OptCTA, ALLOC_COLOR });
