// student.jsx — Student app (iOS frame contents)

const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS } = React;

// ─── Bottom nav ─────────────────────────────────────────────
function StudentTabBar({ tab, setTab, t }) {
  const items = [
    { id: 'home',    label: t.home,    icon: 'home' },
    { id: 'list',    label: t.myReports, icon: 'list' },
    { id: 'profile', label: t.profile, icon: 'user' },
  ];
  return (
    <div style={{
      position: 'absolute', left: 12, right: 12, bottom: 28,
      background: 'rgba(255,255,255,0.78)',
      backdropFilter: 'blur(28px) saturate(180%)',
      WebkitBackdropFilter: 'blur(28px) saturate(180%)',
      border: '1px solid rgba(255,255,255,0.6)',
      borderRadius: 28,
      padding: 6,
      display: 'flex',
      boxShadow: '0 12px 32px rgba(45,30,110,0.18)',
      zIndex: 30,
    }}>
      {items.map(it => {
        const active = tab === it.id;
        return (
          <button key={it.id}
            onClick={() => setTab(it.id)}
            style={{
              flex: 1, appearance: 'none', border: 0,
              background: active ? 'var(--bp-grad)' : 'transparent',
              color: active ? '#fff' : 'var(--bp-ink-2)',
              padding: '10px 8px', borderRadius: 22,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              fontSize: 10.5, fontWeight: 500, cursor: 'pointer',
              boxShadow: active ? '0 6px 14px rgba(80,50,180,0.30)' : 'none',
              transition: 'background .18s ease, color .18s ease',
            }}>
            <Icon name={it.icon} size={20} strokeWidth={active ? 2 : 1.6}/>
            <span>{it.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ─── Home screen ────────────────────────────────────────────
function StudentHome({ t, lang, reports, user, goTo, startReport }) {
  const hour = new Date().getHours();
  const greet = hour < 12 ? t.greetingMorning : hour < 17 ? t.greeting : t.greetingEvening;

  const mine = reports.filter(r => r.reporter === user.name || r.mine);
  const recent = mine.slice(0, 3);
  const resolvedCount = mine.filter(r => r.status === 'resolved').length;
  const inProgressCount = mine.filter(r => r.status === 'in-progress').length;

  return (
    <div style={{ padding: '0 0 110px', minHeight: '100%' }}>
      {/* Hero gradient header */}
      <div style={{
        background: 'var(--bp-grad)',
        padding: '60px 22px 100px',
        color: '#fff',
        position: 'relative',
        overflow: 'hidden',
      }}>
        {/* decorative orbs */}
        <div style={{
          position:'absolute', right:-40, top:-30, width:180, height:180, borderRadius:'50%',
          background:'radial-gradient(circle, rgba(255,255,255,0.22), transparent 70%)',
        }}/>
        <div style={{
          position:'absolute', left:-50, bottom:-60, width:200, height:200, borderRadius:'50%',
          background:'radial-gradient(circle, rgba(255,255,255,0.14), transparent 70%)',
        }}/>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Logomark size={36} light/>
            <div style={{ lineHeight: 1.15 }}>
              <div style={{ fontFamily: 'Space Grotesk', fontWeight: 600, fontSize: 16, letterSpacing: '-0.01em' }}>Bodin plus</div>
              <div style={{ fontSize: 11, opacity: 0.85 }}>{t.schoolName}</div>
            </div>
          </div>
          <button onClick={() => goTo('notifications')} style={{
            appearance:'none', border:0, background:'rgba(255,255,255,0.18)',
            width:38, height:38, borderRadius:'50%', color:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
            position:'relative',
          }}>
            <Icon name="bell" size={18}/>
            <span style={{
              position:'absolute', top:6, right:6, width:8, height:8, borderRadius:'50%',
              background:'oklch(0.75 0.22 25)', border:'1.5px solid var(--bp-indigo)',
            }}/>
          </button>
        </div>

        <div style={{ marginTop: 28, position: 'relative' }}>
          <div style={{ fontSize: 14, opacity: 0.88, fontWeight: 400 }}>{greet},</div>
          <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.015em', marginTop: 2 }}>
            {user.name} <span style={{ opacity: 0.7, fontSize: 16, fontWeight: 400 }}>· {user.grade}</span>
          </div>
        </div>
      </div>

      {/* Primary action card — overlapping the hero */}
      <div style={{ padding: '0 16px', marginTop: -70, position: 'relative', zIndex: 2 }}>
        <button onClick={startReport} style={{
          width:'100%', appearance:'none', border:0, cursor:'pointer',
          background:'var(--bp-surface)',
          borderRadius: 22,
          padding: '18px 18px',
          textAlign:'left',
          boxShadow: '0 12px 32px rgba(45,30,110,0.16), 0 0 0 1px rgba(45,30,110,0.04)',
          display:'flex', alignItems:'center', gap:14,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: 16,
            background:'var(--bp-grad)',
            display:'flex', alignItems:'center', justifyContent:'center',
            color:'#fff', boxShadow: '0 8px 18px rgba(80,50,180,0.30)',
          }}>
            <Icon name="camera" size={26} strokeWidth={1.8}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 17, fontWeight: 600, color: 'var(--bp-ink)' }}>{t.reportIssue}</div>
            <div style={{ fontSize: 12.5, color: 'var(--bp-ink-3)', marginTop: 2 }}>{t.reportIssueSub}</div>
          </div>
          <Icon name="arrow_r" size={18} stroke="var(--bp-ink-3)"/>
        </button>

        {/* Stats row */}
        <div style={{ display:'flex', gap: 10, marginTop: 14 }}>
          <StatPill icon="list" label={t.myReports} value={mine.length} tint="var(--bp-blue)"/>
          <StatPill icon="clock" label={t.inProgress} value={inProgressCount} tint="oklch(0.62 0.20 290)"/>
          <StatPill icon="check" label={t.resolved} value={resolvedCount} tint="oklch(0.55 0.16 155)"/>
        </div>

        {/* Recent */}
        <div style={{ marginTop: 28 }}>
          <SectionHeader title={t.recent} action={t.seeAll} onAction={() => goTo('list')}/>
          <div style={{ display:'flex', flexDirection:'column', gap: 10, marginTop: 10 }}>
            {recent.length === 0 && (
              <div style={{
                padding: 24, textAlign: 'center', color: 'var(--bp-ink-3)',
                background: 'var(--bp-soft)', borderRadius: 16, fontSize: 13,
              }}>
                ยังไม่มีรายการ — เริ่มจากปุ่มด้านบนได้เลย
              </div>
            )}
            {recent.map(r => (
              <ReportRow key={r.id} r={r} t={t} lang={lang} onClick={() => goTo('detail', r.id)}/>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function SectionHeader({ title, action, onAction }) {
  return (
    <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between' }}>
      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--bp-ink)' }}>{title}</div>
      {action && (
        <button onClick={onAction} style={{
          appearance:'none', border:0, background:'transparent',
          color:'var(--bp-blue)', fontSize: 12.5, fontWeight: 500, cursor:'pointer',
        }}>{action} ›</button>
      )}
    </div>
  );
}

function StatPill({ icon, label, value, tint }) {
  return (
    <div style={{
      flex: 1, padding: '12px 12px', borderRadius: 16,
      background: 'var(--bp-surface)', border:'1px solid var(--bp-line)',
      boxShadow:'var(--bp-shadow-sm)',
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: 8, background: tint + '1A',
        color: tint, display:'flex', alignItems:'center', justifyContent:'center',
        marginBottom: 6,
      }}><Icon name={icon} size={14}/></div>
      <div className="font-num" style={{ fontSize: 18, fontWeight: 600, color: 'var(--bp-ink)' }}>{value}</div>
      <div style={{ fontSize: 10.5, color: 'var(--bp-ink-3)', marginTop: 1 }}>{label}</div>
    </div>
  );
}

// ─── Report row (compact card) ─────────────────────────────
function ReportRow({ r, t, lang, onClick }) {
  const cat = CAT_BY_ID[r.category];
  return (
    <button onClick={onClick} style={{
      appearance:'none', border:0, background:'var(--bp-surface)', cursor:'pointer',
      borderRadius: 14, padding: 12, textAlign:'left',
      display:'flex', gap: 12, alignItems:'stretch',
      border:'1px solid var(--bp-line)',
      width: '100%',
    }}>
      <div style={{ width: 64, height: 64, flexShrink: 0 }}>
        <Photo hue={r.before.hue} label={r.before.label} url={r.before.url} tag="" height={64} style={{ borderRadius: 12, padding: 0 }}/>
      </div>
      <div style={{ flex: 1, minWidth: 0, display:'flex', flexDirection:'column', justifyContent:'space-between' }}>
        <div>
          <div style={{
            fontSize: 13.5, fontWeight: 500, color: 'var(--bp-ink)',
            lineHeight: 1.3, marginBottom: 4,
            display:'-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient:'vertical', overflow:'hidden',
          }}>{lang === 'th' ? r.title : r.titleEn}</div>
          <div style={{ display:'flex', gap: 6, alignItems:'center' }}>
            <CategoryChip cat={cat} lang={lang}/>
          </div>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop: 6 }}>
          <span style={{ fontSize: 10.5, color: 'var(--bp-ink-3)' }}>{relTime(r.submittedAt, lang)}</span>
          <StatusPill status={r.status} lang={lang} t={t}/>
        </div>
      </div>
    </button>
  );
}

// ─── Camera screen ─────────────────────────────────────────
function StudentCamera({ t, goBack, onCapture }) {
  const [preview, setPreview] = useStateS(null); // { file, dataUrl }
  const cameraRef = React.useRef(null);
  const galleryRef = React.useRef(null);

  function pick(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => setPreview({ file, dataUrl: ev.target.result });
    reader.readAsDataURL(file);
    e.target.value = '';
  }

  return (
    <div style={{ height: '100%', display:'flex', flexDirection:'column', background:'#000', color:'#fff', position:'relative' }}>
      {/* hidden inputs */}
      <input ref={cameraRef} type="file" accept="image/*" capture="environment" onChange={pick} style={{ display:'none' }}/>
      <input ref={galleryRef} type="file" accept="image/*" onChange={pick} style={{ display:'none' }}/>

      {/* top bar */}
      <div style={{
        position:'absolute', top: 56, left: 16, right: 16, zIndex: 5,
        display:'flex', alignItems:'center', justifyContent:'flex-start',
      }}>
        <IOSGlassPill dark>
          <button onClick={goBack} style={{
            width: 36, height: 36, appearance:'none', border:0, background:'transparent',
            color:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center',
          }}><Icon name="close" size={16} stroke="#fff"/></button>
        </IOSGlassPill>
      </div>

      {/* viewfinder */}
      <div style={{ flex: 1, display:'flex', alignItems:'center', justifyContent:'center', padding: '110px 20px 220px', position:'relative' }}>
        {!preview ? (
          <button onClick={() => cameraRef.current?.click()} style={{
            width:'100%', aspectRatio: '3 / 4', borderRadius: 22,
            appearance:'none', border:0, cursor:'pointer',
            background:
              `repeating-linear-gradient(135deg, rgba(255,255,255,0.04) 0, rgba(255,255,255,0.04) 14px, transparent 14px, transparent 28px),
               linear-gradient(160deg, oklch(0.35 0.18 270), oklch(0.40 0.22 295))`,
            position:'relative', overflow:'hidden', color:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            {['tl','tr','bl','br'].map(corner => (
              <div key={corner} style={{
                position:'absolute',
                top: corner.startsWith('t') ? 18 : 'auto',
                bottom: corner.startsWith('b') ? 18 : 'auto',
                left: corner.endsWith('l') ? 18 : 'auto',
                right: corner.endsWith('r') ? 18 : 'auto',
                width: 22, height: 22,
                borderTop: corner.startsWith('t') ? '2px solid rgba(255,255,255,0.85)' : 'none',
                borderBottom: corner.startsWith('b') ? '2px solid rgba(255,255,255,0.85)' : 'none',
                borderLeft: corner.endsWith('l') ? '2px solid rgba(255,255,255,0.85)' : 'none',
                borderRight: corner.endsWith('r') ? '2px solid rgba(255,255,255,0.85)' : 'none',
                borderRadius: 4,
              }}/>
            ))}
            <div style={{ textAlign:'center', color:'rgba(255,255,255,0.85)', fontFamily:'IBM Plex Mono', fontSize: 11 }}>
              <div style={{ fontSize: 28, marginBottom: 6 }}><Icon name="camera" size={28}/></div>
              แตะเพื่อเปิดกล้อง / TAP TO OPEN CAMERA
            </div>
          </button>
        ) : (
          <div style={{
            width: '100%', aspectRatio: '3 / 4', borderRadius: 22,
            background: `url(${preview.dataUrl}) center/cover no-repeat`,
            border:'1px solid rgba(255,255,255,0.18)',
          }}/>
        )}
      </div>

      {/* bottom controls */}
      <div style={{
        position:'absolute', bottom: 0, left: 0, right: 0, padding: '24px 24px 50px',
        display:'flex', alignItems:'center', justifyContent: 'space-around', gap: 16,
      }}>
        {!preview ? (
          <>
            <CamButton icon="image" label="คลังภาพ" onClick={() => galleryRef.current?.click()}/>
            <button onClick={() => cameraRef.current?.click()} style={{
              width: 76, height: 76, borderRadius:'50%',
              background:'#fff', border:'4px solid rgba(255,255,255,0.3)',
              cursor:'pointer', boxShadow:'0 0 0 2px #fff inset',
            }}/>
            <CamButton icon="refresh" label="กลับด้าน" onClick={() => cameraRef.current?.click()}/>
          </>
        ) : (
          <>
            <button onClick={() => setPreview(null)} style={{
              flex: 1, padding:'14px 18px', borderRadius: 16,
              background:'rgba(255,255,255,0.16)', color:'#fff', border:0,
              fontSize: 14, fontWeight: 500, cursor:'pointer',
            }}>{t.retake}</button>
            <button onClick={() => onCapture({ file: preview.file, dataUrl: preview.dataUrl, label: 'PHOTO' })} style={{
              flex: 1.4, padding:'14px 18px', borderRadius: 16,
              background:'var(--bp-grad)', color:'#fff', border:0,
              fontSize: 14, fontWeight: 600, cursor:'pointer',
              boxShadow:'0 8px 22px rgba(80,50,180,0.4)',
              display:'flex', alignItems:'center', justifyContent:'center', gap: 8,
            }}>{t.usePhoto} <Icon name="arrow_r" size={16}/></button>
          </>
        )}
      </div>
    </div>
  );
}

function CamButton({ icon, label, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 50, height: 50, borderRadius: 14,
      background:'rgba(255,255,255,0.14)', color:'#fff', border: 0,
      display:'flex', alignItems:'center', justifyContent:'center',
      cursor:'pointer',
    }}>
      <Icon name={icon} size={20}/>
    </button>
  );
}

// ─── Form screen ─────────────────────────────────────────
function StudentForm({ t, lang, photo, goBack, onSubmit }) {
  const [category, setCategory] = useStateS(null);
  const [desc, setDesc] = useStateS('');
  const [location, setLocation] = useStateS('');

  const canSubmit = category && desc.trim() && location.trim();

  return (
    <div style={{ padding: '52px 18px 130px', minHeight: '100%' }}>
      {/* top bar */}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 18 }}>
        <button onClick={goBack} style={{
          appearance:'none', border:0, background:'rgba(45,30,110,0.06)',
          width: 36, height: 36, borderRadius:'50%',
          display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
        }}><Icon name="chev_l" size={18}/></button>
        <div style={{ fontSize: 16, fontWeight: 600 }}>{t.addDetails}</div>
        <div style={{ width: 36 }}/>
      </div>

      {/* photo preview */}
      <div style={{ marginBottom: 18 }}>
        <Photo hue={photo?.hue} label={photo?.label} url={photo?.dataUrl || photo?.url} tag="BEFORE" height={180} style={{ borderRadius: 16, padding: 12 }}/>
      </div>

      {/* category */}
      <FormLabel>{t.category} <span style={{ color: 'oklch(0.60 0.22 25)' }}>*</span></FormLabel>
      <div style={{
        display:'grid', gridTemplateColumns:'1fr 1fr', gap: 8,
        marginBottom: 18,
      }}>
        {CATEGORIES.map(c => {
          const active = category === c.id;
          return (
            <button key={c.id} onClick={() => setCategory(c.id)} style={{
              appearance:'none', cursor:'pointer',
              padding:'10px 12px', borderRadius: 12,
              border: active ? `1.5px solid ${c.tint}` : '1px solid var(--bp-line)',
              background: active ? c.tint + '12' : 'var(--bp-surface)',
              display:'flex', alignItems:'center', gap: 9,
              textAlign:'left',
              fontFamily:'inherit',
              transition: 'border-color .12s ease, background .12s ease',
            }}>
              <span style={{
                width: 26, height: 26, borderRadius: 7,
                background: c.tint, color:'#fff',
                display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
              }}><Icon name={CAT_ICONS[c.id]} size={13} strokeWidth={2}/></span>
              <span style={{ fontSize: 11.5, fontWeight: 500, color:'var(--bp-ink)', lineHeight: 1.15 }}>
                {c[lang]}
              </span>
            </button>
          );
        })}
      </div>

      {/* description */}
      <FormLabel>{t.description} <span style={{ color: 'oklch(0.60 0.22 25)' }}>*</span></FormLabel>
      <textarea value={desc} onChange={e => setDesc(e.target.value)}
        placeholder={t.descPlaceholder} rows={4} style={inputStyle('textarea')}/>

      {/* location */}
      <FormLabel style={{ marginTop: 14 }}>
        <span style={{ display:'inline-flex', alignItems:'center', gap: 6 }}>
          <Icon name="pin" size={14}/> {t.location} <span style={{ color: 'oklch(0.60 0.22 25)' }}>*</span>
        </span>
      </FormLabel>
      <input value={location} onChange={e => setLocation(e.target.value)}
        placeholder={t.locPlaceholder} style={inputStyle('input')}/>

      {/* Submit — sticky bottom in flow */}
      <button disabled={!canSubmit}
        onClick={() => onSubmit({ category, desc, location })}
        style={{
          width:'100%', marginTop: 24,
          appearance:'none', border: 0, cursor: canSubmit ? 'pointer' : 'not-allowed',
          padding: '15px 18px', borderRadius: 16,
          background: canSubmit ? 'var(--bp-grad)' : 'oklch(0.88 0.02 270)',
          color:'#fff', fontSize: 15, fontWeight: 600,
          boxShadow: canSubmit ? '0 10px 24px rgba(80,50,180,0.30)' : 'none',
          display:'flex', alignItems:'center', justifyContent:'center', gap: 8,
        }}>
        {t.submit} <Icon name="arrow_r" size={18}/>
      </button>
    </div>
  );
}

function FormLabel({ children, style }) {
  return (
    <div style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--bp-ink-2)', marginBottom: 7, ...style }}>
      {children}
    </div>
  );
}

function inputStyle(kind) {
  return {
    width:'100%', appearance:'none',
    padding: kind === 'textarea' ? '12px 14px' : '12px 14px',
    borderRadius: 12, border:'1px solid var(--bp-line)',
    background:'var(--bp-surface)', fontFamily:'inherit', fontSize: 13.5,
    color:'var(--bp-ink)', outline:'none',
    resize: kind === 'textarea' ? 'vertical' : undefined,
    minHeight: kind === 'textarea' ? 96 : undefined,
    boxSizing: 'border-box',
  };
}

// ─── Success screen ─────────────────────────────────────
function StudentSuccess({ t, lang, report, goHome, goList }) {
  return (
    <div style={{
      height: '100%', padding: '70px 22px 40px',
      display:'flex', flexDirection:'column',
      background:'var(--bp-grad-soft)',
    }}>
      <div style={{ flex: 1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', textAlign:'center' }}>
        {/* animated check */}
        <div style={{
          width: 96, height: 96, borderRadius:'50%',
          background:'var(--bp-grad)', color:'#fff',
          display:'flex', alignItems:'center', justifyContent:'center',
          boxShadow:'0 16px 40px rgba(80,50,180,0.30)',
          animation: 'bp-pop 0.5s cubic-bezier(.2,1.2,.4,1)',
        }}>
          <Icon name="check" size={48} strokeWidth={2.4}/>
        </div>
        <div style={{ fontSize: 22, fontWeight: 700, marginTop: 22, color:'var(--bp-ink)' }}>{t.submitted}</div>
        <div style={{ fontSize: 13.5, color:'var(--bp-ink-2)', marginTop: 6, maxWidth: 280, lineHeight: 1.45 }}>
          {t.submittedSub}
        </div>

        <div style={{ marginTop: 22, fontSize: 11, fontFamily:'IBM Plex Mono', color:'var(--bp-ink-3)' }}>
          REPORT ID · {report.id}
        </div>
      </div>

      <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
        <button onClick={goList} style={{
          appearance:'none', border: 0, cursor:'pointer',
          padding:'14px 18px', borderRadius: 16,
          background:'var(--bp-grad)', color:'#fff',
          fontSize: 14, fontWeight: 600,
          boxShadow:'0 10px 24px rgba(80,50,180,0.28)',
        }}>{t.viewMine}</button>
        <button onClick={goHome} style={{
          appearance:'none', border:'1px solid var(--bp-line)', cursor:'pointer',
          padding:'12px 18px', borderRadius: 16,
          background:'var(--bp-surface)', color:'var(--bp-ink)',
          fontSize: 14, fontWeight: 500,
        }}>{t.backToHome}</button>
      </div>
    </div>
  );
}

// ─── List screen ─────────────────────────────────────
function StudentList({ t, lang, reports, user, goTo }) {
  const [filter, setFilter] = useStateS('all');
  const mine = reports.filter(r => r.reporter === user.name || r.mine);
  const shown = filter === 'all' ? mine : mine.filter(r => r.status === filter);

  const filters = [
    { id: 'all', label: 'ทั้งหมด' },
    { id: 'pending', label: t.pending },
    { id: 'in-progress', label: t.inProgress },
    { id: 'resolved', label: t.resolved },
  ];

  return (
    <div style={{ padding: '60px 16px 110px', minHeight: '100%' }}>
      <div style={{ fontSize: 26, fontWeight: 700, color:'var(--bp-ink)', letterSpacing:'-0.015em' }}>
        {t.myReports}
      </div>
      <div style={{ fontSize: 13, color:'var(--bp-ink-3)', marginTop: 4 }}>
        {mine.length} {lang === 'th' ? 'รายการ' : 'reports'}
      </div>

      <div style={{ display:'flex', gap: 6, marginTop: 18, overflowX:'auto', paddingBottom: 4 }}>
        {filters.map(f => {
          const active = filter === f.id;
          return (
            <button key={f.id} onClick={() => setFilter(f.id)} style={{
              appearance:'none', border:0, cursor:'pointer',
              padding:'8px 14px', borderRadius: 999,
              background: active ? 'var(--bp-grad)' : 'var(--bp-soft)',
              color: active ? '#fff' : 'var(--bp-ink-2)',
              fontSize: 12, fontWeight: 500, whiteSpace:'nowrap',
              boxShadow: active ? '0 4px 10px rgba(80,50,180,0.25)' : 'none',
            }}>{f.label}</button>
          );
        })}
      </div>

      <div style={{ display:'flex', flexDirection:'column', gap: 10, marginTop: 18 }}>
        {shown.map(r => (
          <ReportRow key={r.id} r={r} t={t} lang={lang} onClick={() => goTo('detail', r.id)}/>
        ))}
        {shown.length === 0 && (
          <div style={{
            padding: 36, textAlign:'center', color:'var(--bp-ink-3)',
            background:'var(--bp-soft)', borderRadius: 16, fontSize: 13,
          }}>ไม่พบรายการในหมวดนี้</div>
        )}
      </div>
    </div>
  );
}

// ─── Detail screen (read-only timeline view) ─────────────────────
function StudentDetail({ t, lang, report: r, goBack }) {
  const cat = CAT_BY_ID[r.category];
  if (!r) return null;
  return (
    <div style={{ padding: '0 0 90px', minHeight: '100%' }}>
      {/* Photo header */}
      <div style={{ position:'relative' }}>
        <Photo hue={r.before.hue} label={r.before.label} url={r.before.url} tag="BEFORE" height={280} style={{ borderRadius: 0, padding: 22, paddingTop: 70 }}/>
        <button onClick={goBack} style={{
          position:'absolute', top: 56, left: 16, zIndex: 5,
          width: 36, height: 36, borderRadius:'50%',
          background:'rgba(255,255,255,0.85)', backdropFilter:'blur(12px)',
          border:0, cursor:'pointer',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}><Icon name="chev_l" size={18}/></button>
      </div>

      <div style={{ padding:'20px 18px' }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <CategoryChip cat={cat} lang={lang} size="lg"/>
          <StatusPill status={r.status} lang={lang} t={t}/>
        </div>

        <div style={{ fontSize: 18, fontWeight: 600, marginTop: 14, color:'var(--bp-ink)', lineHeight: 1.3 }}>
          {lang === 'th' ? r.title : r.titleEn}
        </div>
        <div style={{ fontSize: 13.5, color:'var(--bp-ink-2)', marginTop: 8, lineHeight: 1.55 }}>
          {lang === 'th' ? r.desc : r.descEn}
        </div>

        <div style={{ display:'flex', gap: 14, marginTop: 16, fontSize: 12, color:'var(--bp-ink-3)' }}>
          <span style={{ display:'inline-flex', alignItems:'center', gap: 4 }}>
            <Icon name="pin" size={13}/> {lang === 'th' ? r.location : r.locationEn}
          </span>
          <span style={{ display:'inline-flex', alignItems:'center', gap: 4 }}>
            <Icon name="clock" size={13}/> {relTime(r.submittedAt, lang)}
          </span>
        </div>

        {/* Progress (in-progress only) */}
        {r.status === 'in-progress' && (
          <div style={{
            marginTop: 18, padding: 14,
            background:'var(--bp-grad-soft)', borderRadius: 14,
            border:'1px solid var(--bp-line)',
          }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 8 }}>
              <span style={{ fontSize: 12, fontWeight: 600, color:'var(--bp-ink-2)' }}>
                {lang === 'th' ? 'คุณครูแก้ไขไปแล้ว' : 'Teacher progress'}
              </span>
              <span className="font-num" style={{ fontSize: 22, fontWeight: 700, color:'var(--bp-violet)', letterSpacing:'-0.01em' }}>
                {r.progress || 0}<span style={{ fontSize: 14, color:'var(--bp-ink-3)' }}>%</span>
              </span>
            </div>
            <div style={{ height: 6, borderRadius: 999, background:'rgba(255,255,255,0.7)', overflow:'hidden' }}>
              <div style={{
                width: (r.progress || 0) + '%', height:'100%',
                background:'var(--bp-grad)', borderRadius: 999,
                transition:'width .35s ease',
              }}/>
            </div>
          </div>
        )}

        {/* After photo (if resolved) */}
        {r.after && (
          <div style={{ marginTop: 22 }}>
            <FormLabel>{t.after}</FormLabel>
            <Photo hue={r.after.hue} label={r.after.label} url={r.after.url} tag="AFTER" after height={170} style={{ borderRadius: 14, padding: 14 }}/>
          </div>
        )}

        {/* Timeline */}
        <div style={{ marginTop: 24 }}>
          <FormLabel>{t.timelineEvents}</FormLabel>
          <Timeline events={r.timeline} t={t} lang={lang}/>
        </div>

        {r.thanks > 0 && (
          <div style={{
            marginTop: 24, padding: 16,
            borderRadius: 16, background:'var(--bp-grad-soft)',
            border:'1px solid var(--bp-line)',
            display:'flex', alignItems:'center', gap: 12,
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: 12,
              background:'var(--bp-grad)', color:'#fff',
              display:'flex', alignItems:'center', justifyContent:'center',
            }}><Icon name="heart" size={18} fill="#fff"/></div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color:'var(--bp-ink)' }}>
                คุณได้รับคำขอบคุณ {r.thanks} ครั้ง
              </div>
              <div style={{ fontSize: 11, color:'var(--bp-ink-3)' }}>จากคุณครูที่ดูแลการแก้ไข</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Timeline used by both student detail + teacher detail
function Timeline({ events, t, lang }) {
  const evMap = {
    submitted: { icon: 'plus',  th: 'ส่งรายงาน',  en: 'Submitted',   color: 'var(--bp-blue)' },
    'in-progress': { icon: 'clock', th: 'รับเรื่องและดำเนินการ', en: 'Accepted', color: 'oklch(0.55 0.18 70)' },
    progress: { icon: 'chart', th: 'อัปเดตความคืบหน้า', en: 'Progress update', color: 'oklch(0.56 0.20 265)' },
    resolved: { icon: 'check', th: 'แก้ไขเรียบร้อย', en: 'Resolved', color: 'oklch(0.55 0.16 155)' },
  };

  return (
    <div style={{ position:'relative', paddingLeft: 30 }}>
      <div style={{
        position:'absolute', left: 11, top: 6, bottom: 6,
        width: 2, background:'linear-gradient(to bottom, var(--bp-blue), var(--bp-violet) 60%, oklch(0.85 0.04 270))',
        opacity: 0.5, borderRadius: 2,
      }}/>
      {events.map(([type, ts, actor, note], i) => {
        const e = evMap[type];
        return (
          <div key={i} style={{ position:'relative', paddingBottom: 18 }}>
            <div style={{
              position:'absolute', left: -29, top: 0,
              width: 24, height: 24, borderRadius:'50%',
              background:'var(--bp-surface)', border:`2px solid ${e.color}`,
              color: e.color,
              display:'flex', alignItems:'center', justifyContent:'center',
              boxShadow:'0 2px 6px rgba(0,0,0,0.06)',
            }}>
              <Icon name={e.icon} size={11} strokeWidth={2.3}/>
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, color:'var(--bp-ink)' }}>{e[lang]}</div>
            <div style={{ fontSize: 11, color:'var(--bp-ink-3)', marginTop: 2 }}>
              {fullDateTime(ts, lang)} · <span style={{ fontWeight: 500 }}>{actor}</span>
            </div>
            {note && (
              <div style={{
                marginTop: 8, padding:'10px 12px', borderRadius: 10,
                background:'var(--bp-soft)', fontSize: 12, color:'var(--bp-ink-2)', lineHeight: 1.5,
              }}>{note}</div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ─── Profile screen ─────────────────────────────────────────
function StudentProfile({ t, lang, setLang, user, setUser, theme, setTheme }) {
  const [editingName, setEditingName] = useStateS(false);
  const [nameDraft, setNameDraft] = useStateS(user.name);
  const [showPwModal, setShowPwModal] = useStateS(false);
  const [showFeedback, setShowFeedback] = useStateS(false);

  function saveName() {
    const newName = nameDraft.trim();
    if (newName) {
      setUser({ ...user, name: newName });
      sbUpdateDisplayName(newName).catch(() => {});
    }
    setEditingName(false);
  }

  const L = lang === 'th' ? {
    editProfile: 'แก้ไขโปรไฟล์',
    nameLabel: 'ชื่อที่แสดง',
    save: 'บันทึก',
    cancel: 'ยกเลิก',
    changePw: 'เปลี่ยนรหัสผ่าน',
    changePwSub: 'ปรับปรุงรหัสผ่านเป็นประจำเพื่อความปลอดภัย',
    feedback: 'ติชม / แก้ไขเว็บไซต์',
    feedbackSub: 'แจ้งปัญหาหรือเสนอแนะการปรับปรุง',
    appearance: 'การแสดงผล',
    theme: 'ธีม',
    light: 'สว่าง',
    dark: 'มืด',
    language: 'ภาษา',
    thai: 'ไทย',
    english: 'English',
    accountSettings: 'การตั้งค่าบัญชี',
  } : {
    editProfile: 'Edit profile',
    nameLabel: 'Display name',
    save: 'Save',
    cancel: 'Cancel',
    changePw: 'Change password',
    changePwSub: 'Update your password regularly for security',
    feedback: 'Feedback / Improve site',
    feedbackSub: 'Report a problem or suggest an improvement',
    appearance: 'Appearance',
    theme: 'Theme',
    light: 'Light',
    dark: 'Dark',
    language: 'Language',
    thai: 'ไทย',
    english: 'English',
    accountSettings: 'Account settings',
  };

  return (
    <div style={{ padding: '60px 16px 110px' }}>
      <div style={{ fontSize: 26, fontWeight: 700, letterSpacing:'-0.015em', color:'var(--bp-ink)' }}>{t.profile}</div>

      {/* Profile card */}
      <div style={{
        marginTop: 18, padding: 22,
        borderRadius: 22, background:'var(--bp-grad)', color:'#fff',
        position:'relative', overflow:'hidden',
      }}>
        <div style={{ position:'absolute', right:-30, top:-30, width:140, height:140, borderRadius:'50%',
          background:'radial-gradient(circle, rgba(255,255,255,0.22), transparent 70%)' }}/>
        <div style={{ display:'flex', alignItems:'center', gap: 14, position:'relative' }}>
          <AvatarUpload
            photo={user.photo}
            name={user.name}
            onChange={(p) => { setUser({ ...user, photo: p }); sbUpdateAvatar(p).catch(() => {}); }}
            size={64}
            light
          />
          <div style={{ flex: 1, minWidth: 0 }}>
            {editingName ? (
              <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
                <input
                  autoFocus
                  value={nameDraft}
                  onChange={e => setNameDraft(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') setEditingName(false); }}
                  style={{
                    width:'100%', appearance:'none', border:0, outline:'none',
                    background:'rgba(255,255,255,0.20)', color:'#fff',
                    fontSize: 18, fontWeight: 600, fontFamily:'inherit',
                    padding:'6px 10px', borderRadius: 8,
                  }}/>
                <div style={{ display:'flex', gap: 6 }}>
                  <button onClick={saveName} style={profileEditBtn(true)}>{L.save}</button>
                  <button onClick={() => { setEditingName(false); setNameDraft(user.name); }} style={profileEditBtn(false)}>{L.cancel}</button>
                </div>
              </div>
            ) : (
              <>
                <div style={{ fontSize: 18, fontWeight: 600, display:'flex', alignItems:'center', gap: 8 }}>
                  {user.name}
                  <button onClick={() => setEditingName(true)} style={{
                    appearance:'none', border:0, cursor:'pointer',
                    background:'rgba(255,255,255,0.20)', color:'#fff',
                    width: 24, height: 24, borderRadius: 6,
                    display:'flex', alignItems:'center', justifyContent:'center',
                  }}>
                    <Icon name="edit" size={12}/>
                  </button>
                </div>
                <div style={{ fontSize: 12.5, opacity: 0.86, marginTop: 2 }}>{user.grade} · เลขที่ {user.no}</div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Settings groups */}
      <SettingGroup title={L.appearance}>
        <SettingRow icon="sparkle" tint="var(--bp-violet)" label={L.theme}>
          <Segmented value={theme} onChange={setTheme} options={[
            ['light', L.light, 'sparkle'],
            ['dark',  L.dark,  'eye'],
          ]}/>
        </SettingRow>
        <SettingRow icon="globe" tint="var(--bp-blue)" label={L.language}>
          <Segmented value={lang} onChange={setLang} options={[
            ['th', L.thai,    null],
            ['en', L.english, null],
          ]}/>
        </SettingRow>
      </SettingGroup>

      <SettingGroup title={L.accountSettings}>
        <SettingButton icon="user" tint="var(--bp-blue)" label={L.editProfile}
          detail={user.name} onClick={() => setEditingName(true)}/>
        <SettingButton icon="cog" tint="var(--bp-violet)" label={L.changePw}
          detail={L.changePwSub} onClick={() => setShowPwModal(true)}/>
        <SettingButton icon="sparkle" tint="oklch(0.62 0.18 325)" label={L.feedback}
          detail={L.feedbackSub} onClick={() => window.open('https://docs.google.com/forms/d/e/1FAIpQLSeZw2qxHID5krUdD53pM_tE9lF80IzCWCv1tmkzFk7gX1Ww5Q/viewform', '_blank', 'noopener,noreferrer')}/>
      </SettingGroup>

      {showPwModal && (
        <ChangePasswordModal lang={lang} onClose={() => setShowPwModal(false)}/>
      )}
      {showFeedback && (
        <FeedbackModal lang={lang} onClose={() => setShowFeedback(false)}/>
      )}
    </div>
  );
}

function profileEditBtn(primary) {
  return {
    appearance:'none', border:0, cursor:'pointer',
    background: primary ? '#fff' : 'rgba(255,255,255,0.18)',
    color: primary ? 'var(--bp-violet)' : '#fff',
    fontFamily:'inherit', fontSize: 11.5, fontWeight: 600,
    padding:'6px 14px', borderRadius: 8,
  };
}

function SettingGroup({ title, children }) {
  return (
    <div style={{ marginTop: 22 }}>
      <div style={{
        fontSize: 11, fontWeight: 600, color:'var(--bp-ink-3)',
        textTransform:'uppercase', letterSpacing:'0.06em',
        padding:'0 4px 8px',
      }}>{title}</div>
      <div style={{
        background:'var(--bp-surface)', borderRadius: 16,
        border:'1px solid var(--bp-line)', overflow:'hidden',
      }}>{children}</div>
    </div>
  );
}

function SettingRow({ icon, tint, label, children }) {
  return (
    <div style={{
      padding:'14px 16px',
      display:'flex', alignItems:'center', gap: 12,
      borderBottom:'1px solid var(--bp-line)',
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 9,
        background: tint + '1A', color: tint,
        display:'flex', alignItems:'center', justifyContent:'center',
        flexShrink: 0,
      }}><Icon name={icon} size={16}/></div>
      <div style={{ flex: 1, fontSize: 14, color:'var(--bp-ink)', fontWeight: 500 }}>{label}</div>
      {children}
    </div>
  );
}
// Remove bottom border on last row
function SettingButton({ icon, tint, label, detail, onClick }) {
  return (
    <button onClick={onClick} style={{
      appearance:'none', cursor:'pointer', border:0,
      background:'transparent', width:'100%',
      padding:'14px 16px', textAlign:'left',
      display:'flex', alignItems:'center', gap: 12,
      borderBottom:'1px solid var(--bp-line)',
      fontFamily:'inherit',
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 9,
        background: tint + '1A', color: tint,
        display:'flex', alignItems:'center', justifyContent:'center',
        flexShrink: 0,
      }}><Icon name={icon} size={16}/></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, color:'var(--bp-ink)', fontWeight: 500 }}>{label}</div>
        {detail && (
          <div style={{ fontSize: 11.5, color:'var(--bp-ink-3)', marginTop: 2,
            whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
          }}>{detail}</div>
        )}
      </div>
      <Icon name="chev_r" size={14} stroke="var(--bp-ink-3)"/>
    </button>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div style={{
      display:'inline-flex', background:'var(--bp-soft)',
      borderRadius: 10, padding: 3, gap: 2,
    }}>
      {options.map(([v, lab, icon]) => {
        const active = value === v;
        return (
          <button key={v} onClick={() => onChange(v)} style={{
            appearance:'none', border:0, cursor:'pointer',
            padding:'6px 12px', borderRadius: 8,
            background: active ? 'var(--bp-surface)' : 'transparent',
            color: active ? 'var(--bp-ink)' : 'var(--bp-ink-3)',
            fontFamily:'inherit', fontSize: 12, fontWeight: 600,
            display:'inline-flex', alignItems:'center', gap: 5,
            boxShadow: active ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
            transition:'background .12s ease, color .12s ease',
          }}>
            {icon && <Icon name={icon} size={12}/>}
            {lab}
          </button>
        );
      })}
    </div>
  );
}

function ChangePasswordModal({ lang, onClose }) {
  const [curr, setCurr] = useStateS('');
  const [nw, setNw] = useStateS('');
  const [nw2, setNw2] = useStateS('');
  const [done, setDone] = useStateS(false);
  const [err, setErr] = useStateS('');
  const [loading, setLoading] = useStateS(false);

  const L = lang === 'th' ? {
    title: 'เปลี่ยนรหัสผ่าน',
    current: 'รหัสผ่านปัจจุบัน',
    newPw: 'รหัสผ่านใหม่',
    confirm: 'ยืนยันรหัสผ่านใหม่',
    submit: 'บันทึก',
    cancel: 'ยกเลิก',
    success: 'เปลี่ยนรหัสผ่านเรียบร้อย',
    mismatch: 'รหัสผ่านใหม่ไม่ตรงกัน',
    wrongCurrent: 'รหัสผ่านปัจจุบันไม่ถูกต้อง',
    tooShort: 'รหัสผ่านใหม่ต้องมีอย่างน้อย 6 ตัวอักษร',
    errGeneric: 'เกิดข้อผิดพลาด กรุณาลองใหม่',
  } : {
    title: 'Change password',
    current: 'Current password',
    newPw: 'New password',
    confirm: 'Confirm new password',
    submit: 'Save',
    cancel: 'Cancel',
    success: 'Password updated',
    mismatch: 'New passwords do not match',
    wrongCurrent: 'Current password is incorrect',
    tooShort: 'New password must be at least 6 characters',
    errGeneric: 'Something went wrong, please try again',
  };

  async function submit(e) {
    e?.preventDefault?.();
    setErr('');
    if (nw !== nw2) { setErr(L.mismatch); return; }
    if (nw.length < 6) { setErr(L.tooShort); return; }
    setLoading(true);
    try {
      await sbUpdatePassword(curr, nw);
      setDone(true);
      setTimeout(onClose, 1500);
    } catch (e) {
      setErr(e.message === 'wrong_current_password' ? L.wrongCurrent : L.errGeneric);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div onClick={onClose} style={{
      position:'absolute', inset: 0,
      background:'rgba(20,14,60,0.42)',
      backdropFilter:'blur(6px)',
      display:'flex', alignItems:'center', justifyContent:'center',
      zIndex: 100, padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background:'var(--bp-surface)', borderRadius: 20, padding: 22,
        width:'100%', maxWidth: 360,
        boxShadow:'var(--bp-shadow-lg)',
        border:'1px solid var(--bp-line)',
      }}>
        {!done ? (
          <>
            <div style={{ display:'flex', alignItems:'center', gap: 10, marginBottom: 16 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background:'var(--bp-violet)1A', color:'var(--bp-violet)',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}><Icon name="cog" size={18}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 600, color:'var(--bp-ink)' }}>{L.title}</div>
              </div>
              <button onClick={onClose} style={{
                appearance:'none', border:0, background:'var(--bp-soft)', cursor:'pointer',
                width: 28, height: 28, borderRadius: 8, color:'var(--bp-ink-2)',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}><Icon name="close" size={13}/></button>
            </div>

            <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap: 12 }}>
              <PwInput label={L.current} value={curr} onChange={setCurr}/>
              <PwInput label={L.newPw} value={nw} onChange={setNw}/>
              <PwInput label={L.confirm} value={nw2} onChange={setNw2}/>

              {err && (
                <div style={{
                  fontSize: 12, color:'oklch(0.55 0.22 25)',
                  background:'oklch(0.97 0.04 25)', border:'1px solid oklch(0.88 0.08 25)',
                  borderRadius: 8, padding:'8px 12px',
                }}>{err}</div>
              )}

              <div style={{ display:'flex', gap: 8, marginTop: 6 }}>
                <button type="button" onClick={onClose} style={{
                  flex: 1, appearance:'none', border:'1px solid var(--bp-line)', cursor:'pointer',
                  background:'var(--bp-surface)', color:'var(--bp-ink-2)',
                  padding:'11px 14px', borderRadius: 11,
                  fontSize: 13, fontWeight: 500, fontFamily:'inherit',
                }}>{L.cancel}</button>
                <button type="submit" disabled={loading} style={{
                  flex: 1.4, appearance:'none', border:0, cursor: loading ? 'not-allowed' : 'pointer',
                  background:'var(--bp-grad)', color:'#fff',
                  padding:'11px 14px', borderRadius: 11,
                  fontSize: 13, fontWeight: 600, fontFamily:'inherit',
                  boxShadow:'0 6px 14px rgba(80,50,180,0.25)',
                  opacity: loading ? 0.7 : 1,
                }}>{loading ? '...' : L.submit}</button>
              </div>
            </form>
          </>
        ) : (
          <div style={{ padding:'18px 0 8px', textAlign:'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius:'50%',
              background:'oklch(0.55 0.16 155)', color:'#fff',
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              animation:'bp-pop 0.4s ease',
            }}><Icon name="check" size={28} strokeWidth={2.4}/></div>
            <div style={{ fontSize: 15, fontWeight: 600, color:'var(--bp-ink)', marginTop: 14 }}>{L.success}</div>
          </div>
        )}
      </div>
    </div>
  );
}

function PwInput({ label, value, onChange }) {
  return (
    <div>
      <div style={{ fontSize: 11.5, fontWeight: 500, color:'var(--bp-ink-2)', marginBottom: 5 }}>{label}</div>
      <input type="password" value={value} onChange={e => onChange(e.target.value)} style={{
        width:'100%', appearance:'none',
        padding:'10px 12px', borderRadius: 10,
        border:'1px solid var(--bp-line)',
        background:'var(--bp-surface)', color:'var(--bp-ink)',
        fontFamily:'inherit', fontSize: 13, outline:'none',
        boxSizing:'border-box',
      }}/>
    </div>
  );
}

function ChangeUsernameModal({ lang, onClose }) {
  const [curr, setCurr] = useStateS('');
  const [uname, setUname] = useStateS('');
  const [done, setDone] = useStateS(false);
  const [err, setErr] = useStateS('');
  const [loading, setLoading] = useStateS(false);

  const L = lang === 'th' ? {
    title: 'เปลี่ยนรหัสประจำตัว',
    current: 'รหัสผ่านปัจจุบัน',
    newU: 'รหัสประจำตัวใหม่',
    submit: 'บันทึก',
    cancel: 'ยกเลิก',
    success: 'เปลี่ยนรหัสประจำตัวเรียบร้อย',
    wrongCurrent: 'รหัสผ่านปัจจุบันไม่ถูกต้อง',
    tooShort: 'รหัสประจำตัวต้องมีอย่างน้อย 3 ตัวอักษร',
    errGeneric: 'เกิดข้อผิดพลาด รหัสประจำตัวนี้อาจถูกใช้แล้ว',
  } : {
    title: 'Change username',
    current: 'Current password',
    newU: 'New username',
    submit: 'Save',
    cancel: 'Cancel',
    success: 'Username updated',
    wrongCurrent: 'Current password is incorrect',
    tooShort: 'Username must be at least 3 characters',
    errGeneric: 'Something went wrong — username may be taken',
  };

  async function submit(e) {
    e?.preventDefault?.();
    setErr('');
    if (uname.trim().length < 3) { setErr(L.tooShort); return; }
    setLoading(true);
    try {
      await sbUpdateUsername(curr, uname.trim());
      setDone(true);
      setTimeout(onClose, 1500);
    } catch (e) {
      setErr(e.message === 'wrong_current_password' ? L.wrongCurrent : L.errGeneric);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div onClick={onClose} style={{
      position:'absolute', inset: 0,
      background:'rgba(20,14,60,0.42)',
      backdropFilter:'blur(6px)',
      display:'flex', alignItems:'center', justifyContent:'center',
      zIndex: 100, padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background:'var(--bp-surface)', borderRadius: 20, padding: 22,
        width:'100%', maxWidth: 360,
        boxShadow:'var(--bp-shadow-lg)',
        border:'1px solid var(--bp-line)',
      }}>
        {!done ? (
          <>
            <div style={{ display:'flex', alignItems:'center', gap: 10, marginBottom: 16 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10,
                background:'var(--bp-blue)1A', color:'var(--bp-blue)',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}><Icon name="user" size={18}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 600, color:'var(--bp-ink)' }}>{L.title}</div>
              </div>
              <button onClick={onClose} style={{
                appearance:'none', border:0, background:'var(--bp-soft)', cursor:'pointer',
                width: 28, height: 28, borderRadius: 8, color:'var(--bp-ink-2)',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}><Icon name="close" size={13}/></button>
            </div>

            <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap: 12 }}>
              <PwInput label={L.current} value={curr} onChange={setCurr}/>
              <div>
                <div style={{ fontSize: 11.5, fontWeight: 500, color:'var(--bp-ink-2)', marginBottom: 5 }}>{L.newU}</div>
                <input type="text" value={uname} onChange={e => setUname(e.target.value)} style={{
                  width:'100%', appearance:'none',
                  padding:'10px 12px', borderRadius: 10,
                  border:'1px solid var(--bp-line)',
                  background:'var(--bp-surface)', color:'var(--bp-ink)',
                  fontFamily:'inherit', fontSize: 13, outline:'none',
                  boxSizing:'border-box',
                }}/>
              </div>

              {err && (
                <div style={{
                  fontSize: 12, color:'oklch(0.55 0.22 25)',
                  background:'oklch(0.97 0.04 25)', border:'1px solid oklch(0.88 0.08 25)',
                  borderRadius: 8, padding:'8px 12px',
                }}>{err}</div>
              )}

              <div style={{ display:'flex', gap: 8, marginTop: 6 }}>
                <button type="button" onClick={onClose} style={{
                  flex: 1, appearance:'none', border:'1px solid var(--bp-line)', cursor:'pointer',
                  background:'var(--bp-surface)', color:'var(--bp-ink-2)',
                  padding:'11px 14px', borderRadius: 11,
                  fontSize: 13, fontWeight: 500, fontFamily:'inherit',
                }}>{L.cancel}</button>
                <button type="submit" disabled={loading} style={{
                  flex: 1.4, appearance:'none', border:0, cursor: loading ? 'not-allowed' : 'pointer',
                  background:'var(--bp-grad)', color:'#fff',
                  padding:'11px 14px', borderRadius: 11,
                  fontSize: 13, fontWeight: 600, fontFamily:'inherit',
                  boxShadow:'0 6px 14px rgba(80,50,180,0.25)',
                  opacity: loading ? 0.7 : 1,
                }}>{loading ? '...' : L.submit}</button>
              </div>
            </form>
          </>
        ) : (
          <div style={{ padding:'18px 0 8px', textAlign:'center' }}>
            <div style={{
              width: 56, height: 56, borderRadius:'50%',
              background:'oklch(0.55 0.16 155)', color:'#fff',
              display:'inline-flex', alignItems:'center', justifyContent:'center',
              animation:'bp-pop 0.4s ease',
            }}><Icon name="check" size={28} strokeWidth={2.4}/></div>
            <div style={{ fontSize: 15, fontWeight: 600, color:'var(--bp-ink)', marginTop: 14 }}>{L.success}</div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Notifications drawer (simple list) ───────────────────────
function StudentNotifications({ t, lang, goBack }) {
  const notifs = [
    { id:1, title:'ห้องน้ำชายตึก 2 แก้ไขเรียบร้อย', sub:'ครูประภาส ได้ส่งภาพหลังแก้ไขแล้ว', time: hoursAgo(3), icon:'check', tint:'oklch(0.60 0.16 155)' },
    { id:2, title:'รายงาน BP-2026-0146 กำลังดำเนินการ', sub:'ครูสมศักดิ์ รับเรื่องแล้ว', time: hoursAgo(8), icon:'clock', tint:'oklch(0.62 0.18 70)' },
    { id:3, title:'คุณได้รับคำขอบคุณ', sub:'จากครูประภาส สำหรับการแจ้งก๊อกน้ำรั่ว', time: daysAgo(1), icon:'heart', tint:'var(--bp-violet)' },
  ];
  return (
    <div style={{ padding: '52px 16px 110px' }}>
      <div style={{ display:'flex', alignItems:'center', gap: 10 }}>
        <button onClick={goBack} style={{
          appearance:'none', border:0, background:'rgba(45,30,110,0.06)',
          width: 36, height: 36, borderRadius:'50%',
          display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
        }}><Icon name="chev_l" size={18}/></button>
        <div style={{ fontSize: 22, fontWeight: 700 }}>{t.notifications}</div>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap: 8, marginTop: 18 }}>
        {notifs.map(n => (
          <div key={n.id} style={{
            background:'var(--bp-surface)', borderRadius: 14, padding: 14,
            border:'1px solid var(--bp-line)',
            display:'flex', gap: 12, alignItems:'flex-start',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 11, flexShrink: 0,
              background: n.tint + '1A', color: n.tint,
              display:'flex', alignItems:'center', justifyContent:'center',
            }}><Icon name={n.icon} size={16}/></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 500, color:'var(--bp-ink)' }}>{n.title}</div>
              <div style={{ fontSize: 12, color:'var(--bp-ink-2)', marginTop: 2 }}>{n.sub}</div>
              <div style={{ fontSize: 10.5, color:'var(--bp-ink-3)', marginTop: 4 }}>{relTime(n.time, lang)}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Student App container ─────────────────────────────────
function StudentApp({ lang, setLang, reports, setReports, theme, setTheme, initialUser }) {
  const t = T[lang];
  const [user, setUser] = useStateS(initialUser || { name: 'ณัฐภัทร', grade: 'ม.5/2', no: 12 });

  const [screen, setScreen] = useStateS('home'); // home | camera | form | success | list | detail | profile | notifications
  const [tab, setTab] = useStateS('home');
  const [draftPhoto, setDraftPhoto] = useStateS(null);
  const [activeReport, setActiveReport] = useStateS(null);
  const [lastReport, setLastReport] = useStateS(null);

  function goTo(s, payload) {
    if (s === 'detail') {
      const r = reports.find(x => x.id === payload);
      setActiveReport(r);
      setScreen('detail');
    } else {
      setScreen(s);
      if (['home', 'list', 'profile'].includes(s)) setTab(s);
    }
  }

  function setTabAndScreen(newTab) {
    setTab(newTab);
    setScreen(newTab);
  }

  function startReport() {
    setScreen('camera');
  }

  function handleCapture(photo) {
    setDraftPhoto(photo);
    setScreen('form');
  }

  async function handleSubmit(data) {
    const reportId = `BP-2026-${String(149 + reports.length).padStart(4,'0')}`;
    // Build initial photo metadata - use data URL for preview, will be replaced with public URL after upload
    const photoForState = draftPhoto
      ? { label: draftPhoto.label || 'PHOTO', url: draftPhoto.dataUrl || null, hue: 270 }
      : { hue: 270, label: 'NEW REPORT' };

    const newReport = {
      id: reportId,
      category: data.category,
      title: data.desc.slice(0, 60),
      titleEn: data.desc.slice(0, 60),
      desc: data.desc, descEn: data.desc,
      location: data.location, locationEn: data.location,
      reporter: user.name, grade: user.grade,
      reporter_id: user.userId || null,
      submittedAt: new Date().toISOString(),
      urgency: 'normal', status: 'pending',
      before: photoForState,
      after: null,
      timeline: [['submitted', new Date().toISOString(), user.name]],
      mine: true,
    };
    setReports(prev => [newReport, ...prev]); // optimistic
    setLastReport(newReport);
    setScreen('success');

    // Upload photo to Supabase Storage, then insert report with public URL
    (async () => {
      try {
        let publicUrl = null;
        if (draftPhoto?.file) {
          publicUrl = await sbUploadImage(draftPhoto.file, reportId, 'before');
        }
        const finalReport = {
          ...newReport,
          before: { ...photoForState, url: publicUrl || photoForState.url },
        };
        await sbInsertReport(finalReport);
        // Update local state with the public URL
        if (publicUrl) {
          setReports(prev => prev.map(r => r.id === reportId ? finalReport : r));
          setLastReport(finalReport);
        }
      } catch (e) {
        setReports(prev => prev.filter(r => r.id !== reportId));
      }
    })();
  }

  // Decide if we need the bottom nav
  const showTabBar = ['home', 'list', 'profile'].includes(screen);

  return (
    <div style={{ position:'relative', width:'100%', height:'100%', background:'var(--bp-canvas)', overflow:'hidden' }}>
      <div className="bp-mobile-scroll">
        {screen === 'home' && (
          <StudentHome t={t} lang={lang} reports={reports} user={user} goTo={goTo} startReport={startReport}/>
        )}
        {screen === 'list' && (
          <StudentList t={t} lang={lang} reports={reports} user={user} goTo={goTo}/>
        )}
        {screen === 'profile' && (
          <StudentProfile t={t} lang={lang} setLang={setLang} user={user} setUser={setUser} theme={theme} setTheme={setTheme}/>
        )}
        {screen === 'camera' && (
          <StudentCamera t={t} goBack={() => setScreen('home')} onCapture={handleCapture}/>
        )}
        {screen === 'form' && (
          <StudentForm t={t} lang={lang} photo={draftPhoto} goBack={() => setScreen('camera')} onSubmit={handleSubmit}/>
        )}
        {screen === 'success' && lastReport && (
          <StudentSuccess t={t} lang={lang} report={lastReport}
            goHome={() => setScreen('home')}
            goList={() => { setTab('list'); setScreen('list'); }}/>
        )}
        {screen === 'detail' && activeReport && (
          <StudentDetail t={t} lang={lang} report={activeReport} goBack={() => setScreen(tab)}/>
        )}
        {screen === 'notifications' && (
          <StudentNotifications t={t} lang={lang} goBack={() => setScreen('home')}/>
        )}
      </div>

      {showTabBar && <StudentTabBar tab={tab} setTab={setTabAndScreen} t={t}/>}
    </div>
  );
}

Object.assign(window, {
  StudentApp, ReportRow, Timeline, ChangePasswordModal, ChangeUsernameModal,
});
