/* ===== Setting (ตั้งค่า) — Product mgmt · Sync · Account ===== */
const { useState:useStateSet, useRef:useRefSet } = React;

// reusable toggle
const Switch = ({on, onClick, gold, disabled}) => (
  <button className={"switch"+(on?" on":"")+(gold?" gold":"")} disabled={disabled} onClick={onClick}><i/></button>
);

// seed products grouped by company (our agent = AIA / co3)
const SEED_PRODUCTS = [
  { id:'p1', co:'co3', name:'AIA Health Happy', type:'สุขภาพ', hi:'เหมาจ่ายสูงสุด 25 ล้าน/ปี', on:true,  show:true },
  { id:'p2', co:'co3', name:'AIA Issara Plus', type:'ตลอดชีพ', hi:'คุ้มครองชีวิตถึงอายุ 99 ปี', on:true,  show:true },
  { id:'p3', co:'co3', name:'AIA Annuity Fix 60/85', type:'บำนาญ', hi:'รับบำนาญ 15% ทุกปีหลังเกษียณ', on:true,  show:false },
  { id:'p4', co:'co3', name:'AIA Unit Linked', type:'ยูนิตลิงค์', hi:'ลงทุน + คุ้มครองในกรมธรรม์เดียว', on:true,  show:true },
  { id:'p5', co:'co3', name:'AIA CI SuperCare', type:'โรคร้ายแรง', hi:'คุ้มครอง 44 โรคร้ายแรง', on:false, show:false },
  { id:'p6', co:'co2', name:'D Health Plus', type:'สุขภาพ', hi:'เหมาจ่ายค่ารักษาพยาบาล', on:true,  show:true },
  { id:'p7', co:'co2', name:'เมืองไทย Smart Protection', type:'ตลอดชีพ', hi:'เบี้ยคงที่ คุ้มครองยาว', on:true,  show:false },
  { id:'p8', co:'co1', name:'ทีพี ออมทรัพย์ 10/5', type:'สะสมทรัพย์', hi:'ออม 5 ปี คุ้มครอง 10 ปี', on:true,  show:true },
  { id:'p9', co:'co4', name:'BLA Happy Saving', type:'สะสมทรัพย์', hi:'การันตีผลตอบแทนครบกำหนด', on:false, show:false },
];

// sync alerts from other agents
const SEED_SYNC = [
  { id:'s1', co:'co3', n:2, by:'พิมพ์ใจ (หัวหน้าทีม AIA)', when:'2 ชั่วโมงที่แล้ว',
    items:['AIA Health Happy (New Gen)','AIA Pension 90/60'] },
  { id:'s2', co:'co2', n:1, by:'ศุภชัย (ทีมเมืองไทย)', when:'เมื่อวาน',
    items:['เมืองไทย Legacy Plus'] },
];

