/* ===== Presentation mode (6 fullscreen slides) ===== */
const { useState:useStatePr } = React;

// faux QR
const FauxQR = ({size=150, seed=7}) => {
  const n=21; let x=seed*9301+49297;
  const rnd=()=>{ x=(x*9301+49297)%233280; return x/233280; };
  const cells=[];
  for(let r=0;r<n;r++)for(let c=0;c<n;c++){
    const finder=(r<7&&c<7)||(r<7&&c>=n-7)||(r>=n-7&&c<7);
    if(finder)continue;
    if(rnd()>0.55) cells.push([r,c]);
  }
  const u=size/n;
  const Finder=({px,py})=>(<g>
    <rect x={px} y={py} width={u*7} height={u*7} fill="#0a1430"/>
    <rect x={px+u} y={py+u} width={u*5} height={u*5} fill="#fff"/>
    <rect x={px+u*2} y={py+u*2} width={u*3} height={u*3} fill="#0a1430"/>
  </g>);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{borderRadius:12,background:'#fff'}}>
      {cells.map(([r,c],i)=>(<rect key={i} x={c*u} y={r*u} width={u} height={u} fill="#0a1430"/>))}
      <Finder px={0} py={0}/><Finder px={(n-7)*u} py={0}/><Finder px={0} py={(n-7)*u}/>
    </svg>
  );
};

