/* ============ skooldee — Settings screen ============ */

/* ===================== SETTINGS ===================== */
function Settings({ go }){
  useDataVersion();
  const [toast, showToast] = useToast();
  const [section, setSection] = useState('school'); // 'school' | 'categories' | 'profile' | 'account'

  const tab = (id, label)=>(
    <button
      onClick={()=>setSection(id)}
      style={{
        padding:'8px 18px', borderRadius:8, border:'none', cursor:'pointer',
        fontWeight:600, fontSize:13.5,
        background: section===id ? 'var(--primary)' : 'var(--surface)',
        color: section===id ? '#fff' : 'var(--text-2)',
        transition:'background .15s',
      }}>
      {label}
    </button>
  );

  return (
    <div style={{ maxWidth:700, margin:'0 auto', padding:'4px 0 40px' }}>
      {/* tabs */}
      <div style={{ display:'flex', gap:8, marginBottom:28, flexWrap:'wrap' }}>
        {tab('school',     '🏫 ข้อมูลโรงเรียน')}
        {tab('categories', '🎨 ประเภทวิชา')}
        {tab('staff',      '👥 บัญชีพนักงาน')}
        {tab('line',       '🔔 LINE แจ้งเตือน')}
        {tab('profile',    '👤 ข้อมูลผู้ใช้')}
        {tab('account',    '🔐 บัญชีและความปลอดภัย')}
      </div>

      {section==='school'      && <SchoolSettingsSection showToast={showToast}/>}
      {section==='categories'  && <CategoriesSettingsSection showToast={showToast}/>}
      {section==='staff'       && <StaffSettingsSection showToast={showToast}/>}
      {section==='line'        && <LineSettingsSection showToast={showToast}/>}
      {section==='profile'     && <ProfileSettingsSection showToast={showToast}/>}
      {section==='account'     && <AccountSettingsSection showToast={showToast} go={go}/>}

      {toast}
    </div>
  );
}

