// ============ Main app — auth + routing + Supabase boot ============
const { useState: useS, useEffect: useE } = React;

const getNav = (role) => ({
  student: [
    { id:'home', label:'หน้าหลัก · Home', icon:'home' },
    { id:'upload', label:'อัปโหลด · Upload', icon:'upload' },
    { id:'gallery', label:'คลังผลงาน · Gallery', icon:'gallery' },
    { id:'profile', label:'โปรไฟล์ · Profile', icon:'user' },
  ],
  teacher: [
    { id:'home', label:'ภาพรวม · Dashboard', icon:'home' },
    { id:'submissions', label:'ผลงานส่ง · Submissions', icon:'file',
      badge: (window.DATA.works || []).filter(w => w.status !== 'graded').length || undefined },
    { id:'gallery', label:'คลังผลงาน · Gallery', icon:'gallery' },
    { id:'groups', label:'จัดการกลุ่ม · Groups', icon:'users' },
    { id:'profile', label:'โปรไฟล์ · Profile', icon:'user' },
  ],
  admin: [
    { id:'home', label:'ภาพรวม · Overview', icon:'home' },
    { id:'users', label:'ผู้ใช้งาน · Users', icon:'users' },
    { id:'classes', label:'ห้องเรียน · Classes', icon:'book' },
    { id:'settings', label:'ตั้งค่า · Settings', icon:'settings' },
  ],
})[role];

const TITLES = {
  student: {
    home: ['หน้าหลัก', '· Home'],
    upload: ['อัปโหลดผลงาน', '· Upload'],
    gallery: ['คลังผลงาน', '· Gallery'],
    profile: ['โปรไฟล์ของฉัน', '· Profile'],
  },
  teacher: {
    home: ['Dashboard', ''],
    submissions: ['ผลงานส่งเข้ามา', '· Submissions'],
    gallery: ['คลังผลงาน', '· Gallery'],
    groups: ['จัดการกลุ่ม', '· Groups'],
    profile: ['โปรไฟล์ของฉัน', '· My Profile'],
  },
  admin: {
    home: ['Overview', ''],
    users: ['ผู้ใช้งาน', '· Users'],
    classes: ['ห้องเรียน', '· Classes'],
    settings: ['ตั้งค่า', '· Settings'],
  },
};

function BootScreen({ message, error }) {
  return (
    <div style={{
      minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center',
      flexDirection:'column', gap:14, fontFamily:'var(--font-sans, system-ui)',
      background:'var(--paper, #f8f5ef)', color:'var(--ink, #2a2a2a)', padding:24, textAlign:'center'
    }}>
      <div style={{fontFamily:'var(--font-serif)', fontSize:42, fontWeight:500, letterSpacing:'-.02em'}}>
        CMUDS<span style={{opacity:.5}}>-</span>ITPC
      </div>
      {!error ? (
        <>
          <div style={{width:24, height:24, borderRadius:99, border:'3px solid #ddd', borderTopColor:'var(--brand-500, #6f43c0)', animation:'spin .8s linear infinite'}} />
          <div className="muted" style={{fontSize:13}}>{message || 'กำลังเชื่อมต่อระบบ…'}</div>
          <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
        </>
      ) : (
        <div style={{maxWidth:520, fontSize:13.5, padding:'14px 16px', borderRadius:12, background:'oklch(0.97 0.04 25)', border:'1px solid oklch(0.85 0.08 25)', color:'oklch(0.4 0.18 25)'}}>
          <div style={{fontWeight:600, marginBottom:6}}>เชื่อมต่อฐานข้อมูลไม่สำเร็จ</div>
          <div style={{fontSize:12.5, whiteSpace:'pre-wrap'}}>{error}</div>
          <div style={{marginTop:10, fontSize:12, opacity:.85}}>ตรวจสอบไฟล์ <code>supabase-config.js</code> และสคีมาในฐานข้อมูล</div>
        </div>
      )}
    </div>
  );
}

