/* ===== Covera shared UI ===== */
const { useState, useRef, useEffect } = React;

const StatusBar = ({onNavy}) => (
  <div className={"statusbar"+(onNavy?" on-navy":"")}/>
);

const AppBar = ({title, sub, onBack, right, navy}) => (
  <div className="appbar">
    {onBack && <button className="iconbtn" onClick={onBack}><Icon name="arrowL" /></button>}
    <div style={{minWidth:0}}>
      <div className="title" style={navy?{color:'#fff'}:null}>{title}</div>
      {sub && <div className="sub" style={navy?{color:'rgba(255,255,255,.7)'}:null}>{sub}</div>}
    </div>
    <div className="spacer" />
    {right}
  </div>
);

const BottomNav = ({tab, onTab}) => {
  const tabs=[
    {k:'customers', label:'ลูกค้า', icon:'users'},
    {k:'policies', label:'กรมธรรม์', icon:'docStack'},
    {k:'reports', label:'รายงาน', icon:'chartBar'},
    {k:'me', label:'ฉัน', icon:'user'},
  ];
  return (
    <div className="bottomnav">
      {tabs.map(t=>(
        <button key={t.k} className={"navtab"+(tab===t.k?" active":"")} onClick={()=>onTab(t.k)}>
          <Icon name={t.icon} size={26} sw={tab===t.k?2.1:1.8} />
          <span className="nt-label">{t.label}</span>
        </button>
      ))}
    </div>
  );
};

const Avatar = ({name, color, size}) => (
  <div className={"avatar"+(size?" "+size:"")} style={{background:`linear-gradient(150deg, ${color}, ${color}cc)`}}>
    {initials(name)}
  </div>
);

const KPI = ({icon, val, label, color, bg}) => (
  <div className="kpi">
    <div className="k-ico" style={{background:bg, color}}><Icon name={icon} size={23} /></div>
    <div className="k-val" style={{color:'var(--ink)'}}>{val}</div>
    <div className="k-label">{label}</div>
  </div>
);