/* ---- reusable card wrapper ---- */
function SettingsCard({ title, sub, children }){
  return (
    <div style={{ background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--radius-lg)', padding:'26px 28px', marginBottom:20 }}>
      <div style={{ fontWeight:700, fontSize:16, marginBottom:sub?4:18 }}>{title}</div>
      {sub && <div style={{ color:'var(--text-2)', fontSize:13, marginBottom:18 }}>{sub}</div>}
      {children}
    </div>
  );
}

/* ---- shared input style hook ---- */
function useInpStyle(){
  return { width:'100%', padding:'10px 13px', borderRadius:9,
           border:'1.5px solid var(--border)', fontSize:14,
           background:'var(--surface)', color:'var(--text)',
           boxSizing:'border-box', outline:'none' };
}

/* ===================== School Settings ===================== */
function SchoolSettingsSection({ showToast }){
  const school = DATA._schoolRaw || {};
  const CATS = [
    { v:'',            l:'ไม่ระบุ' },
    { v:'piano',       l:'เปียโน' },
    { v:'guitar',      l:'กีตาร์' },
    { v:'violin',      l:'ไวโอลิน' },
    { v:'singing',     l:'ร้องเพลง' },
    { v:'dance',       l:'เต้น' },
    { v:'drums',       l:'กลอง' },
    { v:'art',         l:'ศิลปะ' },
    { v:'english',     l:'ภาษาอังกฤษ' },
    { v:'math',        l:'คณิตศาสตร์' },
    { v:'science',     l:'วิทยาศาสตร์' },
    { v:'other',       l:'อื่นๆ' },
  ];

  const _m2t = (m)=> m==null ? '' : String(Math.floor(m/60)).padStart(2,'0')+':'+String(m%60).padStart(2,'0');
  const _t2m = (t)=>{ if(!t) return null; const [h,mm]=t.split(':').map(Number); return h*60+(mm||0); };
  const [f, setF] = useState({
    name: school.name || '',
    category: school.category || '',
    near_limit_threshold: school.near_limit_threshold ?? DATA.NEAR_LIMIT ?? 2,
    name_display: ['nick','both'].includes(school.name_display) ? school.name_display : 'full',
    hours_start: _m2t(school.hours_start!=null?school.hours_start:600),
    hours_end: _m2t(school.hours_end!=null?school.hours_end:1170),
  });
  const [busy, setBusy] = useState(false);
  const set = (k, v)=>setF(p=>({...p, [k]:v}));
  const inp = useInpStyle();

  const save = async(e)=>{
    e.preventDefault();
    if(!f.name.trim()){ showToast('กรุณากรอกชื่อโรงเรียน','error'); return; }
    setBusy(true);
    try{
      if(DATA.updateSchool){
        const hs=_t2m(f.hours_start), he=_t2m(f.hours_end);
        if(hs!=null && he!=null && he<=hs){ showToast('เวลาปิดต้องหลังเวลาเปิด','error'); setBusy(false); return; }
        await DATA.updateSchool({
          name: f.name.trim(),
          category: f.category || null,
          near_limit_threshold: Number(f.near_limit_threshold),
          name_display: f.name_display,
          hours_start: hs, hours_end: he,
        });
        DATA.NAME_DISPLAY = f.name_display; if(DATA.setNameDisplay) DATA.setNameDisplay(f.name_display);
        if(hs!=null && he!=null && he>hs){
          DATA.DAY_START=hs; DATA.DAY_END=he;
          const st=[]; for(let m=hs;m<=he;m+=30){ st.push(String(Math.floor(m/60)).padStart(2,'0')+':'+String(m%60).padStart(2,'0')); } DATA.SLOT_TIMES=st;
        }
        bumpData();
        showToast('บันทึกข้อมูลโรงเรียนแล้ว ✓');
      } else {
        showToast('ใช้ได้เฉพาะ Live mode','error');
      }
    } catch(ex){ showToast(ex.message||'เกิดข้อผิดพลาด','error'); }
    setBusy(false);
  };

  return (
    <form onSubmit={save}>
      <SettingsCard title="โปรไฟล์โรงเรียน" sub="ชื่อและประเภทของโรงเรียนที่แสดงในระบบ">
        <div style={{ display:'grid', gap:16 }}>
          <div>
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>ชื่อโรงเรียน *</label>
            <input style={inp} value={f.name} onChange={e=>set('name',e.target.value)} placeholder="เช่น บ้านมาริ มิวสิค"/>
          </div>
          <div>
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:8 }}>ประเภทโรงเรียน</label>
            <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
              {CATS.map(c=>(
                <button key={c.v} type="button"
                  onClick={()=>set('category', c.v)}
                  style={{
                    padding:'6px 14px', borderRadius:20, border:'1.5px solid',
                    borderColor: f.category===c.v ? 'var(--primary)' : 'var(--border)',
                    background: f.category===c.v ? 'var(--primary-soft)' : 'transparent',
                    color: f.category===c.v ? 'var(--primary-ink)' : 'var(--text-2)',
                    fontSize:13, cursor:'pointer', fontWeight: f.category===c.v ? 600 : 400,
                  }}>
                  {c.l}
                </button>
              ))}
            </div>
          </div>
        </div>
      </SettingsCard>

      <SettingsCard title="การแจ้งเตือน" sub="เงื่อนไขการแสดงคำเตือน 'คอร์สใกล้หมด'">
        <div style={{ display:'flex', alignItems:'center', gap:16, flexWrap:'wrap' }}>
          <label style={{ fontWeight:600, fontSize:13 }}>แจ้งเตือนเมื่อคอร์สเหลือ ≤</label>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <input
              type="number" min={1} max={10} step={1}
              value={f.near_limit_threshold}
              onChange={e=>set('near_limit_threshold', Math.max(1,Math.min(10,parseInt(e.target.value)||1)))}
              style={{ ...inp, width:80, textAlign:'center' }}
            />
            <span style={{ fontSize:13, color:'var(--text-2)' }}>ครั้ง</span>
          </div>
          <div style={{ fontSize:12.5, color:'var(--text-3)' }}>ค่าที่อนุญาต: 1–10</div>
        </div>
      </SettingsCard>

      <SettingsCard title="เวลาทำการ" sub="ช่วงเวลาที่แสดงในตารางเรียนและตัวเลือกเวลาจองคาบ">
        <div style={{ display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
          <div>
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>เปิด</label>
            <input type="time" style={{ ...inp, width:130 }} value={f.hours_start} onChange={e=>set('hours_start', e.target.value)}/>
          </div>
          <span style={{ color:'var(--text-3)', alignSelf:'flex-end', paddingBottom:10 }}>ถึง</span>
          <div>
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>ปิด</label>
            <input type="time" style={{ ...inp, width:130 }} value={f.hours_end} onChange={e=>set('hours_end', e.target.value)}/>
          </div>
        </div>
        <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:10 }}>ตารางเรียนจะแสดงเฉพาะช่วงนี้ และเวลาเริ่มคาบจะเลือกได้ในช่วงนี้</div>
      </SettingsCard>

      <SettingsCard title="การแสดงชื่อนักเรียน" sub="เลือกว่าจะแสดงชื่อจริงหรือชื่อเล่นทั่วทั้งระบบ">
        <div style={{ display:'flex', gap:10, flexWrap:'wrap' }}>
          {[['full','ชื่อจริง','น้องอินดี้ สมมติ'],['nick','ชื่อเล่น','อินดี้'],['both','ชื่อจริง (ชื่อเล่น)','น้องอินดี้ สมมติ (อินดี้)']].map(([v,l,hint])=>(
            <button key={v} type="button" onClick={()=>set('name_display', v)} style={{
              flex:'1 1 140px', padding:'12px 10px', borderRadius:10, cursor:'pointer', textAlign:'left',
              border:'1.5px solid '+(f.name_display===v?'var(--primary)':'var(--border)'),
              background: f.name_display===v?'var(--primary-soft)':'transparent' }}>
              <div style={{ fontWeight:700, fontSize:14, color: f.name_display===v?'var(--primary-ink)':'var(--text)' }}>{l}</div>
              <div style={{ fontSize:12, color:'var(--text-3)', marginTop:2 }}>{hint}</div>
            </button>
          ))}
        </div>
        <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:10 }}>หมายเหตุ: ถ้าเลือก "ชื่อเล่น" แต่นักเรียนไม่มีชื่อเล่น จะแสดงชื่อจริงแทน</div>
      </SettingsCard>

      {/* School slug (read-only) */}
      {DATA._schoolRaw && DATA._schoolRaw.slug && (
        <SettingsCard title="URL โรงเรียน" sub="ไม่สามารถเปลี่ยนได้หลังสมัคร">
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ ...inp, width:'auto', flex:1, background:'var(--surface-2)',
                          color:'var(--text-3)', userSelect:'all', fontFamily:'monospace', fontSize:13 }}>
              skooldee.com/{DATA._schoolRaw.slug}
            </div>
          </div>
        </SettingsCard>
      )}

      <div style={{ display:'flex', justifyContent:'flex-end' }}>
        <button type="submit" className="btn btn-primary" disabled={busy}
          style={{ padding:'11px 28px', fontSize:14.5, fontWeight:700 }}>
          {busy ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
        </button>
      </div>
    </form>
  );
}