const SettingScreen = ({go, setTab, toast}) => {
  const [tab,setT]=useStateSet('product');
  const TABS=[
    {k:'product', i:'docStack', label:'จัดการผลิตภัณฑ์'},
    {k:'sync',    i:'refresh',  label:'ซิงค์ผลิตภัณฑ์'},
    {k:'account', i:'user',     label:'บัญชี & ทั่วไป'},
  ];

  // shared state
  const [products,setProducts]=useStateSet(SEED_PRODUCTS);
  const [syncs,setSyncs]=useStateSet(SEED_SYNC);
  const syncCount=syncs.reduce((a,s)=>a+s.n,0);

  return (
    <div className="screen">
      <StatusBar/>
      <AppBar title="ตั้งค่า" sub="จัดการผลิตภัณฑ์ · ซิงค์ · บัญชี"
        right={<button className="iconbtn" onClick={()=>go('notifications')} style={{position:'relative'}}><Icon name="bell" size={23}/><span style={{position:'absolute',top:9,right:10,width:9,height:9,borderRadius:9,background:'var(--gold)',border:'2px solid #fff'}}/></button>}/>
      <div className="scroll">
        <div className="pad maxw" style={{paddingTop:4}}>
          {/* section tabs */}
          <div className="settabs" style={{marginBottom:18}}>
            {TABS.map(t=>(
              <button key={t.k} className={"t"+(tab===t.k?" on":"")} onClick={()=>setT(t.k)}>
                <Icon name={t.i} size={17}/> {t.label}
                {t.k==='sync' && syncCount>0 && <span style={{minWidth:18,height:18,padding:'0 5px',borderRadius:99,background:'var(--danger)',color:'#fff',fontSize:11,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center'}}>{syncCount}</span>}
              </button>
            ))}
          </div>

          {tab==='product' && <ProductSettings products={products} setProducts={setProducts} toast={toast}/>}
          {tab==='sync' && <SyncSettings syncs={syncs} setSyncs={setSyncs} setProducts={setProducts} toast={toast} goProduct={()=>setT('product')}/>}
          {tab==='account' && <AccountSettings go={go} toast={toast}/>}
          <div style={{height:8}}/>
        </div>
      </div>
    </div>
  );
};

/* ---------- Section 1: Product management ---------- */
const ProductSettings = ({products, setProducts, toast}) => {
  const usedCos = COMPANIES.filter(co=>products.some(p=>p.co===co.id));
  const [coId,setCoId]=useStateSet('co3');
  const [add,setAdd]=useStateSet(false);
  const co = COMPANIES.find(c=>c.id===coId);
  const list = products.filter(p=>p.co===coId);
  const set=(id,key)=>setProducts(ps=>ps.map(p=>{
    if(p.id!==id) return p;
    const nv={...p,[key]:!p[key]};
    if(key==='on' && !nv.on) nv.show=false;   // ปิดใช้ → ซ่อนด้วย
    return nv;
  }));
  const onCount=list.filter(p=>p.on).length;

  return (
    <div>
      {/* concept note */}
      <div className="card flat" style={{display:'flex',gap:11,alignItems:'center',background:'var(--navy-50)',marginBottom:16}}>
        <Icon name="info" size={19} c="var(--navy-800)"/>
        <div style={{fontSize:13,color:'var(--navy-800)',lineHeight:1.5}}>คุณเลือกเองได้ว่าจะ <b>ใช้</b> และ <b>โชว์</b> ผลิตภัณฑ์ตัวใดให้ลูกค้า — รองรับหลายบริษัทประกัน เลือก/เพิ่มทีละตัว</div>
      </div>

      {/* company selector (by ประกัน) */}
      <div className="flexrow" style={{marginBottom:10}}>
        <div style={{fontSize:13,fontWeight:700,color:'var(--muted)'}}>เลือกบริษัทประกัน</div>
      </div>
      <div className="chip-scroll" style={{paddingBottom:12}}>
        {usedCos.map(c=>{
          const n=products.filter(p=>p.co===c.id).length;
          const onN=products.filter(p=>p.co===c.id&&p.on).length;
          return (
            <button key={c.id} className="cobtn" onClick={()=>setCoId(c.id)}
              style={{display:'flex',alignItems:'center',gap:9,padding:'8px 14px 8px 8px',borderRadius:14,border:'1.5px solid '+(coId===c.id?'var(--navy-700)':'var(--line)'),background:coId===c.id?'var(--navy-50)':'var(--surface)',flex:'0 0 auto'}}>
              <CompanyBadge co={c} size={34}/>
              <div style={{textAlign:'left'}}>
                <div style={{fontSize:13.5,fontWeight:700,whiteSpace:'nowrap'}}>{c.name}</div>
                <div style={{fontSize:11.5,color:'var(--muted)'}}>{onN}/{n} ใช้งาน</div>
              </div>
            </button>
          );
        })}
      </div>

      {/* product list for selected company */}
      <div className="card" style={{padding:'6px 20px 14px'}}>
        <div className="flexrow" style={{padding:'12px 0 8px'}}>
          <CompanyBadge co={co} size={38}/>
          <div style={{marginLeft:11,flex:1}}>
            <div style={{fontSize:16.5,fontWeight:800}}>{co.name}</div>
            <div style={{fontSize:12.5,color:'var(--muted)'}}>{list.length} ผลิตภัณฑ์ · ใช้งาน {onCount}</div>
          </div>
          <button className="btn btn-primary btn-sm" onClick={()=>setAdd(true)}><Icon name="plus" size={17}/> เพิ่มผลิตภัณฑ์</button>
        </div>
        {/* column hints */}
        <div className="flexrow" style={{borderTop:'1px solid var(--line-2)',padding:'10px 0 6px',color:'var(--muted)',fontSize:12,fontWeight:700}}>
          <div style={{flex:1}}>ผลิตภัณฑ์</div>
          <div style={{width:70,textAlign:'center'}}>ใช้</div>
          <div style={{width:70,textAlign:'center'}}>โชว์</div>
        </div>
        <div>
          {list.map(p=>(
            <div key={p.id} className="flexrow" style={{padding:'14px 0',borderTop:'1px solid var(--line-2)',gap:10,opacity:p.on?1:.6}}>
              <div style={{flex:1,minWidth:0}}>
                <div className="flexrow" style={{gap:8}}>
                  <span style={{fontSize:15,fontWeight:700}}>{p.name}</span>
                  <span className="chip gray" style={{height:22,fontSize:11}}>{p.type}</span>
                </div>
                <div style={{fontSize:12.5,color:'var(--muted)',marginTop:3}}><Icon name="check" size={12} c="var(--ok)" style={{verticalAlign:'-1px'}}/> {p.hi}</div>
              </div>
              <div style={{width:70,display:'flex',justifyContent:'center'}}>
                <Switch on={p.on} onClick={()=>{set(p.id,'on');toast(p.on?'ปิดใช้ '+p.name:'เปิดใช้ '+p.name);}}/>
              </div>
              <div style={{width:70,display:'flex',justifyContent:'center'}}>
                <Switch on={p.show} gold disabled={!p.on} onClick={()=>{set(p.id,'show');toast(p.show?'ซ่อน '+p.name:'โชว์ '+p.name+' ให้ลูกค้า');}}/>
              </div>
            </div>
          ))}
          {list.length===0 && <div className="center muted" style={{padding:24}}>ยังไม่มีผลิตภัณฑ์ — กดเพิ่มผลิตภัณฑ์</div>}
        </div>
      </div>

      {add && <AddProductSheet co={co} onClose={()=>setAdd(false)} onSave={(prod)=>{
        setProducts(ps=>[...ps,{...prod,id:'p'+Date.now(),co:co.id,on:true,show:true}]);
        setAdd(false); toast('เพิ่ม '+prod.name+' แล้ว');
      }}/>}
    </div>
  );
};

const AddProductSheet = ({co, onClose, onSave}) => {
  const [name,setName]=useStateSet('');
  const [type,setType]=useStateSet(PLAN_TYPES[0]);
  const [hi,setHi]=useStateSet('');
  const [file,setFile]=useStateSet(null);
  const fref=useRefSet(null);
  return (
    <div className="scrim" onClick={onClose}>
      <div className="sheet slide-up" onClick={e=>e.stopPropagation()}>
        <div className="grab"/>
        <div className="flexrow" style={{gap:11,marginBottom:16}}>
          <CompanyBadge co={co} size={42}/>
          <div style={{flex:1}}><div style={{fontSize:18,fontWeight:800}}>เพิ่มผลิตภัณฑ์</div><div className="muted" style={{fontSize:13}}>{co.name}</div></div>
          <button className="iconbtn ghost" onClick={onClose}><Icon name="x" size={22}/></button>
        </div>
        <div className="field"><label>ชื่อผลิตภัณฑ์</label><input className="input" value={name} onChange={e=>setName(e.target.value)} placeholder="เช่น AIA Smart Saver 10/5"/></div>
        <div className="field"><label>ประเภท</label>
          <select className="select" value={type} onChange={e=>setType(e.target.value)}>{PLAN_TYPES.map(t=>(<option key={t}>{t}</option>))}</select>
        </div>
        <div className="field"><label>จุดเด่น</label><textarea className="input" value={hi} onChange={e=>setHi(e.target.value)} placeholder="เช่น เหมาจ่ายค่ารักษา 5 ล้าน/ปี" style={{height:64}}/></div>
        <div className="field"><label>โบรชัวร์ (PDF/รูป)</label>
          <input ref={fref} type="file" accept=".pdf,image/*" style={{display:'none'}} onChange={e=>setFile(e.target.files[0]?e.target.files[0].name:null)}/>
          <button className="btn btn-outline block" onClick={()=>fref.current&&fref.current.click()} style={{justifyContent:'flex-start',gap:10}}>
            <Icon name={file?'doc':'plusDoc'} size={19} c={file?'var(--ok)':'var(--navy-700)'}/>
            <span style={{color:file?'var(--ink)':'var(--muted)',fontWeight:600,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{file||'อัปโหลดไฟล์โบรชัวร์'}</span>
            {file && <span className="chip ok" style={{marginLeft:'auto',height:24}}>แนบแล้ว</span>}
          </button>
        </div>
        <button className="btn btn-primary block" style={{marginTop:6}} disabled={!name} onClick={()=>onSave({name,type,hi:hi||'—'})}><Icon name="check" size={19}/> บันทึกผลิตภัณฑ์</button>
      </div>
    </div>
  );
};

/* ---------- Section 2: Product sync ---------- */
const SyncSettings = ({syncs, setSyncs, setProducts, toast, goProduct}) => {
  const doSync=(s)=>{
    setProducts(ps=>[...ps, ...s.items.map((nm,i)=>({id:'sync'+Date.now()+i,co:s.co,name:nm,type:'สุขภาพ',hi:'ซิงค์จาก '+s.by,on:true,show:false}))]);
    setSyncs(ss=>ss.filter(x=>x.id!==s.id));
    toast('ซิงค์ '+s.n+' รายการเข้าของฉันแล้ว');
  };
  const skip=(s)=>{ setSyncs(ss=>ss.filter(x=>x.id!==s.id)); toast('ข้ามการอัปเดตแล้ว'); };
  return (
    <div>
      <div className="card flat" style={{display:'flex',gap:11,alignItems:'center',background:'var(--navy-50)',marginBottom:16}}>
        <Icon name="refresh" size={19} c="var(--navy-800)"/>
        <div style={{fontSize:13,color:'var(--navy-800)',lineHeight:1.5}}>เมื่อมีตัวแทนคนอื่นอัปเดตผลิตภัณฑ์ ระบบจะแจ้งเตือนให้คุณเลือก <b>ซิงค์เข้าของฉัน</b> หรือ <b>ข้าม</b></div>
      </div>
      <div className="stack" style={{gap:14}}>
        {syncs.map(s=>{
          const co=COMPANIES.find(c=>c.id===s.co);
          return (
            <div key={s.id} className="card">
              <div className="flexrow" style={{gap:12}}>
                <CompanyBadge co={co} size={44}/>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:16,fontWeight:800}}>มี {co.name} อัปเดตใหม่ {s.n} รายการ</div>
                  <div style={{fontSize:12.5,color:'var(--muted)',marginTop:2}}><Icon name="user" size={12} style={{verticalAlign:'-2px'}}/> โดย {s.by} · {s.when}</div>
                </div>
                <span className="chip warn" style={{height:26}}>ใหม่</span>
              </div>
              <div className="card flat" style={{background:'var(--bg)',margin:'12px 0',padding:'10px 14px'}}>
                {s.items.map((it,i)=>(
                  <div key={i} className="flexrow" style={{padding:'5px 0',fontSize:13.5,gap:8}}><Icon name="plusDoc" size={15} c="var(--navy-700)"/> {it}</div>
                ))}
              </div>
              <div className="grid2" style={{gap:10}}>
                <button className="btn btn-outline" onClick={()=>skip(s)}>ข้าม</button>
                <button className="btn btn-primary" onClick={()=>doSync(s)}><Icon name="refresh" size={18}/> ซิงค์เข้าของฉัน</button>
              </div>
            </div>
          );
        })}
        {syncs.length===0 && (
          <div className="card center" style={{padding:'40px 20px'}}>
            <div style={{width:56,height:56,borderRadius:18,background:'var(--ok-50)',color:'var(--ok)',display:'flex',alignItems:'center',justifyContent:'center',margin:'0 auto 14px'}}><Icon name="checkCircle" size={30}/></div>
            <div style={{fontSize:16,fontWeight:700}}>ผลิตภัณฑ์เป็นปัจจุบันแล้ว</div>
            <div className="muted" style={{fontSize:13.5,marginTop:4}}>ไม่มีรายการอัปเดตที่รอซิงค์</div>
            <button className="btn btn-soft btn-sm" style={{marginTop:16}} onClick={goProduct}>ไปจัดการผลิตภัณฑ์ <Icon name="chevR" size={15}/></button>
          </div>
        )}
      </div>
    </div>
  );
};

/* ---------- Section 3: Account & general ---------- */
const AccountSettings = ({go, toast}) => {
  const [profile,setProfile]=useStateSet({name:AGENT.name, code:AGENT.code, phone:'081-234-5678', email:'somchai.agent@covera.co.th'});
  const [edit,setEdit]=useStateSet(false);
  const [draft,setDraft]=useStateSet(profile);
  const [otp,setOtp]=useStateSet('email');
  const [notif,setNotif]=useStateSet({due:true, appt:true, product:true});
  const [conn,setConn]=useStateSet({line:false, gcal:true});
  const setN=k=>setNotif(n=>({...n,[k]:!n[k]}));

  return (
    <div className="cols c-2" style={{alignItems:'start'}}>
      <div className="stack" style={{gap:16}}>
        {/* profile */}
        <div className="card">
          <div className="flexrow" style={{marginBottom:14}}>
            <div style={{fontSize:16.5,fontWeight:800}}>โปรไฟล์ตัวแทน</div>
            <div className="spacer"/>
            {!edit
              ? <button className="chip" onClick={()=>{setDraft(profile);setEdit(true);}}><Icon name="edit" size={14}/> แก้ไข</button>
              : <button className="chip ok" onClick={()=>{setProfile(draft);setEdit(false);toast('บันทึกโปรไฟล์แล้ว');}}><Icon name="check" size={14}/> บันทึก</button>}
          </div>
          {!edit ? (
            <div className="stack" style={{gap:0}}>
              {[['ชื่อ-นามสกุล',profile.name],['รหัสตัวแทน',profile.code],['เบอร์โทร',profile.phone],['อีเมล',profile.email]].map(([l,v])=>(
                <div key={l} className="flexrow" style={{padding:'11px 0',borderTop:'1px solid var(--line-2)',fontSize:14}}>
                  <span className="muted" style={{width:120}}>{l}</span><b style={{flex:1}}>{v}</b>
                </div>
              ))}
            </div>
          ) : (
            <div className="stack" style={{gap:12}}>
              <div className="field"><label>ชื่อ-นามสกุล</label><input className="input" value={draft.name} onChange={e=>setDraft({...draft,name:e.target.value})}/></div>
              <div className="grid2" style={{gap:12}}>
                <div className="field"><label>รหัสตัวแทน</label><input className="input" value={draft.code} onChange={e=>setDraft({...draft,code:e.target.value})}/></div>
                <div className="field"><label>เบอร์โทร</label><input className="input" value={draft.phone} onChange={e=>setDraft({...draft,phone:e.target.value})}/></div>
              </div>
              <div className="field"><label>อีเมล</label><input className="input" value={draft.email} onChange={e=>setDraft({...draft,email:e.target.value})}/></div>
            </div>
          )}
        </div>

        {/* OTP method */}
        <div className="card">
          <div style={{fontSize:16.5,fontWeight:800,marginBottom:4}}>วิธีรับรหัส OTP</div>
          <div className="muted" style={{fontSize:13,marginBottom:14}}>ใช้ยืนยันตัวตนเมื่อเข้าสู่ระบบ</div>
          <div className="seg">
            <button className={"opt"+(otp==='email'?" active":"")} onClick={()=>{setOtp('email');toast('รับ OTP ทางอีเมล');}}><Icon name="mail" size={18}/> อีเมล</button>
            <button className={"opt"+(otp==='phone'?" active":"")} onClick={()=>{setOtp('phone');toast('รับ OTP ทางเบอร์โทร');}}><Icon name="phone" size={18}/> เบอร์โทร</button>
          </div>
          <div className="flexrow" style={{marginTop:12,gap:8,fontSize:12.5,color:'var(--muted)'}}><Icon name="info" size={14}/> {otp==='email'?'ค่าเริ่มต้น · ส่งไปที่ '+profile.email:'ส่ง SMS ไปที่ '+profile.phone+' (ตัวเลือกเสริม)'}</div>
        </div>
      </div>

      <div className="stack" style={{gap:16}}>
        {/* notifications */}
        <div className="card">
          <div style={{fontSize:16.5,fontWeight:800,marginBottom:12}}>การแจ้งเตือน</div>
          {[['due','กรมธรรม์ครบกำหนดชำระ','แจ้งก่อนถึงกำหนด 7 วัน'],['appt','นัดหมาย & งานวันนี้','เตือนตามปฏิทิน'],['product','ผลิตภัณฑ์อัปเดต','เมื่อมีตัวแทนซิงค์ใหม่']].map(([k,t,s])=>(
            <div key={k} className="flexrow" style={{padding:'13px 0',borderTop:'1px solid var(--line-2)'}}>
              <div style={{flex:1}}><div style={{fontSize:14.5,fontWeight:600}}>{t}</div><div className="muted" style={{fontSize:12.5}}>{s}</div></div>
              <Switch on={notif[k]} onClick={()=>{setN(k);toast(notif[k]?'ปิดแจ้งเตือน':'เปิดแจ้งเตือน');}}/>
            </div>
          ))}
        </div>

        {/* connections */}
        <div className="card">
          <div style={{fontSize:16.5,fontWeight:800,marginBottom:12}}>การเชื่อมต่อ</div>
          {[['line','Line OA','ส่งแผน/เอกสารให้ลูกค้า','#06c755'],['gcal','Google Calendar','ซิงค์นัดหมายอัตโนมัติ','#4285f4']].map(([k,t,s,clr])=>(
            <div key={k} className="flexrow" style={{padding:'13px 0',borderTop:'1px solid var(--line-2)',gap:12}}>
              <div style={{width:40,height:40,borderRadius:12,background:clr+'18',color:clr,display:'flex',alignItems:'center',justifyContent:'center',flex:'0 0 auto'}}><Icon name={k==='line'?'send':'calendar'} size={20}/></div>
              <div style={{flex:1}}><div style={{fontSize:14.5,fontWeight:600}}>{t}</div><div className="muted" style={{fontSize:12.5}}>{s}</div></div>
              {conn[k]
                ? <button className="chip ok" onClick={()=>{setConn(c=>({...c,[k]:false}));toast('ยกเลิกเชื่อมต่อ '+t);}}><Icon name="check" size={13}/> เชื่อมแล้ว</button>
                : <button className="btn btn-outline btn-sm" onClick={()=>{setConn(c=>({...c,[k]:true}));toast('เชื่อมต่อ '+t+' แล้ว');}}><Icon name="link" size={15}/> เชื่อม</button>}
            </div>
          ))}
        </div>

        <button className="btn btn-soft block" style={{color:'var(--danger)'}} onClick={()=>go('login')}><Icon name="logout" size={20}/> ออกจากระบบ</button>
      </div>
    </div>
  );
};

Object.assign(window, { SettingScreen, Switch });