// circular coverage ring
const Ring = ({pct, size=150, stroke=14, color='var(--navy-700)', track='#e7ebf1', children}) => {
  const r=(size-stroke)/2, c=2*Math.PI*r, off=c*(1-pct/100);
  return (
    <div style={{width:size,height:size,position:'relative'}}>
      <svg width={size} height={size} style={{transform:'rotate(-90deg)'}}>
        <circle cx={size/2} cy={size/2} r={r} stroke={track} strokeWidth={stroke} fill="none"/>
        <circle cx={size/2} cy={size/2} r={r} stroke={color} strokeWidth={stroke} fill="none"
          strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}
          style={{transition:'stroke-dashoffset 1s cubic-bezier(.4,0,.2,1)'}}/>
      </svg>
      <div style={{position:'absolute',inset:0,display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center'}}>
        {children}
      </div>
    </div>
  );
};

// CV timeline chart (premium accumulated vs surrender value)
const CVChart = ({data, w=560, h=210}) => {
  const pad={l:16,r:16,t:14,b:26};
  const maxV = Math.max(...data.map(d=>Math.max(d.paid,d.cv)))*1.08;
  const X = i => pad.l + (i/(data.length-1))*(w-pad.l-pad.r);
  const Y = v => pad.t + (1-v/maxV)*(h-pad.t-pad.b);
  const line = key => data.map((d,i)=>`${i===0?'M':'L'}${X(i).toFixed(1)},${Y(d[key]).toFixed(1)}`).join(' ');
  const area = key => `${line(key)} L${X(data.length-1)},${h-pad.b} L${X(0)},${h-pad.b} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" style={{display:'block'}}>
      <defs>
        <linearGradient id="cvg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#1e40af" stopOpacity=".22"/><stop offset="1" stopColor="#1e40af" stopOpacity="0"/></linearGradient>
      </defs>
      {[0,.5,1].map(g=>(<line key={g} x1={pad.l} x2={w-pad.r} y1={pad.t+g*(h-pad.t-pad.b)} y2={pad.t+g*(h-pad.t-pad.b)} stroke="#eef1f6" strokeWidth="1"/>))}
      <path d={area('cv')} fill="url(#cvg)"/>
      <path d={line('paid')} fill="none" stroke="#94a3b8" strokeWidth="2.4" strokeDasharray="5 5" strokeLinecap="round"/>
      <path d={line('cv')} fill="none" stroke="#1e40af" strokeWidth="3" strokeLinecap="round"/>
      {data.map((d,i)=> (i%Math.ceil(data.length/6)===0 || i===data.length-1) && (
        <text key={i} x={X(i)} y={h-8} fontSize="11" fill="#94a3b8" textAnchor="middle">ปี{2567-data.length+1+i-1+1>0?d.y:d.y}</text>
      ))}
      {(() => { const i=data.length-1; return <g><circle cx={X(i)} cy={Y(data[i].cv)} r="5" fill="#1e40af" stroke="#fff" strokeWidth="2.5"/></g>; })()}
    </svg>
  );
};

// signature pad
const SignaturePad = ({onChange, height=160}) => {
  const ref=useRef(null); const drawing=useRef(false); const [has,setHas]=useState(false);
  useEffect(()=>{
    const cv=ref.current; const dpr=window.devicePixelRatio||1;
    const rect=cv.getBoundingClientRect();
    cv.width=rect.width*dpr; cv.height=rect.height*dpr;
    const ctx=cv.getContext('2d'); ctx.scale(dpr,dpr);
    ctx.strokeStyle='#0f172a'; ctx.lineWidth=2.6; ctx.lineCap='round'; ctx.lineJoin='round';
    cv._ctx=ctx; cv._rect=rect;
  },[]);
  const pos=e=>{ const cv=ref.current; const r=cv.getBoundingClientRect(); const t=e.touches?e.touches[0]:e; return {x:t.clientX-r.left, y:t.clientY-r.top}; };
  const start=e=>{ e.preventDefault(); drawing.current=true; const p=pos(e); const ctx=ref.current._ctx; ctx.beginPath(); ctx.moveTo(p.x,p.y); };
  const move=e=>{ if(!drawing.current)return; e.preventDefault(); const p=pos(e); const ctx=ref.current._ctx; ctx.lineTo(p.x,p.y); ctx.stroke(); if(!has){setHas(true); onChange&&onChange(true);} };
  const end=()=>{ drawing.current=false; };
  const clear=()=>{ const cv=ref.current; cv._ctx.clearRect(0,0,cv.width,cv.height); setHas(false); onChange&&onChange(false); };
  return (
    <div>
      <div style={{position:'relative',border:'1.5px dashed var(--line)',borderRadius:16,background:'#fff',overflow:'hidden'}}>
        <canvas ref={ref} style={{width:'100%',height,display:'block',touchAction:'none'}}
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end}/>
        {!has && <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center',color:'var(--muted-2)',fontSize:15,pointerEvents:'none',gap:8}}><Icon name="edit" size={18}/> เซ็นชื่อด้วยนิ้วที่นี่</div>}
      </div>
      <div style={{display:'flex',justifyContent:'flex-end',marginTop:8}}>
        <button className="btn btn-ghost btn-sm" onClick={clear}><Icon name="refresh" size={16}/> ล้าง</button>
      </div>
    </div>
  );
};

const Toast = ({icon='checkCircle', children}) => (
  <div className="toast slide-up"><Icon name={icon} size={19} c="#4ade80"/>{children}</div>
);

const CompanyBadge = ({co, size=44}) => (
  <div style={{width:size,height:size,borderRadius:13,background:co.color,color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',fontWeight:700,fontSize:size<40?12:13,flex:'0 0 auto',letterSpacing:'-.02em'}}>
    {co.init}
  </div>
);

Object.assign(window, { StatusBar, AppBar, BottomNav, Avatar, KPI, Ring, CVChart, SignaturePad, Toast, CompanyBadge });