const Presentation = ({go, back, params, toast}) => {
  const c=CUSTOMERS.find(x=>x.id===params.id);
  const py=pyramidFor(c);
  const [i,setI]=useStatePr(0);
  const [shareOpen,setShare]=useStatePr(false);
  const N=6;
  const go2=n=>setI(Math.max(0,Math.min(N-1,n)));

  const Dot=({on})=>(<span style={{width:on?22:7,height:7,borderRadius:7,background:on?'var(--gold)':'rgba(255,255,255,.3)',transition:'.3s'}}/>);
  const slideWrap=(children,key)=>(<div key={key} className="present-slide" style={{padding:'70px 44px 120px'}}><div className="fade-in" style={{height:'100%',display:'flex',flexDirection:'column'}}>{children}</div></div>);

  const catRow=(cat)=>{const has=(c.coverage[cat.key]||0)>0;return(
    <div key={cat.key} className="flexrow" style={{gap:14,padding:'14px 16px',borderRadius:16,background:has?'rgba(34,197,94,.12)':'rgba(251,191,36,.14)',marginBottom:10}}>
      <div style={{width:42,height:42,borderRadius:12,background:has?'rgba(34,197,94,.25)':'rgba(251,191,36,.25)',display:'flex',alignItems:'center',justifyContent:'center'}}><Icon name={cat.icon} size={22} c={has?'#4ade80':'var(--gold)'}/></div>
      <div style={{flex:1}}><div style={{fontSize:17,fontWeight:700,color:'#fff'}}>{cat.name}</div><div style={{fontSize:13,color:'rgba(255,255,255,.6)'}}>{has?THBshort(c.coverage[cat.key]):'ยังไม่มีความคุ้มครอง'}</div></div>
      {has?<Icon name="checkCircle" size={24} c="#4ade80"/>:<span style={{fontSize:13,fontWeight:700,color:'var(--gold)'}}>ควรเสริม</span>}
    </div>
  );};

  const Heading=({tag,title,sub,color='var(--gold)'})=>(
    <div style={{marginBottom:26}}>
      <span style={{fontSize:14,fontWeight:700,color,letterSpacing:'2px',textTransform:'uppercase'}}>{tag}</span>
      <div style={{fontSize:34,fontWeight:800,color:'#fff',marginTop:8,letterSpacing:'-.02em',lineHeight:1.15}}>{title}</div>
      {sub && <div style={{fontSize:16,color:'rgba(255,255,255,.7)',marginTop:8,lineHeight:1.5}}>{sub}</div>}
    </div>
  );

  const slides=[
    // 1 pyramid
    slideWrap(<>
      <Heading tag="Financial Pyramid" title={`พีระมิดการเงินของ\n${c.name}`} sub="ภาพรวมความมั่นคงทางการเงินใน 4 ชั้น"/>
      <div style={{flex:1,display:'flex',alignItems:'center',justifyContent:'center'}}><div style={{width:300}}><PyramidSVG data={py} w={340} h={320}/></div></div>
      <div className="flexrow" style={{justifyContent:'center',gap:8,color:'#fff'}}><span style={{fontSize:15,color:'rgba(255,255,255,.7)'}}>คะแนนรวม</span><b style={{fontSize:26,color:'var(--gold)'}}>{py.score}</b><span style={{color:'rgba(255,255,255,.5)'}}>/100</span></div>
    </>,0),
    // 2 foundation
    slideWrap(<>
      <Heading tag="ชั้นที่ 1 · Foundation" title="ฐาน — ความคุ้มครอง" sub="ปกป้องครอบครัวจากความเสี่ยงก่อนสร้างความมั่งคั่ง"/>
      <div style={{flex:1,overflowY:'auto'}}>{CATS.map(catRow)}</div>
    </>,1),
    // 3 saving
    slideWrap(<>
      <Heading tag="ชั้นที่ 2 · Saving" title="ออม — เป้าหมายชีวิต" color="#fbbf24"/>
      <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'center',gap:18}}>
        {[{t:'เงินสำรองฉุกเฉิน',v:'6 เดือน',p:70},{t:'ทุนการศึกษาบุตร',v:THBshort(2000000),p:40},{t:'เงินเกษียณ (เป้า '+THBshort(6000000)+')',v:py.save+'%',p:py.save}].map((g,k)=>(
          <div key={k}>
            <div className="flexrow" style={{justifyContent:'space-between',marginBottom:9}}><span style={{fontSize:18,fontWeight:700,color:'#fff'}}>{g.t}</span><b style={{color:'var(--gold)',fontSize:17}}>{g.v}</b></div>
            <div style={{height:12,borderRadius:99,background:'rgba(255,255,255,.12)',overflow:'hidden'}}><div style={{height:'100%',width:g.p+'%',borderRadius:99,background:'linear-gradient(90deg,#fbbf24,#f59e0b)'}}/></div>
          </div>
        ))}
      </div>
    </>,2),
    // 4 investment
    slideWrap(<>
      <Heading tag="ชั้นที่ 3 · Investment" title="ลงทุน — พอร์ตของคุณ"/>
      <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'center',alignItems:'center',gap:26}}>
        <Ring pct={py.invest} size={210} stroke={20} color="var(--gold)" track="rgba(255,255,255,.12)">
          <div style={{fontSize:46,fontWeight:800,color:'#fff'}}>{py.invest}%</div>
          <div style={{fontSize:14,color:'rgba(255,255,255,.6)'}}>กระจายความเสี่ยง</div>
        </Ring>
        <div className="flexrow" style={{gap:10,flexWrap:'wrap',justifyContent:'center'}}>
          {[['ตราสารหนี้','40%'],['หุ้น/กองทุน','35%'],['ยูนิตลิงค์','25%']].map(([a,b])=>(<span key={a} style={{padding:'10px 18px',borderRadius:99,background:'rgba(255,255,255,.1)',color:'#fff',fontSize:15,fontWeight:600}}>{a} <b style={{color:'var(--gold)'}}>{b}</b></span>))}
        </div>
      </div>
    </>,3),
    // 5 legacy
    slideWrap(<>
      <Heading tag="ชั้นที่ 4 · Legacy" title="มรดก — ส่งต่อความมั่งคั่ง"/>
      <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'center',gap:16}}>
        {[{i:'crown',t:'วางแผนมรดก',s:py.legacy>=40?'มีแผนเบื้องต้นแล้ว':'ยังไม่มีแผน — แนะนำเริ่มวางแผน'},{i:'shieldCheck',t:'ประกันเพื่อมรดก',s:'สร้างมรดกปลอดภาษีให้ทายาท'},{i:'doc',t:'พินัยกรรม',s:'ระบุเจตนาการส่งต่อชัดเจน'}].map((r,k)=>(
          <div key={k} className="flexrow" style={{gap:16,padding:'18px 20px',borderRadius:18,background:'rgba(255,255,255,.07)'}}>
            <div style={{width:48,height:48,borderRadius:13,background:'rgba(251,191,36,.2)',display:'flex',alignItems:'center',justifyContent:'center'}}><Icon name={r.i} size={24} c="var(--gold)"/></div>
            <div><div style={{fontSize:18,fontWeight:700,color:'#fff'}}>{r.t}</div><div style={{fontSize:14,color:'rgba(255,255,255,.65)',marginTop:2}}>{r.s}</div></div>
          </div>
        ))}
      </div>
    </>,4),
    // 6 summary
    slideWrap(<>
      <Heading tag="สรุป" title="ก้าวต่อไปของคุณ"/>
      <div style={{flex:1,display:'flex',flexDirection:'column',justifyContent:'center'}}>
        <div style={{textAlign:'center',marginBottom:24}}>
          <div style={{fontSize:15,color:'rgba(255,255,255,.7)'}}>คะแนนสุขภาพการเงิน</div>
          <div style={{fontSize:64,fontWeight:800,color:'#fff',lineHeight:1}}>{py.score}<span style={{fontSize:24,color:'var(--gold)'}}>/100</span></div>
        </div>
        <div className="stack" style={{gap:12}}>
          {(gaps(c).length?[`เสริมความคุ้มครองที่ขาด ${gaps(c).length} หมวด`]:['รักษาความคุ้มครองให้ครบถ้วน']).concat(['ตั้งเป้าออมเงินเกษียณให้ถึง 100%','เริ่มวางแผนส่งต่อมรดก']).map((t,k)=>(
            <div key={k} className="flexrow" style={{gap:13,padding:'15px 18px',borderRadius:14,background:'rgba(255,255,255,.08)'}}>
              <span style={{width:30,height:30,borderRadius:99,background:'var(--gold)',color:'#5b3d05',display:'flex',alignItems:'center',justifyContent:'center',fontWeight:800,fontSize:15}}>{k+1}</span>
              <span style={{fontSize:16,color:'#fff',fontWeight:600}}>{t}</span>
            </div>
          ))}
        </div>
        <button className="btn btn-gold block btn-lg" style={{marginTop:26}} onClick={()=>setShare(true)}><Icon name="send" size={21}/> ส่งลิงก์ให้ลูกค้า / สแกน QR</button>
      </div>
    </>,5),
  ];

  return (
    <div className="present">
      <div style={{position:'absolute',inset:0,background:'radial-gradient(900px 500px at 80% -5%, #1e3a8a 0%, #0a1430 60%)'}}/>
      {/* progress dots */}
      <div style={{position:'absolute',top:30,left:0,right:0,display:'flex',justifyContent:'center',gap:7,zIndex:3}}>
        {Array.from({length:N}).map((_,k)=>(<Dot key={k} on={k===i}/>))}
      </div>
      <button className="iconbtn ghost" style={{position:'absolute',top:22,right:22,zIndex:3,color:'#fff'}} onClick={back}><Icon name="close" size={26}/></button>
      <div style={{position:'absolute',inset:0,zIndex:2}}>{slides[i]}</div>
      {/* nav */}
      <div style={{position:'absolute',bottom:34,left:0,right:0,display:'flex',alignItems:'center',justifyContent:'space-between',padding:'0 30px',zIndex:3}}>
        <button className="btn" style={{background:'rgba(255,255,255,.12)',color:'#fff',width:58,padding:0,opacity:i===0?.4:1}} onClick={()=>go2(i-1)} disabled={i===0}><Icon name="chevL" size={24}/></button>
        <span style={{color:'rgba(255,255,255,.7)',fontSize:15,fontWeight:600}}>{i+1} / {N}</span>
        {i<N-1
          ? <button className="btn btn-gold" style={{width:58,padding:0}} onClick={()=>go2(i+1)}><Icon name="chevR" size={24}/></button>
          : <button className="btn btn-gold" style={{padding:'0 20px'}} onClick={()=>setShare(true)}><Icon name="qr" size={20}/></button>}
      </div>

      {shareOpen && (
        <div className="scrim" style={{position:'absolute'}} onClick={()=>setShare(false)}>
          <div className="sheet slide-up" onClick={e=>e.stopPropagation()} style={{textAlign:'center'}}>
            <div className="grab"/>
            <div style={{fontSize:20,fontWeight:800}}>ส่งให้ {c.name}</div>
            <div className="muted" style={{fontSize:14,margin:'6px 0 20px'}}>ลูกค้าสแกนเพื่อเปิดมุมมองของตนเอง</div>
            <div style={{display:'flex',justifyContent:'center',marginBottom:18}}><div style={{padding:16,background:'#fff',borderRadius:20,boxShadow:'var(--sh-1)'}}><FauxQR size={180} seed={c.id.charCodeAt(1)*7}/></div></div>
            <div className="chip gray" style={{height:38,fontSize:13.5,marginBottom:18}}><Icon name="link" size={15}/> covera.co.th/v/{c.id}-8f2a</div>
            <button className="btn btn-primary block" onClick={()=>{setShare(false);go('customerView',{id:c.id});}}><Icon name="eye" size={20}/> เปิดมุมมองลูกค้า</button>
            <button className="btn btn-ghost block" style={{marginTop:10}} onClick={()=>{setShare(false);toast('คัดลอกลิงก์แล้ว');}}>คัดลอกลิงก์</button>
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { FauxQR, Presentation });