/* ===================== Profile Settings ===================== */
function ProfileSettingsSection({ showToast }){
  const user = DATA._userRaw || {};
  const [name, setName] = useState(user.name || DATA.SCHOOL.owner || '');
  const [busy, setBusy] = useState(false);
  const inp = useInpStyle();

  const save = async(e)=>{
    e.preventDefault();
    if(!name.trim()){ showToast('กรุณากรอกชื่อ','error'); return; }
    setBusy(true);
    try{
      if(DATA.updateProfile){
        await DATA.updateProfile({ name: name.trim() });
        showToast('บันทึกข้อมูลผู้ใช้แล้ว ✓');
      } else {
        showToast('ใช้ได้เฉพาะ Live mode','error');
      }
    } catch(ex){ showToast(ex.message||'เกิดข้อผิดพลาด','error'); }
    setBusy(false);
  };

  return (
    <form onSubmit={save}>
      <SettingsCard title="ข้อมูลส่วนตัว" sub="ชื่อที่แสดงในระบบสำหรับบัญชีของคุณ">
        <div style={{ display:'flex', alignItems:'center', gap:16, marginBottom:20, flexWrap:'wrap' }}>
          <Avatar name={name||'?'} size={64} color="var(--primary)"/>
          <div>
            <div style={{ fontWeight:700, fontSize:15 }}>{name || '-'}</div>
            <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:3 }}>
              {DATA.SCHOOL.ownerRole} · {user.email || ''}
            </div>
          </div>
        </div>

        <div style={{ display:'grid', gap:16 }}>
          <div>
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>ชื่อ-นามสกุล</label>
            <input style={inp} value={name} onChange={e=>setName(e.target.value)} placeholder="ชื่อที่ต้องการแสดง"/>
          </div>
          <div>
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>อีเมล (เปลี่ยนไม่ได้)</label>
            <input style={{ ...inp, background:'var(--surface-2)', color:'var(--text-3)', cursor:'not-allowed' }}
              value={user.email || ''} readOnly/>
          </div>
          <div>
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>บทบาท</label>
            <input style={{ ...inp, background:'var(--surface-2)', color:'var(--text-3)', cursor:'not-allowed' }}
              value={DATA.SCHOOL.ownerRole} readOnly/>
          </div>
        </div>
      </SettingsCard>

      <div style={{ display:'flex', justifyContent:'flex-end' }}>
        <button type="submit" className="btn btn-primary" disabled={busy}
          style={{ padding:'11px 28px', fontSize:14.5, fontWeight:700 }}>
          {busy ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
        </button>
      </div>
    </form>
  );
}

/* ===================== Account & Security Settings ===================== */
function AccountSettingsSection({ showToast, go }){
  const [changingPw, setChangingPw] = useState(false);

  const school = DATA._schoolRaw || {};
  const joined = school.created_at ? school.created_at.slice(0,10) : '-';

  const Row = ({ icon, label, value, action })=>(
    <div style={{ display:'flex', alignItems:'center', gap:14, padding:'14px 0',
                  borderBottom:'1px solid var(--border)' }}>
      <div style={{ width:36, height:36, borderRadius:10, background:'var(--primary-soft)',
                    display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
        <Icon n={icon} size={18} style={{ color:'var(--primary)' }}/>
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontWeight:600, fontSize:13.5 }}>{label}</div>
        <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:2 }}>{value}</div>
      </div>
      {action}
    </div>
  );

  return (
    <>
      <SettingsCard title="ความปลอดภัย">
        <Row
          icon="key"
          label="รหัสผ่าน"
          value="เปลี่ยนรหัสผ่านบัญชีของคุณ"
          action={
            <button className="btn" style={{ fontSize:13, padding:'7px 16px', whiteSpace:'nowrap' }}
              onClick={()=>setChangingPw(true)}>
              เปลี่ยนรหัสผ่าน
            </button>
          }
        />
        <Row
          icon="logout"
          label="ออกจากระบบ"
          value="ออกจากระบบในเบราว์เซอร์นี้"
          action={
            <button className="btn" style={{ fontSize:13, padding:'7px 16px', color:'var(--danger)',
                                             borderColor:'var(--danger)', whiteSpace:'nowrap' }}
              onClick={()=>window.API && window.API.logout()}>
              ออกจากระบบ
            </button>
          }
        />
      </SettingsCard>

      <SettingsCard title="ข้อมูลบัญชี">
        <div style={{ display:'grid', gap:12 }}>
          {[
            ['อีเมล', DATA._userRaw?.email || '-'],
            ['วันที่สมัคร', joined],
            ['รหัสโรงเรียน', school.id ? '#'+school.id : '-'],
            ['ช่วงทดลองใช้', '14 วันฟรี หลังสมัคร'],
          ].map(([k,v])=>(
            <div key={k} style={{ display:'flex', justifyContent:'space-between', alignItems:'center',
                                  padding:'10px 0', borderBottom:'1px solid var(--border)', gap:12 }}>
              <span style={{ fontSize:13.5, color:'var(--text-2)', fontWeight:500 }}>{k}</span>
              <span style={{ fontSize:13.5, fontWeight:600 }}>{v}</span>
            </div>
          ))}
        </div>
      </SettingsCard>

      <SettingsCard title="การแจ้งเตือนอีเมล">
        <div style={{ display:'flex', gap:12, padding:'4px 0', flexWrap:'wrap' }}>
          <div style={{ flex:1, minWidth:200 }}>
            <div style={{ fontWeight:600, fontSize:13.5, marginBottom:4 }}>Resend Integration</div>
            <div style={{ fontSize:12.5, color:'var(--text-3)', lineHeight:1.6 }}>
              เมื่อตั้งค่า <code style={{ background:'var(--surface-2)', padding:'1px 5px', borderRadius:4 }}>RESEND_API_KEY</code> บน Railway
              ระบบจะส่งอีเมลยืนยัน รีเซ็ตรหัสผ่าน และแจ้งเตือนอื่นๆ โดยอัตโนมัติ
            </div>
          </div>
          <div style={{ display:'flex', alignItems:'flex-start', paddingTop:4 }}>
            <div style={{
              padding:'4px 12px', borderRadius:20, fontSize:12, fontWeight:700,
              background: 'var(--surface-2)',
              color: 'var(--text-3)',
            }}>
              ⏳ รอตั้งค่า
            </div>
          </div>
        </div>
      </SettingsCard>

      {changingPw && <ChangePasswordModal onClose={()=>setChangingPw(false)}/>}
    </>
  );
}

