/* ===== Dashboard — landing home after login (agent overview) ===== */
const { useState:useStateDash } = React;

// KPI card with optional sub-line + click affordance
const DashKPI = ({icon, val, label, sub, color, bg, onClick}) => (
  <button className="kpi" style={{textAlign:'left',cursor:onClick?'pointer':'default',border:'1px solid var(--line)'}} onClick={onClick}>
    <div className="flexrow">
      <div className="k-ico" style={{background:bg, color}}><Icon name={icon} size={22}/></div>
      <div className="spacer"/>
      {onClick && <Icon name="chevR" size={18} c="var(--muted-2)"/>}
    </div>
    <div className="k-val">{val}</div>
    <div className="k-label">{label}{sub && <span style={{color,fontWeight:700}}> · {sub}</span>}</div>
  </button>
);

const DashboardHome = ({go, setTab}) => {
  const events = window.CAL_EVENTS || {};
  const taskIcon = window.TASK_ICON || {meet:'calendar',call:'phone',doc:'doc',due:'alert'};
  const today = window.CAL_TODAY || {y:2568,m:6,d:2};
  const months = window.TH_MO || ['มกราคม','กุมภาพันธ์','มีนาคม','เมษายน','พฤษภาคม','มิถุนายน','กรกฎาคม','สิงหาคม','กันยายน','ตุลาคม','พฤศจิกายน','ธันวาคม'];
  const todayKey = `${today.y}-${today.m}-${today.d}`;
  const todayTasks = events[todayKey] || [];

  // KPIs
  const dueList = CUSTOMERS.filter(c=>c.tag==='ครบกำหนด');
  const followList = CUSTOMERS.filter(c=>c.tag==='ค้างติดตาม');
  const actionList = CUSTOMERS.filter(c=>c.tag);
  const totalPrem = CUSTOMERS.reduce((s,c)=>s+c.policies.reduce((a,p)=>a+p.premium,0),0);
  const dueDays = Math.max(0, 15 - today.d); // ครบกำหนดชำระ 15 มิ.ย.
  const notifCount = 4;

  // featured customer for the mini pyramid (highest-priority: a due customer)
  const featured = dueList[0] || CUSTOMERS[0];

  return (
    <div className="screen">
      <StatusBar/>
      <div className="scroll">
        <div className="pad maxw" style={{paddingTop:18}}>
          {/* 1 — top bar */}
          <div className="flexrow" style={{gap:12}}>
            <div>
              <div style={{fontSize:14,color:'var(--muted)',fontWeight:600}}>สวัสดีตอนเช้า 👋</div>
              <div style={{fontSize:26,fontWeight:800,letterSpacing:'-.02em',marginTop:2}}>{AGENT.name}</div>
              <div style={{fontSize:13,color:'var(--muted)',marginTop:3}}>{today.d} {months[today.m-1]} {today.y} · {AGENT.title}</div>
            </div>
            <div className="spacer"/>
            <button className="iconbtn" onClick={()=>go('notifications')} style={{position:'relative'}}>
              <Icon name="bell" size={23}/>
              {notifCount>0 && <span style={{position:'absolute',top:-4,right:-4,minWidth:20,height:20,padding:'0 5px',borderRadius:99,background:'var(--danger)',color:'#fff',fontSize:11.5,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center',border:'2px solid #fff'}}>{notifCount}</span>}
            </button>
          </div>

          {/* 2 — KPI row */}
          <div className="grid2 stagger" style={{gridTemplateColumns:'repeat(4,1fr)',marginTop:20}}>
            <DashKPI icon="users" val={CUSTOMERS.length} label="ลูกค้าทั้งหมด" color="#1e40af" bg="var(--navy-50)" onClick={()=>setTab('customers')}/>
            <DashKPI icon="clock" val={dueList.length} label="ครบกำหนดชำระ" sub={`ภายใน ${dueDays} วัน`} color="#f59e0b" bg="var(--warn-50)" onClick={()=>go('renewal',{})}/>
            <DashKPI icon="alert" val={followList.length} label="ที่ต้องติดตาม" color="#dc2626" bg="var(--danger-50)" onClick={()=>go('pipeline',{})}/>
            <DashKPI icon="wallet" val={THBshort(totalPrem)} label="เบี้ยรวมต่อปี" color="#0d9488" bg="#effdfa" onClick={()=>setTab('reports')}/>
          </div>

          {/* body: two columns */}
          <div className="cols c-2" style={{marginTop:20}}>
            {/* left column */}
            <div className="stack" style={{gap:16}}>
              {/* 3 — mini financial pyramid */}
              <div className="card" style={{paddingBottom:16}}>
                <div className="flexrow" style={{marginBottom:4}}>
                  <div>
                    <div style={{fontSize:18,fontWeight:700}}>พีระมิดการเงิน</div>
                    <div className="muted" style={{fontSize:12.5,marginTop:1}}>ลูกค้าแนะนำให้ทบทวน · {featured.name}</div>
                  </div>
                  <div className="spacer"/>
                  <button className="chip" onClick={()=>go('triangle',{cid:featured.id})}>เปิดเต็ม <Icon name="chevR" size={13}/></button>
                </div>
                <FinancialPyramid c={featured} variant="mini" onLayer={()=>go('triangle',{cid:featured.id})}/>
                <div className="flexrow" style={{marginTop:14,gap:8}}>
                  <span className="muted" style={{fontSize:12.5}}>คะแนนสุขภาพการเงิน</span>
                  <div className="spacer"/>
                  <b className="navy-t" style={{fontSize:20}}>{pyramidScore(featured)}</b><span className="muted" style={{fontWeight:700,fontSize:13}}>/100</span>
                  <button className="btn btn-soft btn-sm" style={{marginLeft:8}} onClick={()=>go('planner')}><Icon name="target" size={16}/> เครื่องมือวางแผน</button>
                </div>
              </div>

              {/* 4 — today's tasks */}
              <div className="card" style={{padding:'8px 20px 14px'}}>
                <div className="flexrow" style={{padding:'10px 2px 4px'}}>
                  <div style={{fontSize:18,fontWeight:700}}>งาน & นัดหมายวันนี้</div>
                  <div className="spacer"/>
                  <button className="chip" onClick={()=>go('calendar',{})}>ดูปฏิทิน <Icon name="chevR" size={13}/></button>
                </div>
                <div style={{borderTop:'1px solid var(--line-2)',marginTop:6}}>
                  {todayTasks.map((e,i)=>(
                    <button key={i} className="row" style={{width:'100%',textAlign:'left',alignItems:'flex-start',padding:'13px 0'}}
                      onClick={()=>e.cid?go('customer',{id:e.cid}):go('calendar',{})}>
                      <div style={{width:54,fontSize:13.5,fontWeight:700,color:'var(--ink-2)',paddingTop:8}}>{e.t}</div>
                      <div style={{width:40,height:40,borderRadius:12,background:e.c+'18',color:e.c,display:'flex',alignItems:'center',justifyContent:'center',flex:'0 0 auto'}}><Icon name={taskIcon[e.type]} size={20}/></div>
                      <div className="r-main" style={{paddingTop:1}}>
                        <div className="r-name" style={{fontSize:15}}>{e.title}</div>
                        <div className="r-sub"><Icon name="user" size={12} style={{verticalAlign:'-2px'}}/> {e.who} · {e.todo}</div>
                      </div>
                      <Icon name="chevR" size={18} c="var(--muted-2)" style={{marginTop:10}}/>
                    </button>
                  ))}
                  {todayTasks.length===0 && <div className="center muted" style={{padding:'26px 0'}}>วันนี้ไม่มีนัดหมาย 🎉</div>}
                </div>
                <button className="btn btn-outline block" style={{marginTop:10}} onClick={()=>go('calendar',{})}><Icon name="plus" size={18}/> เพิ่มนัดหมาย</button>
              </div>
            </div>

            {/* right rail — 5 customers needing action */}
            <div className="stack" style={{gap:16}}>
              <div className="card" style={{padding:'8px 18px 12px'}}>
                <div className="flexrow" style={{padding:'10px 2px 8px'}}>
                  <div style={{fontSize:16.5,fontWeight:700}}>ลูกค้าที่ต้องดำเนินการ</div>
                  <div className="spacer"/>
                  <span className="chip warn" style={{height:26}}>{actionList.length}</span>
                </div>
                <div style={{borderTop:'1px solid var(--line-2)'}}>
                  {actionList.map(c=>(
                    <div key={c.id} style={{padding:'13px 0',borderBottom:'1px solid var(--line-2)'}}>
                      <button className="flexrow" style={{width:'100%',textAlign:'left',gap:11,background:'none'}} onClick={()=>go('customer',{id:c.id})}>
                        <Avatar name={c.name} color={c.avatar} size="sm"/>
                        <div className="r-main" style={{flex:1,minWidth:0}}>
                          <div className="r-name" style={{fontSize:15}}>{c.name}</div>
                          <div className="r-sub">{c.job} · {c.phone}</div>
                        </div>
                        <span className={"chip "+(c.tag==='ครบกำหนด'?'warn':'danger')} style={{height:26}}>{c.tag}</span>
                      </button>
                      <div className="grid2" style={{gap:8,marginTop:9}}>
                        <a href={`tel:${c.phone.replace(/-/g,'')}`} className="btn btn-soft btn-sm" style={{textDecoration:'none'}}><Icon name="phone" size={16}/> โทร</a>
                        <button className="btn btn-outline btn-sm" onClick={()=>go('customer',{id:c.id})}><Icon name="user" size={16}/> ดูโปรไฟล์</button>
                      </div>
                    </div>
                  ))}
                  {actionList.length===0 && <div className="muted center" style={{padding:'18px 0',fontSize:13.5}}>ไม่มีงานค้าง 🎉</div>}
                </div>
                <button className="btn btn-ghost block" style={{marginTop:10}} onClick={()=>setTab('customers')}>ดูลูกค้าทั้งหมด <Icon name="chevR" size={16}/></button>
              </div>

              {/* quick add */}
              <button className="navy-panel" style={{textAlign:'left',border:'none'}} onClick={()=>go('addCustomer')}>
                <div className="glow"/>
                <div style={{width:44,height:44,borderRadius:13,background:'rgba(255,255,255,.16)',display:'flex',alignItems:'center',justifyContent:'center'}}><Icon name="plusUser" size={24} c="#fff"/></div>
                <div style={{fontSize:18,fontWeight:700,marginTop:14}}>เพิ่มลูกค้า</div>
                <div style={{fontSize:12.5,color:'rgba(255,255,255,.7)',marginTop:2}}>พร้อมขอความยินยอม PDPA</div>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { DashboardHome, DashKPI });