function App() {
  const [booting, setBooting] = useS(true);
  const [bootErr, setBootErr] = useS(null);
  const [auth, setAuth] = useS(null);
  const [page, setPage] = useS('home');
  const [openWork, setOpenWork] = useS(null);
  const [sidebarOpen, setSidebarOpen] = useS(false);
  const [, forceTick] = useS(0);

  // Bootstrap: load all DB data + restore prior session
  useE(() => {
    (async () => {
      try {
        await window.DB.loadAll();
        const session = await window.AUTH.restore();
        if (session) setAuth(session);
      } catch (e) {
        console.error('Boot error', e);
        setBootErr(e.message || String(e));
      } finally {
        setBooting(false);
      }
    })();
  }, []);

  const refresh = async () => {
    await window.DB.loadAll();
    forceTick(t => t + 1);
  };

  const handleLogin = async (info) => {
    setAuth(info);
    setPage('home');
    setSidebarOpen(false);
    // re-load data with the now-authenticated session (RLS may unlock more rows)
    await refresh();
  };

  const handleLogout = async () => {
    await window.AUTH.signOut();
    setAuth(null);
    setPage('home');
    setOpenWork(null);
    setSidebarOpen(false);
  };

  if (booting) return <BootScreen />;
  if (bootErr) return <BootScreen error={bootErr} />;

  if (!auth) {
    return (
      <div data-screen-label="Login">
        <LoginScreen onLogin={handleLogin} />
      </div>
    );
  }

  const role = auth.role;
  const me = role === 'student'
    ? H.byId(DATA.students, auth.userId)
    : role === 'teacher'
      ? H.byId(DATA.teachers, auth.userId)
      : DATA.admin || { id:'admin', name:'ผู้ดูแลระบบ', nameEn:'System Admin', initial:'A', color:'oklch(0.30 0.02 290)', role:'admin', email:'admin@cmuds.local' };

  if (!me) {
    return <BootScreen error={`ไม่พบโปรไฟล์สำหรับผู้ใช้นี้ (user_id: ${auth.userId}) — กรุณาตรวจสอบ profiles table`} />;
  }

  const [titleTh, titleEn] = TITLES[role][page] || ['', ''];

  const renderScreen = () => {
    const open = (w) => setOpenWork(w);
    const nav = (p) => { setPage(p); setSidebarOpen(false); };
    const ctx = { refresh };

    if (role === 'student') {
      if (page === 'home')    return <StudentHome me={me} onOpen={open} onNav={nav} />;
      if (page === 'upload')  return <StudentUpload me={me} onDone={()=>setPage('gallery')} />;
      if (page === 'gallery') return <Gallery me={me} role="student" onOpen={open} />;
      if (page === 'profile') return <StudentProfile me={me} onOpen={open} />;
    }
    if (role === 'teacher') {
      if (page === 'home')        return <TeacherHome me={me} onOpen={open} onNav={nav} />;
      if (page === 'submissions') return <TeacherSubmissions onOpen={open} />;
      if (page === 'gallery')     return <Gallery me={me} role="teacher" onOpen={open} />;
      if (page === 'groups')      return <TeacherGroups onOpen={open} />;
      if (page === 'profile')     return <TeacherProfile me={me} />;
    }
    if (role === 'admin') {
      if (page === 'home')     return <AdminHome onNav={nav} />;
      if (page === 'users')    return <AdminUsers />;
      if (page === 'classes')  return <AdminClasses />;
      if (page === 'settings') return (
        <div className="content">
          <div style={{fontSize:20, fontWeight:600, marginBottom:8}}>ตั้งค่าระบบ <span className="tag-en">· settings</span></div>
          <div className="muted" style={{fontSize:12.5, marginBottom:16}}>ปรับแต่งข้อมูลโรงเรียน วิชา และฟีเจอร์ของระบบ</div>
          <div className="card card-pad col" style={{gap:16, maxWidth:720}}>
            <div className="field"><label>ชื่อโรงเรียน · School Name</label><input className="input" defaultValue="โรงเรียนสาธิตมหาวิทยาลัยเชียงใหม่ ระดับอนุบาลและประถมศึกษา" /></div>
            <div className="field"><label>School Name (English)</label><input className="input" defaultValue="Chiang Mai University Demonstration School, Kindergarten and Primary Levels" /></div>
            <div className="field"><label>ชื่อวิชา · Subject</label><input className="input" defaultValue="Art & 2D Animation" /></div>
            <div className="row" style={{gap:12}}>
              <div className="field" style={{flex:1}}>
                <label>ภาคเรียน · Semester</label>
                <input className="input" defaultValue="เทอม 2 / ปีการศึกษา 2569" placeholder="เช่น เทอม 2 / ปีการศึกษา 2569" />
                <div className="muted" style={{fontSize:11, marginTop:2}}>พิมพ์ภาคเรียนได้อิสระ — รูปแบบใดก็ได้</div>
              </div>
              <div className="field" style={{flex:1}}><label>ภาษาเริ่มต้น · Default Language</label>
                <div className="seg" style={{alignSelf:'flex-start', marginTop:2}}>
                  <button className="on">ไทย</button>
                  <button>English</button>
                </div>
              </div>
            </div>
            <div className="field">
              <label>ฟีเจอร์ที่เปิดใช้งาน · Features</label>
              <div className="col" style={{gap:8, marginTop:6}}>
                {['ให้นักเรียนคอมเมนต์เพื่อนได้', 'ให้ดาวน์โหลดผลงานเพื่อน', 'แสดงพัฒนาการแบบไทม์ไลน์', 'ให้นักเรียนเปลี่ยนรหัสผ่านเอง', 'ให้นักเรียนอัปโหลดรูปโปรไฟล์'].map((f,i)=>(
                  <label key={f} className="row" style={{gap:8, fontSize:13}}><input type="checkbox" defaultChecked={i!==1} /> {f}</label>
                ))}
              </div>
            </div>
            <div className="row" style={{gap:8, justifyContent:'flex-end', marginTop:6}}>
              <button className="btn btn-ghost">รีเซ็ต</button>
              <button className="btn btn-brand"><Icon name="check" size={12} /> บันทึก</button>
            </div>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="app-root" data-screen-label={`${role} / ${page}`}>
      <div className="layout">
        <Sidebar
          items={getNav(role)}
          current={page}
          onSelect={(p)=>{ setPage(p); setSidebarOpen(false); }}
          user={me}
          role={role === 'student' ? 'นักเรียน · Student' : role === 'teacher' ? 'ครู · Teacher' : 'ผู้ดูแลระบบ · Admin'}
          open={sidebarOpen}
          onLogout={handleLogout}
        />
        <div className="main">
          <TopBar
            titleTh={titleTh}
            titleEn={titleEn}
            onMenu={()=>setSidebarOpen(!sidebarOpen)}
            right={(
              <div className="row" style={{gap:8}}>
                <button className="btn btn-ghost sm" title="ค้นหา"><Icon name="search" size={16} /></button>
                <button className="btn btn-ghost sm" title="การแจ้งเตือน" style={{position:'relative'}}>
                  <Icon name="bell" size={16} />
                  <span style={{position:'absolute', top:4, right:6, width:7, height:7, borderRadius:99, background:'var(--warm-500)'}}></span>
                </button>
              </div>
            )}
          />
          {renderScreen()}
        </div>
      </div>
      {openWork && (
        <WorkDetail
          work={openWork}
          asPerson={me}
          role={role}
          onClose={()=>setOpenWork(null)}
          onChanged={refresh}
        />
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