/* ===================== Categories Settings ===================== */
const CAT_PALETTE = [
  '#3B82F6','#10B981','#F59E0B','#EF4444','#8B5CF6',
  '#EC4899','#06B6D4','#84CC16','#F97316','#6366F1',
  '#0EA5E9','#14B8A6','#A855F7','#F43F5E','#78716C',
];

function catsToArray(catsObj){
  return Object.values(catsObj||{}).map(c=>({
    key:c.key, label:c.label, icon:c.icon||'📚', color:c.color, room:c.room||''
  }));
}

function CategoriesSettingsSection({ showToast }){
  const [cats, setCats] = useState(()=> catsToArray(DATA.CATS));
  const [adding, setAdding] = useState(false);
  const [editIdx, setEditIdx] = useState(null);
  const [newLabel, setNewLabel] = useState('');
  const [newIcon,  setNewIcon]  = useState('📚');
  const [busy, setBusy] = useState(false);

  const usedColors = cats.map(c=>c.color);
  const nextColor = CAT_PALETTE.find(c=>!usedColors.includes(c)) || CAT_PALETTE[cats.length % CAT_PALETTE.length];

  const save = async(list)=>{
    setBusy(true);
    try{
      if(DATA.saveCategories){
        await DATA.saveCategories(list);
        showToast('บันทึกประเภทวิชาแล้ว ✓');
      } else {
        DATA.CATS = {};
        list.forEach(c=>{ DATA.CATS[c.key] = { key:c.key, label:c.label, color:c.color, soft:c.color+'22', icon:c.icon, room:c.room||c.label }; });
        bumpData();
        showToast('บันทึกแล้ว (demo)');
      }
      setCats(list);
    } catch(ex){ showToast(ex.message||'เกิดข้อผิดพลาด','error'); }
    setBusy(false);
  };

  const addCat = ()=>{
    const label = newLabel.trim();
    if(!label){ showToast('กรุณาใส่ชื่อวิชา','error'); return; }
    const key = label.toLowerCase().replace(/\s+/g,'_').replace(/[^\w_]/g,'') || ('cat'+Date.now());
    if(cats.find(c=>c.key===key)){ showToast('มีวิชานี้อยู่แล้ว','error'); return; }
    const list = [...cats, { key, label, icon:newIcon, color:nextColor, room:label }];
    save(list);
    setNewLabel(''); setNewIcon('📚'); setAdding(false);
  };

  const updateCat = (idx)=>{
    const label = newLabel.trim();
    if(!label){ showToast('กรุณาใส่ชื่อวิชา','error'); return; }
    const list = cats.map((c,i)=> i===idx ? { ...c, label, icon:newIcon } : c);
    save(list);
    setEditIdx(null); setNewLabel(''); setNewIcon('📚');
  };

  const deleteCat = (idx)=>{
    if(!confirm(`ลบวิชา "${cats[idx].label}"? นักเรียนที่มีวิชานี้จะยังอยู่ในระบบ`)) return;
    save(cats.filter((_,i)=>i!==idx));
  };

  const startEdit = (idx)=>{
    setEditIdx(idx); setAdding(false);
    setNewLabel(cats[idx].label); setNewIcon(cats[idx].icon||'📚');
  };

  const inp = useInpStyle();
  const emojiOpts = ['🎹','🎸','🎤','💃','🎨','🥁','🎷','🎺','🎻','🎵','📖','➕','🎯','✏️','🌟'];

  return (
    <SettingsCard title="ประเภทวิชา" sub="เพิ่ม แก้ไข หรือลบวิชาที่โรงเรียนของคุณเปิดสอน">
      {/* list */}
      <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:16 }}>
        {cats.length===0 && (
          <div style={{ padding:'20px', textAlign:'center', color:'var(--text-3)', fontSize:13.5 }}>
            ยังไม่มีวิชา กด "+ เพิ่มวิชา" เพื่อเริ่มต้น
          </div>
        )}
        {cats.map((c,idx)=>(
          <div key={c.key} style={{
            display:'flex', alignItems:'center', gap:12, padding:'12px 14px',
            background:'var(--surface-2)', borderRadius:10,
            border: editIdx===idx ? '1.5px solid var(--primary)' : '1.5px solid transparent',
          }}>
            {/* colour swatch */}
            <div style={{ width:14, height:14, borderRadius:'50%', background:c.color, flexShrink:0 }}/>
            <span style={{ fontSize:20, lineHeight:1, flexShrink:0 }}>{c.icon}</span>
            <span style={{ flex:1, fontWeight:600, fontSize:14 }}>{c.label}</span>

            {editIdx===idx ? (
              /* inline edit form */
              <div style={{ display:'flex', gap:8, alignItems:'center', flexWrap:'wrap' }}>
                {/* emoji picker */}
                <select value={newIcon} onChange={e=>setNewIcon(e.target.value)}
                  style={{ ...inp, width:72, padding:'6px 8px', fontSize:18, textAlign:'center' }}>
                  {emojiOpts.map(em=><option key={em} value={em}>{em}</option>)}
                </select>
                <input value={newLabel} onChange={e=>setNewLabel(e.target.value)}
                  placeholder="ชื่อวิชา" onKeyDown={e=>e.key==='Enter'&&updateCat(idx)}
                  style={{ ...inp, width:130, padding:'7px 10px' }} autoFocus/>
                <button className="btn btn-primary" disabled={busy}
                  style={{ padding:'7px 14px', fontSize:13 }}
                  onClick={()=>updateCat(idx)}>บันทึก</button>
                <button className="btn" style={{ padding:'7px 12px', fontSize:13 }}
                  onClick={()=>setEditIdx(null)}>ยกเลิก</button>
              </div>
            ) : (
              <div style={{ display:'flex', gap:8 }}>
                <button className="btn" style={{ padding:'5px 12px', fontSize:12.5 }}
                  onClick={()=>startEdit(idx)}>แก้ไข</button>
                <button className="btn" style={{ padding:'5px 12px', fontSize:12.5,
                  color:'var(--danger)', borderColor:'var(--danger)' }}
                  onClick={()=>deleteCat(idx)}>ลบ</button>
              </div>
            )}
          </div>
        ))}
      </div>

      {/* add form */}
      {adding ? (
        <div style={{ display:'flex', gap:8, alignItems:'center', flexWrap:'wrap',
                      padding:'14px', background:'var(--surface-2)', borderRadius:10,
                      border:'1.5px dashed var(--primary)' }}>
          <div style={{ width:14, height:14, borderRadius:'50%', background:nextColor, flexShrink:0 }}/>
          <select value={newIcon} onChange={e=>setNewIcon(e.target.value)}
            style={{ ...inp, width:72, padding:'6px 8px', fontSize:18, textAlign:'center' }}>
            {emojiOpts.map(em=><option key={em} value={em}>{em}</option>)}
          </select>
          <input value={newLabel} onChange={e=>setNewLabel(e.target.value)}
            placeholder="ชื่อวิชาใหม่ เช่น ไวโอลิน"
            onKeyDown={e=>e.key==='Enter'&&addCat()}
            style={{ ...inp, flex:1, minWidth:140, padding:'7px 10px' }} autoFocus/>
          <button className="btn btn-primary" disabled={busy}
            style={{ padding:'7px 14px', fontSize:13 }}
            onClick={addCat}>{busy?'กำลังบันทึก…':'เพิ่มวิชา'}</button>
          <button className="btn" style={{ padding:'7px 12px', fontSize:13 }}
            onClick={()=>{ setAdding(false); setNewLabel(''); setNewIcon('📚'); }}>ยกเลิก</button>
        </div>
      ) : (
        <button className="btn btn-primary" style={{ fontSize:13.5 }}
          onClick={()=>{ setAdding(true); setEditIdx(null); }}>
          + เพิ่มวิชา
        </button>
      )}
    </SettingsCard>
  );
}

