/* ===== Central reusable AIA-style financial pyramid ===== */
const { useState:useStateFP, useRef:useRefFP, useEffect:useEffectFP } = React;

// geometry: half-width fraction at each horizontal boundary (0=apex top .. 4=base bottom)
const FP_APEX = 0.12, FP_BASE = 0.50, FP_N = 4;
const fpHalf = i => FP_APEX + (FP_BASE - FP_APEX) * (i / FP_N);
const FP_BANDS = Array.from({length:FP_N}, (_,i)=>{
  const tH = fpHalf(i), bH = fpHalf(i+1);
  return {
    tH, bH,
    clip:`polygon(${(0.5-tH)*100}% 0, ${(0.5+tH)*100}% 0, ${(0.5+bH)*100}% 100%, ${(0.5-bH)*100}% 100%)`,
    // safe content width = a bit under the band's TOP edge so multi-line text never clips
    safeW: (2*tH*0.96*100),
  };
});

// the rotated "Tax Planning" diagonal axis — measured against the live pyramid box
const FpTaxAxis = ({ labelBg }) => {
  // placed by parent via absolute; here we just render line + label
  return null;
};

const FinancialPyramid = ({ c, vals, variant='full', onLayer, active, scale=1 }) => {
  const v = vals || pyramidVals(c);
  const layers = PYRAMID_LAYERS;                       // 0=apex(legacy) .. 3=base
  const hasProducts = variant!=='mini';
  const onDark = variant==='present';
  const bandH = ({full:96, present:104, view:84, mini:42}[variant]) * scale;
  const gap = variant==='mini' ? 4 : 6;
  const stackH = bandH*FP_N + gap*(FP_N-1);

  const stackRef = useRefFP(null);
  const [axis,setAxis] = useStateFP({deg:-60, len:200});
  useEffectFP(()=>{
    const el = stackRef.current; if(!el) return;
    const measure = ()=>{
      const W = el.offsetWidth, H = el.offsetHeight;
      const apexX = (0.5 - FP_APEX) * W;                // top-left silhouette x
      const deg = Math.atan2(-H, apexX) * 180/Math.PI;
      const len = Math.hypot(apexX, H) * 0.96;
      setAxis({deg, len});
    };
    measure();
    const ro = new ResizeObserver(measure); ro.observe(el);
    return ()=> ro.disconnect();
  },[bandH, variant]);

  const fz = k => Math.round(k*scale);

  const bandContent = (l, i) => {
    const mw = FP_BANDS[i].safeW + '%';
    if(variant==='mini'){
      const label = l.en ? l.en : (l.key==='save'?'ออม':'ฐาน');
      const thb = l.en==='Legacy'?'ส่งต่อความมั่นคง':l.key==='save'?'เป้าหมายชีวิต':l.key==='base'?'ความคุ้มครอง':'';
      return (
        <div style={{maxWidth:mw,margin:'0 auto'}}>
          <div className="fp-en" style={{fontSize:fz(12.5)}}>{label}</div>
          {thb && <div className="fp-th" style={{fontSize:fz(9.5)}}>{thb}</div>}
        </div>
      );
    }
    if(l.split){
      const isBase = l.key==='base';
      return (
        <div className="fp-split" style={{maxWidth:mw,margin:'0 auto'}}>
          <span className="fp-div"/>
          {['left','right'].map(side=>{
            const s = l.split[side];
            return (
              <div key={side}>
                <div className="fp-htitle" style={{fontSize:fz(isBase?12.5:12.5)}}>{s.title}</div>
                {s.th && <div className="fp-hsub" style={{fontSize:fz(10.5)}}>{s.th}{s.sub?' '+s.sub:''}</div>}
                <div className="fp-items" style={{fontSize:fz(9.8)}}>{s.items.join(' · ')}</div>
              </div>
            );
          })}
        </div>
      );
    }
    return (
      <div style={{maxWidth:mw,margin:'0 auto'}}>
        <div className="fp-en" style={{fontSize:fz(15)}}>{l.en}</div>
        <div className="fp-th" style={{fontSize:fz(i===0?11.5:11)}}>{l.th}</div>
      </div>
    );
  };

  const cls = ['fp', variant, hasProducts?'has-products':'', onDark?'on-dark':''].filter(Boolean).join(' ');

  return (
    <div className={cls}>
      <div className="fp-grid">
        {/* pyramid */}
        <div className="fp-stack" ref={stackRef} style={{height:stackH}}>
          {layers.map((l,i)=>{
            const pct = v[l.key]||0;
            const light = l.text!=='#ffffff';
            return (
              <button key={l.key}
                className={'fp-band'+(light?' light':'')+(active===l.key?' active':'')}
                style={{ clipPath:FP_BANDS[i].clip, background:l.color, color:l.text,
                  height:bandH, marginBottom:i<FP_N-1?gap:0, cursor:onLayer?'pointer':'default' }}
                onClick={()=>onLayer&&onLayer(l)}>
                <div className="fp-band-in">{bandContent(l,i)}</div>
                {variant!=='mini' && <span className="fp-pct">{pct}%</span>}
                <span className="fp-gauge" style={{width:pct+'%'}}/>
              </button>
            );
          })}
          {/* Tax Planning diagonal */}
          {variant!=='mini' && (
          <div className="fp-tax" style={{transform:`rotate(${axis.deg}deg)`, width:axis.len}}>
            <span className="fp-tax-line" style={{flex:1}}/>
            <span className="fp-tax-label" style={{fontSize:fz(13), background: onDark?'#15275a':'var(--surface)', padding:'0 8px'}}>Tax Planning · วางแผนภาษี</span>
            <span className="fp-tax-line" style={{flex:1}}/>
          </div>
          )}
        </div>

        {/* product lists aligned per band */}
        {hasProducts && (
          <div className="fp-products" style={{minHeight:stackH}}>
            {layers.map((l)=>(
              <div key={l.key} className="fp-prow">
                <div className="fp-plabel">
                  <span style={{width:9,height:9,borderRadius:3,background:l.color,flex:'0 0 auto'}}/>
                  {l.en || (l.key==='save'?'ออม · เป้าหมายชีวิต':'ฐาน · ความคุ้มครอง')}
                </div>
                {l.note && <div className="fp-pnote">{l.note}</div>}
                <div className="fp-chips">
                  {l.products.map((p,k)=>(<span key={k} className="fp-chip">{p}</span>))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { FinancialPyramid, FP_BANDS, FP_BANDS_N:FP_N });
