/* ===== MaxFi shared UI: charts, rings, tiles ===== */

function Sparkline({ data, w = 92, h = 30, color = 'var(--gold)', fill = true }) {
  const min = Math.min(...data), max = Math.max(...data);
  const rng = max - min || 1;
  const pts = data.map((v, i) => [ (i/(data.length-1))*w, h - ((v-min)/rng)*(h-4) - 2 ]);
  const line = pts.map((p,i) => (i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
  const area = line + ` L${w} ${h} L0 ${h} Z`;
  const id = 'sg'+Math.round(min*1000)+data.length;
  return (
    <svg width={w} height={h} style={{ display:'block', overflow:'visible' }}>
      <defs><linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor={color} stopOpacity="0.28"/>
        <stop offset="1" stopColor={color} stopOpacity="0"/>
      </linearGradient></defs>
      {fill && <path d={area} fill={`url(#${id})`}/>}
      <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="2.6" fill={color}/>
    </svg>
  );
}

function Ring({ pct, size = 96, stroke = 9, color = 'var(--gold)', track = 'rgba(243,239,231,.09)', children }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c * (1 - Math.max(0, Math.min(1, pct)));
  return (
    <div style={{ position:'relative', width:size, height:size }}>
      <svg width={size} height={size} style={{ transform:'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={track} strokeWidth={stroke}/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
          strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
          style={{ transition:'stroke-dashoffset .7s cubic-bezier(.2,.8,.2,1)' }}/>
      </svg>
      <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column',
        alignItems:'center', justifyContent:'center', textAlign:'center' }}>{children}</div>
    </div>
  );
}

// FIRE projection area chart with target line
function ProjectionChart({ series, fiNumber, years, w = 340, h = 150, label = 'FI' }) {
  const pad = { l:0, r:0, t:10, b:0 };
  const maxV = Math.max(fiNumber * 1.08, series[series.length-1].v);
  const maxY = series[series.length-1].y || 1;
  const X = (y) => (y / maxY) * w;
  const Y = (v) => h - pad.t - (v / maxV) * (h - pad.t) ;
  const pts = series.map(s => [X(s.y), Y(s.v)]);
  const line = pts.map((p,i)=>(i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ');
  const area = line + ` L${w} ${h} L0 ${h} Z`;
  const fiY = Y(fiNumber);
  // monte-carlo style band (widening cone)
  const upper = series.map(s => [X(s.y), Y(s.v * (1 + 0.10*Math.sqrt(s.y)))]);
  const lower = series.map(s => [X(s.y), Y(s.v * (1 - 0.085*Math.sqrt(s.y)))]);
  const band = upper.map((p,i)=>(i?'L':'M')+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ')
             + ' ' + lower.slice().reverse().map(p=>'L'+p[0].toFixed(1)+' '+p[1].toFixed(1)).join(' ') + ' Z';
  return (
    <svg width={w} height={h} style={{ display:'block', overflow:'visible' }}>
      <defs><linearGradient id="fireGrad" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor="var(--gold)" stopOpacity="0.30"/>
        <stop offset="1" stopColor="var(--gold)" stopOpacity="0"/>
      </linearGradient></defs>
      <path d={band} fill="var(--gold)" opacity="0.07"/>
      {/* target line */}
      <line x1="0" y1={fiY} x2={w} y2={fiY} stroke="var(--green)" strokeWidth="1.3" strokeDasharray="4 4" opacity="0.7"/>
      <text x={w-2} y={fiY-7} textAnchor="end" fontSize="10" fill="var(--green)" fontFamily="var(--font-mono)" letterSpacing="0.5">{label} {fmtINR(fiNumber,1)}</text>
      <path d={area} fill="url(#fireGrad)"/>
      <path d={line} fill="none" stroke="var(--gold)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
      {/* crossing marker */}
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="4" fill="var(--gold)" stroke="var(--bg)" strokeWidth="2"/>
    </svg>
  );
}

function SegmentBar({ cats, total, h = 11 }) {
  return (
    <div style={{ display:'flex', height:h, borderRadius:6, overflow:'hidden', gap:2 }}>
      {cats.map((c,i)=>(
        <div key={i} title={c.name} style={{ flex:c.val, background:c.color, opacity:.85 }}/>
      ))}
    </div>
  );
}

// multi-segment allocation donut
function Donut({ segments, size = 104, stroke = 15, children }) {
  const total = segments.reduce((s,x)=>s+x.val,0) || 1;
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  let acc = 0;
  return (
    <div style={{ position:'relative', width:size, height:size }}>
      <svg width={size} height={size} style={{ transform:'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(243,239,231,.06)" strokeWidth={stroke}/>
        {segments.map((s,i)=>{
          const len = c * s.val / total;
          const el = (
            <circle key={i} cx={size/2} cy={size/2} r={r} fill="none" stroke={s.color} strokeWidth={stroke}
              strokeDasharray={`${Math.max(0,len-2)} ${c-Math.max(0,len-2)}`} strokeDashoffset={-acc}
              strokeLinecap="butt"/>
          );
          acc += len;
          return el;
        })}
      </svg>
      {children && <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center' }}>{children}</div>}
    </div>
  );
}

function CreditCardTile({ card, w = 250, h = 152, dim = false }) {
  return (
    <div style={{ width:w, height:h, borderRadius:18, flexShrink:0, position:'relative', overflow:'hidden',
      background:`linear-gradient(135deg,${card.hue} 0%, ${card.hue}cc 38%, #14171a 120%)`,
      border:'1px solid rgba(255,255,255,.1)', boxShadow:'0 14px 30px -14px rgba(0,0,0,.7)',
      opacity:dim?0.5:1, transition:'opacity .2s', padding:16, color:'#fff' }}>
      <div style={{ position:'absolute', right:-30, top:-30, width:130, height:130, borderRadius:'50%',
        background:'radial-gradient(circle,rgba(255,255,255,.16),transparent 70%)' }}/>
      <div className="row" style={{ justifyContent:'space-between', alignItems:'flex-start' }}>
        <div>
          <div style={{ fontSize:9, letterSpacing:1.5, opacity:.7, fontFamily:'var(--font-mono)', textTransform:'uppercase' }}>{card.issuer}</div>
          <div style={{ fontWeight:700, fontSize:15.5, marginTop:2 }}>{card.name.replace(card.issuer+' ','')}</div>
        </div>
        <div style={{ width:30, height:22, borderRadius:5, background:'linear-gradient(135deg,#f5e7c0,#caa14e)', opacity:.92 }}/>
      </div>
      <div style={{ position:'absolute', left:16, bottom:38, fontFamily:'var(--font-mono)', fontSize:14, letterSpacing:2, opacity:.92 }}>•••• {card.last4}</div>
      <div style={{ position:'absolute', left:16, right:16, bottom:14, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <span style={{ fontSize:10.5, opacity:.82 }}>{card.tagline}</span>
        <span style={{ fontSize:11, fontWeight:700, fontStyle:'italic', opacity:.9 }}>{card.net}</span>
      </div>
    </div>
  );
}

function Stat({ label, value, sub, accent }) {
  return (
    <div style={{ flex:1 }}>
      <div className="eyebrow" style={{ marginBottom:6 }}>{label}</div>
      <div className="serif tnum" style={{ fontSize:23, color:accent||'var(--text)', lineHeight:1 }}>{value}</div>
      {sub && <div style={{ fontSize:11, color:'var(--dim)', marginTop:5 }}>{sub}</div>}
    </div>
  );
}

function SectionTitle({ children, action, onAction }) {
  return (
    <div className="row" style={{ justifyContent:'space-between', margin:'2px 2px 12px' }}>
      <div style={{ fontSize:15.5, fontWeight:700, letterSpacing:'-.01em', whiteSpace:'nowrap' }}>{children}</div>
      {action && <button onClick={onAction} style={{ background:'none', border:0, color:'var(--gold)', fontSize:12.5, fontWeight:600, cursor:'pointer', display:'flex', alignItems:'center', gap:3, fontFamily:'var(--font-sans)' }}>{action}<Icon name="chevR" size={13} color="var(--gold)"/></button>}
    </div>
  );
}

// post-FIRE decumulation chart: median drawdown curve + sequence-risk fan + depletion marker
function DrawdownChart({ med, hi, lo, depleteAge, retireAge, endAge, w = 300, h = 152 }) {
  const top = 12;
  const maxV = Math.max(hi.s[hi.s.length-1].v, med.s[0].v, ...med.s.map(p=>p.v)) || 1;
  const X = (age) => ((age - retireAge) / (endAge - retireAge)) * w;
  const Y = (v) => h - top - (v / maxV) * (h - top - 16);
  const zeroY = Y(0);
  const path = (s) => s.map((p,i)=>(i?'L':'M')+X(p.age).toFixed(1)+' '+Y(p.v).toFixed(1)).join(' ');
  const medLine = path(med.s);
  const band = path(hi.s) + ' ' + lo.s.slice().reverse().map(p=>'L'+X(p.age).toFixed(1)+' '+Y(p.v).toFixed(1)).join(' ') + ' Z';
  const last = med.s[med.s.length-1];
  const medArea = medLine + ` L${X(last.age).toFixed(1)} ${zeroY} L0 ${zeroY} Z`;
  const dep = depleteAge;
  const ticks = [retireAge, Math.round((retireAge+endAge)/2), endAge];
  return (
    <svg width={w} height={h} style={{ display:'block', overflow:'visible' }}>
      <defs><linearGradient id="ddGrad" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0" stopColor="var(--gold)" stopOpacity="0.32"/>
        <stop offset="1" stopColor="var(--gold)" stopOpacity="0"/>
      </linearGradient></defs>
      {/* zero baseline */}
      <line x1="0" y1={zeroY} x2={w} y2={zeroY} stroke="var(--line-2)" strokeWidth="1"/>
      {/* sequence-risk fan */}
      <path d={band} fill="var(--gold)" opacity="0.08"/>
      {/* median area + line */}
      <path d={medArea} fill="url(#ddGrad)"/>
      <path d={medLine} fill="none" stroke="var(--gold)" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
      {/* depletion marker (if bad path or median runs dry) */}
      {dep != null && (
        <>
          <line x1={X(dep)} y1={top} x2={X(dep)} y2={zeroY} stroke="var(--red)" strokeWidth="1.2" strokeDasharray="3 3" opacity="0.8"/>
          <circle cx={X(dep)} cy={zeroY} r="4" fill="var(--red)" stroke="var(--bg)" strokeWidth="2"/>
        </>
      )}
      {/* end marker */}
      <circle cx={X(last.age)} cy={Y(last.v)} r="4" fill="var(--gold)" stroke="var(--bg)" strokeWidth="2"/>
      {/* age ticks */}
      {ticks.map((t,i)=>(
        <text key={i} x={i===0?2:i===2?w-2:X(t)} y={h-1} textAnchor={i===0?'start':i===2?'end':'middle'}
          fontSize="9.5" fill="var(--faint)" fontFamily="var(--font-mono)">{t}</text>
      ))}
    </svg>
  );
}

Object.assign(window, { Sparkline, Ring, ProjectionChart, SegmentBar, Donut, CreditCardTile, Stat, SectionTitle, DrawdownChart });