/* ===================== Staff Accounts ===================== */
const ROLE_LABEL = { owner:'เจ้าของ', admin:'ผู้ดูแล', finance:'การเงิน', teacher:'ครูผู้สอน' };
const ROLE_DESC  = {
  teacher:'เห็นตาราง · เช็คชื่อ · นักเรียน · การบ้าน (ไม่เห็นการเงิน/ตั้งค่า)',
  finance:'เห็นการเงินและรายงาน เพิ่มเติมจากครู',
  admin:'เห็นทุกอย่างเหมือนเจ้าของ (ยกเว้นลบเจ้าของ)',
};

function StaffSettingsSection({ showToast }){
  const [users, setUsers] = useState(null);
  const [adding, setAdding] = useState(false);
  const [f, setF] = useState({ name:'', email:'', password:'', role:'teacher' });
  const [busy, setBusy] = useState(false);
  const inp = useInpStyle();
  const myId = DATA._userRaw && DATA._userRaw.id;

  const load = ()=>{
    if(!(DATA._isLiveMode && window.API && window.API.listUsers)){ setUsers([]); return; }
    window.API.listUsers().then(setUsers).catch(()=>setUsers([]));
  };
  React.useEffect(load, []);

  const create = async()=>{
    if(!f.name.trim()||!f.email.trim()||!f.password){ showToast('กรอกข้อมูลให้ครบ','error'); return; }
    setBusy(true);
    try{
      await window.API.createUser({ name:f.name.trim(), email:f.email.trim().toLowerCase(), password:f.password, role:f.role });
      setF({ name:'', email:'', password:'', role:'teacher' }); setAdding(false);
      showToast('สร้างบัญชีพนักงานแล้ว ✓'); load();
    }catch(ex){ showToast(ex.body&&ex.body.error||ex.message||'สร้างไม่สำเร็จ','error'); }
    setBusy(false);
  };

  const del = async(u)=>{
    if(!confirm(`ลบบัญชี "${u.name}" (${u.email})?`)) return;
    try{ await window.API.deleteUser(u.id); showToast('ลบบัญชีแล้ว'); load(); }
    catch(ex){ showToast(ex.body&&ex.body.error||'ลบไม่สำเร็จ','error'); }
  };

  return (
    <>
      <SettingsCard title="บัญชีพนักงาน" sub="สร้าง login แยกให้ครู/พนักงาน — ครูจะเห็นแค่ตาราง เช็คชื่อ และนักเรียน ไม่เห็นการเงิน">
        {users===null ? (
          <div style={{ color:'var(--text-3)', fontSize:13.5 }}>กำลังโหลด…</div>
        ) : (
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {users.map(u=>(
              <div key={u.id} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px',
                background:'var(--surface-2)', borderRadius:10 }}>
                <Avatar name={u.name} size={36}/>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:600, fontSize:14 }}>{u.name}{u.id===myId && <span style={{ fontSize:11.5, color:'var(--text-3)', fontWeight:400 }}> · คุณ</span>}</div>
                  <div style={{ fontSize:12.5, color:'var(--text-3)' }}>{u.email}</div>
                </div>
                <span style={{ fontSize:12, fontWeight:700, padding:'3px 10px', borderRadius:99,
                  background: u.role==='owner'?'var(--primary-soft)':'var(--surface)', color:'var(--primary-ink)' }}>
                  {ROLE_LABEL[u.role]||u.role}
                </span>
                {u.role!=='owner' && u.id!==myId &&
                  <button className="icon-btn" style={{ border:0, color:'var(--danger)' }} title="ลบบัญชี" onClick={()=>del(u)}><Icon n="x" size={15}/></button>}
              </div>
            ))}
          </div>
        )}

        {adding ? (
          <div style={{ marginTop:14, padding:'16px', border:'1.5px dashed var(--primary)', borderRadius:12, display:'grid', gap:12 }}>
            <div style={{ display:'flex', gap:12, flexWrap:'wrap' }}>
              <div style={{ flex:1, minWidth:140 }}>
                <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>ชื่อ</label>
                <input style={inp} value={f.name} onChange={e=>setF(p=>({...p,name:e.target.value}))} placeholder="เช่น ครูฟ้า"/>
              </div>
              <div style={{ flex:1, minWidth:140 }}>
                <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>บทบาท</label>
                <select style={inp} value={f.role} onChange={e=>setF(p=>({...p,role:e.target.value}))}>
                  <option value="teacher">ครูผู้สอน</option>
                  <option value="finance">การเงิน</option>
                  <option value="admin">ผู้ดูแล</option>
                </select>
              </div>
            </div>
            <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:-4 }}>{ROLE_DESC[f.role]}</div>
            <div>
              <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>อีเมล (ใช้ login)</label>
              <input style={inp} type="email" value={f.email} onChange={e=>setF(p=>({...p,email:e.target.value}))} placeholder="teacher@email.com"/>
            </div>
            <div>
              <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>รหัสผ่านเริ่มต้น <span style={{fontWeight:400,color:'var(--text-3)',fontSize:12}}>(อย่างน้อย 6 ตัว)</span></label>
              <input style={inp} value={f.password} onChange={e=>setF(p=>({...p,password:e.target.value}))} placeholder="ตั้งรหัสให้พนักงาน"/>
            </div>
            <div style={{ display:'flex', gap:8 }}>
              <button className="btn btn-primary" disabled={busy} onClick={create}>{busy?'กำลังสร้าง…':'สร้างบัญชี'}</button>
              <button className="btn" onClick={()=>setAdding(false)}>ยกเลิก</button>
            </div>
          </div>
        ) : (
          <button className="btn btn-primary" style={{ marginTop:14 }} onClick={()=>setAdding(true)}>
            <Icon n="plus" size={15}/> เพิ่มบัญชีพนักงาน
          </button>
        )}
      </SettingsCard>
    </>
  );
}

/* ===================== LINE Settings ===================== */
function LineSettingsSection({ showToast }){
  const [configured, setConfigured] = useState(null); // null=loading
  const [secretCfg, setSecretCfg]   = useState(false);
  const [schoolId, setSchoolId]     = useState(DATA._schoolRaw?.id||null);
  const [token, setToken]   = useState('');
  const [secret, setSecret] = useState('');
  const [busy, setBusy]     = useState(false);
  const [testing, setTesting] = useState(false);
  const [bot, setBot]       = useState(null);
  const [prefs, setPrefs]   = useState({});
  const inp = useInpStyle();

  const webhookUrl = schoolId ? `${(window.API&&window.API.base)||''}/api/line/webhook/${schoolId}` : '';
  const basicId   = bot && bot.basicId ? bot.basicId : '';
  const addUrl    = basicId ? `https://line.me/R/ti/p/${basicId}` : '';
  // QR generated entirely in-browser (no external service) → self-contained data URL
  let qrSrc = '';
  if(addUrl && window.qrcode){
    try{ const q = window.qrcode(0,'M'); q.addData(addUrl); q.make(); qrSrc = q.createDataURL(6, 2); }catch(e){}
  }

  // load current connection status (+ bot info for QR when connected)
  React.useEffect(()=>{
    if(!(DATA._isLiveMode && window.API && window.API.school)){ setConfigured(false); return; }
    window.API.school()
      .then(s=>{
        setConfigured(!!s.line_configured); setSecretCfg(!!s.line_secret_configured);
        if(s.id) setSchoolId(s.id);
        if(s.notify_prefs && typeof s.notify_prefs==='object') setPrefs(s.notify_prefs);
        if(s.line_configured && window.API.testLine){
          window.API.testLine().then(r=>{ if(r.ok) setBot(r.bot); }).catch(()=>{});
        }
      })
      .catch(()=> setConfigured(false));
  }, []);

  const copy = (text)=>{ try{ navigator.clipboard.writeText(text); showToast('คัดลอกแล้ว ✓'); }catch(e){} };

  const togglePref = async(key)=>{
    const next = { ...prefs, [key]: !prefs[key] };
    setPrefs(next);
    try{ await window.API.updateSchool({ notify_prefs: next }); }
    catch(ex){ setPrefs(prefs); showToast('บันทึกไม่สำเร็จ','error'); }
  };

  const saveToken = async()=>{
    if(!token.trim()){ showToast('กรุณาวาง Channel Access Token','error'); return; }
    setBusy(true);
    try{
      await window.API.updateSchool({ line_token: token.trim() });
      setConfigured(true); setToken('');
      showToast('เชื่อมต่อ LINE แล้ว ✓');
    }catch(ex){ showToast(ex.message||'บันทึกไม่สำเร็จ','error'); }
    setBusy(false);
  };

  const saveSecret = async()=>{
    setBusy(true);
    try{
      await window.API.updateSchool({ line_secret: secret.trim() });
      setSecretCfg(!!secret.trim()); setSecret('');
      showToast(secret.trim()?'บันทึก Channel Secret แล้ว ✓':'ลบ Channel Secret แล้ว');
    }catch(ex){ showToast(ex.message||'บันทึกไม่สำเร็จ','error'); }
    setBusy(false);
  };

  const disconnect = async()=>{
    if(!confirm('ยกเลิกการเชื่อมต่อ LINE? ระบบจะหยุดส่งข้อความผ่าน LINE')) return;
    setBusy(true);
    try{
      await window.API.updateSchool({ line_token: '', line_secret: '' });
      setConfigured(false); setSecretCfg(false); setBot(null);
      showToast('ยกเลิกการเชื่อมต่อแล้ว');
    }catch(ex){ showToast(ex.message||'ทำรายการไม่สำเร็จ','error'); }
    setBusy(false);
  };

  const testConn = async()=>{
    setTesting(true); setBot(null);
    try{
      const r = await window.API.testLine();
      if(r.ok){ setBot(r.bot); showToast('เชื่อมต่อสำเร็จ ✓'); }
      else showToast(r.note||'Token ใช้งานไม่ได้','error');
    }catch(ex){ showToast('ทดสอบไม่สำเร็จ','error'); }
    setTesting(false);
  };

  const Step = ({ n, children })=>(
    <div style={{ display:'flex', gap:12, marginBottom:12 }}>
      <div style={{ width:24, height:24, borderRadius:'50%', background:'var(--primary)', color:'#fff',
        display:'flex', alignItems:'center', justifyContent:'center', fontSize:12.5, fontWeight:700, flexShrink:0 }}>{n}</div>
      <div style={{ fontSize:13.5, lineHeight:1.65, color:'var(--text-2)', paddingTop:2 }}>{children}</div>
    </div>
  );

  const codeBox = { background:'var(--surface-2)', padding:'1px 6px', borderRadius:4, fontFamily:'monospace', fontSize:12.5 };

  return (
    <>
      {/* status card */}
      <SettingsCard title="สถานะการเชื่อมต่อ LINE">
        {configured===null ? (
          <div style={{ color:'var(--text-3)', fontSize:13.5 }}>กำลังตรวจสอบ…</div>
        ) : configured ? (
          <div>
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14, flexWrap:'wrap' }}>
              <span style={{ padding:'4px 14px', borderRadius:20, fontSize:13, fontWeight:700,
                background:'#06c75522', color:'#06a046' }}>● เชื่อมต่อแล้ว</span>
              {bot && <span style={{ fontSize:13.5, fontWeight:600 }}>{bot.displayName} {bot.basicId?`(${bot.basicId})`:''}</span>}
            </div>
            <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginBottom:16 }}>
              <button className="btn" style={{ fontSize:13 }} disabled={testing} onClick={testConn}>
                {testing?'กำลังทดสอบ…':'🔍 ทดสอบการเชื่อมต่อ'}
              </button>
              <button className="btn" style={{ fontSize:13, color:'var(--danger)', borderColor:'var(--danger)' }}
                disabled={busy} onClick={disconnect}>ยกเลิกการเชื่อมต่อ</button>
            </div>

            {/* webhook URL — needed for auto-linking parents */}
            <label style={{ display:'block', fontWeight:600, fontSize:13, marginBottom:6 }}>Webhook URL ของโรงเรียนคุณ</label>
            <div style={{ display:'flex', gap:8, alignItems:'center' }}>
              <div style={{ ...inp, flex:1, fontFamily:'monospace', fontSize:12, background:'var(--surface-2)',
                color:'var(--text-2)', overflowX:'auto', whiteSpace:'nowrap', userSelect:'all' }}>{webhookUrl||'—'}</div>
              <button className="btn" style={{ fontSize:13, whiteSpace:'nowrap' }} onClick={()=>copy(webhookUrl)}>คัดลอก</button>
            </div>
            <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:6, lineHeight:1.55 }}>
              นำไปวางใน LINE Developers Console → Messaging API → <b>Webhook URL</b> แล้วเปิด <b>Use webhook</b>
            </div>

            {/* channel secret (optional, for signature verification) */}
            <label style={{ display:'block', fontWeight:600, fontSize:13, margin:'16px 0 6px' }}>
              Channel Secret <span style={{ fontWeight:400, color:'var(--text-3)', fontSize:12 }}>({secretCfg?'ตั้งค่าแล้ว — ใส่ใหม่เพื่อเปลี่ยน':'ไม่บังคับ แต่แนะนำ เพื่อความปลอดภัย'})</span>
            </label>
            <div style={{ display:'flex', gap:8 }}>
              <input style={{ ...inp, flex:1 }} type="password" value={secret} onChange={e=>setSecret(e.target.value)}
                placeholder={secretCfg?'••••••••••••':'วาง Channel Secret'}/>
              <button className="btn" style={{ fontSize:13, whiteSpace:'nowrap' }} disabled={busy} onClick={saveSecret}>บันทึก</button>
            </div>

            {/* OA QR code for parents to scan */}
            {qrSrc && (
              <div style={{ marginTop:18, padding:'16px', background:'var(--surface-2)', borderRadius:12,
                display:'flex', gap:16, alignItems:'center', flexWrap:'wrap' }}>
                <img src={qrSrc} alt="LINE OA QR" width={120} height={120}
                  style={{ borderRadius:10, background:'#fff', padding:6, flexShrink:0 }}/>
                <div style={{ flex:1, minWidth:180 }}>
                  <div style={{ fontWeight:700, fontSize:14, marginBottom:4 }}>QR เพิ่มเพื่อน Official Account</div>
                  <div style={{ fontSize:12.5, color:'var(--text-2)', lineHeight:1.55, marginBottom:10 }}>
                    ให้ผู้ปกครองสแกน QR นี้เพื่อแอด {bot?.displayName||'OA'} เป็นเพื่อน แล้วส่ง "รหัสเชื่อมต่อ" ของบุตรหลาน
                  </div>
                  <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                    <a className="btn btn-sm" href={qrSrc} download="line-oa-qr.gif" style={{ fontSize:12.5, textDecoration:'none' }}>⬇️ ดาวน์โหลด QR</a>
                    <button className="btn btn-sm" style={{ fontSize:12.5 }} onClick={()=>copy(addUrl)}>คัดลอกลิงก์แอด</button>
                  </div>
                </div>
              </div>
            )}
          </div>
        ) : (
          <div>
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
              <span style={{ padding:'4px 14px', borderRadius:20, fontSize:13, fontWeight:700,
                background:'var(--surface-2)', color:'var(--text-3)' }}>○ ยังไม่เชื่อมต่อ</span>
            </div>
            <div style={{ display:'grid', gap:10 }}>
              <label style={{ fontWeight:600, fontSize:13 }}>Channel Access Token</label>
              <input style={inp} type="password" value={token} onChange={e=>setToken(e.target.value)}
                placeholder="วาง token ที่ได้จาก LINE Developers Console"/>
              <button className="btn btn-primary" style={{ alignSelf:'flex-start', padding:'10px 24px', fontWeight:700 }}
                disabled={busy} onClick={saveToken}>{busy?'กำลังบันทึก…':'เชื่อมต่อ LINE'}</button>
            </div>
          </div>
        )}
      </SettingsCard>

      {/* auto-notification preferences (opt-in) */}
      {configured && (
        <SettingsCard title="การแจ้งเตือนอัตโนมัติ" sub="เลือกเหตุการณ์ที่อยากให้ระบบส่ง LINE ถึงผู้ปกครองโดยอัตโนมัติ (ค่าเริ่มต้นปิดทั้งหมด)">
          {[
            { key:'absent',     label:'เมื่อนักเรียนขาด/ลาเรียน', hint:'ส่งทันทีที่เช็คชื่อเป็นขาดหรือลา (ไม่ส่งตอนมาเรียนปกติ)' },
            { key:'invoice',    label:'เมื่อออกใบแจ้งหนี้ใหม่',   hint:'แจ้งยอดที่ต้องชำระให้ผู้ปกครองทราบ' },
            { key:'near_limit', label:'เมื่อคอร์สใกล้หมด',         hint:'เตือนให้ต่อคอร์สเมื่อจำนวนคาบเหลือน้อย' },
          ].map(o=>(
            <label key={o.key} style={{ display:'flex', alignItems:'center', gap:13, padding:'12px 2px',
              borderBottom:'1px solid var(--border)', cursor:'pointer' }}>
              <input type="checkbox" checked={!!prefs[o.key]} onChange={()=>togglePref(o.key)}
                style={{ width:18, height:18, accentColor:'var(--primary)', flexShrink:0 }}/>
              <div style={{ flex:1 }}>
                <div style={{ fontWeight:600, fontSize:13.5 }}>{o.label}</div>
                <div style={{ fontSize:12, color:'var(--text-3)', marginTop:2 }}>{o.hint}</div>
              </div>
              <span style={{ fontSize:12.5, fontWeight:700, color: prefs[o.key]?'#06a046':'var(--text-3)' }}>
                {prefs[o.key]?'เปิด':'ปิด'}
              </span>
            </label>
          ))}
          <div style={{ marginTop:12, fontSize:12.5, color:'var(--text-3)', lineHeight:1.55 }}>
            📌 ส่งได้เฉพาะนักเรียนที่ผู้ปกครอง<b>เชื่อม LINE แล้ว</b> (มีเครื่องหมาย ✓ ในโปรไฟล์นักเรียน)
          </div>
        </SettingsCard>
      )}

      {/* setup guide */}
      <SettingsCard title="วิธีเชื่อมต่อ (ทำครั้งเดียว ~10 นาที)"
        sub="ทำตามขั้นตอนนี้เพื่อให้ระบบส่งแจ้งเตือนถึงผู้ปกครองผ่าน LINE ได้อัตโนมัติ">
        <Step n={1}>สมัคร <b>LINE Official Account</b> ที่ <code style={codeBox}>business.line.me</code> (ฟรี)</Step>
        <Step n={2}>เข้า <b>LINE Developers Console</b> (<code style={codeBox}>developers.line.biz</code>) → สร้าง <b>Messaging API channel</b> ผูกกับ OA ของคุณ</Step>
        <Step n={3}>แท็บ <b>Messaging API</b> → หา <b>Channel access token</b> → กด <b>Issue</b> → คัดลอกมาวางด้านบน แล้วกด "เชื่อมต่อ LINE"</Step>
        <Step n={4}>หลังเชื่อมต่อ → คัดลอก <b>Webhook URL</b> (ด้านบน) ไปวางในช่อง <b>Webhook URL</b> ของ console → เปิด <b>Use webhook</b></Step>
        <Step n={5}>คัดลอก <b>Channel Secret</b> (แท็บ Basic settings) มาใส่ในช่องด้านบน เพื่อยืนยันความปลอดภัยของ webhook</Step>
        <Step n={6}>ให้ผู้ปกครอง <b>แอด Official Account เป็นเพื่อน</b> แล้ว <b>พิมพ์ "รหัสเชื่อมต่อ"</b> ของบุตรหลาน (ดูได้ในโปรไฟล์นักเรียนแต่ละคน) — ระบบจะจับคู่ให้อัตโนมัติ ✓</Step>
        <div style={{ marginTop:6, padding:'11px 14px', background:'var(--primary-soft)', borderRadius:10,
          fontSize:12.5, color:'var(--primary-ink)', lineHeight:1.6 }}>
          💡 Token และ Secret เก็บไว้ในระบบแบบไม่แสดงซ้ำ — ถ้าต้องเปลี่ยนให้ใส่ค่าใหม่ทับได้เลย
        </div>
      </SettingsCard>
    </>
  );
}
