// News / announcements
function NewsPage({ go, params }) {
  const article = params.id ? NEWS.find(n => n.id === params.id) : null;
  const [cat, setCat] = React.useState('all');
  const CATS = ['all','การลงทะเบียน','ทุนการศึกษา','กิจกรรม','ระบบ','รางวัล'];

  const [comments, setComments] = React.useState([]);
  const [cName, setCName] = React.useState('');
  const [cBody, setCBody] = React.useState('');
  const [cBusy, setCBusy] = React.useState(false);
  const [cErr, setCErr] = React.useState('');

  React.useEffect(() => {
    if (!article) { setComments([]); return; }
    let cancelled = false;
    window.api.comments(article.id).then(rows => {
      if (!cancelled) setComments(rows);
    }).catch(() => setComments([]));
    return () => { cancelled = true; };
  }, [article ? article.id : null]);

  async function submitComment(e){
    e.preventDefault();
    setCErr('');
    if (!cName.trim() || !cBody.trim()) { setCErr('กรุณากรอกชื่อและความคิดเห็น'); return; }
    setCBusy(true);
    try {
      const cm = await window.api.addComment(article.id, cName.trim(), cBody.trim());
      setComments(cs => [...cs, cm]);
      setCName(''); setCBody('');
    } catch {
      setCErr('ส่งความคิดเห็นไม่สำเร็จ กรุณาลองใหม่');
    } finally {
      setCBusy(false);
    }
  }

  if (article) {
    return (
      <div>
        <div className="wrap">
          <div className="crumbs">
            <a onClick={()=>go('home')}>หน้าแรก</a><span className="sep">/</span>
            <a onClick={()=>go('news')}>ประกาศ</a><span className="sep">/</span>
            <span className="here">{article.title}</span>
          </div>
        </div>

      <article style={{maxWidth:760, margin:'0 auto', padding:'24px 32px 56px'}}>
          <div className="row" style={{gap:12, marginBottom:18, fontSize:12.5, color:'var(--ink-3)'}}>
            <span className="tag acc">{article.cat}</span>
            <span>{article.date} {article.month} 2569</span>
            <span style={{color:'var(--ink-4)'}}>·</span>
            <span>แผนกประชาสัมพันธ์</span>
          </div>
          <h1 className="serif" style={{fontSize:'clamp(32px, 5vw, 52px)', margin:'0 0 20px', fontWeight:600, lineHeight:1.15, letterSpacing:'-.005em'}}>
            {article.title}
          </h1>
          <p style={{fontSize:18, color:'var(--ink-2)', margin:'0 0 32px', lineHeight:1.65, fontWeight:400}}>{article.dek}</p>
        </article>

        <div style={{maxWidth:1080, margin:'0 auto', padding:'0 32px'}}>
          <Placeholder seed={`news-${article.id}`} label="ภาพประกอบ · งานเสวนาเดือนพฤษภาคม" num="N1" variant="wide"/>
        </div>

        <article style={{maxWidth:720, margin:'0 auto', padding:'40px 32px 56px', fontSize:16.5, lineHeight:1.85, color:'var(--ink-2)'}}>
          <p style={{margin:0}}>มหาวิทยาลัยทดสอบ ขอแจ้งกำหนดการที่เกี่ยวข้องกับนักศึกษาทุกท่าน เพื่อเตรียมความพร้อมในการเข้าศึกษาในภาคต้น ปีการศึกษา 2569 ดังต่อไปนี้.</p>
          <h2 className="serif" style={{fontSize:28, margin:'36px 0 14px', color:'var(--ink)', fontWeight:600}}>กำหนดการสำคัญ</h2>
          <ul style={{paddingLeft:20, margin:0}}>
            <li style={{padding:'6px 0'}}><b>20 พ.ค. - 5 มิ.ย.</b> · เปิดระบบลงทะเบียนเรียน ผ่านเว็บไซต์ของสำนักทะเบียน</li>
            <li style={{padding:'6px 0'}}><b>6 - 12 มิ.ย.</b> · ช่วงปรับแก้รายวิชา (เพิ่ม-ถอน-เปลี่ยนตอน)</li>
            <li style={{padding:'6px 0'}}><b>13 มิ.ย.</b> · วันเปิดภาคเรียน</li>
            <li style={{padding:'6px 0'}}><b>15 มิ.ย.</b> · ชำระค่าธรรมเนียมการศึกษางวดแรก</li>
            <li style={{padding:'6px 0'}}><b>1 ก.ค.</b> · กำหนดส่งคำขอผ่อนชำระ</li>
          </ul>
          <h2 className="serif" style={{fontSize:28, margin:'36px 0 14px', color:'var(--ink)', fontWeight:600}}>คำแนะนำเพิ่มเติม</h2>
          <p>ขอให้นักศึกษาตรวจสอบรายวิชาที่ต้องลงทะเบียนตามแผนการเรียนของหลักสูตร และปรึกษาอาจารย์ที่ปรึกษาทางวิชาการก่อนทำการลงทะเบียน. หากพบปัญหาในการเข้าใช้ระบบ สามารถติดต่อสำนักทะเบียนได้ในวันและเวลาราชการ.</p>
          <blockquote style={{borderLeft:'3px solid var(--accent)', padding:'4px 0 4px 22px', margin:'24px 0', fontFamily:'Noto Serif Thai, serif', fontSize:20, color:'var(--ink)', fontWeight:500}}>
            "นักศึกษาที่ลงทะเบียนไม่ครบตามแผน อาจต้องขยายเวลาเรียน ขอให้วางแผนรายวิชาอย่างรอบคอบ."
          </blockquote>

          {/* Embedded explainer video */}
          <div style={{position:'relative', borderRadius:'var(--r-lg)', overflow:'hidden', background:'#000', aspectRatio:'16/9', margin:'32px 0'}}>
            <video
              src="/assets/video/bbb-360-10s.mp4"
              poster={`/assets/img/picsum/news-explainer-${article.id}_960x540.jpg`}
              controls playsInline preload="metadata"
              style={{width:'100%', height:'100%', objectFit:'cover'}}/>
            <span className="tag" style={{position:'absolute', top:12, left:12, background:'var(--accent)', color:'var(--ink)', borderColor:'transparent'}}>วิดีโออธิบายขั้นตอน · 2:42</span>
          </div>
          <p style={{fontSize:12.5, color:'var(--ink-3)', fontStyle:'italic', margin:'-16px 0 16px'}}>
            สาธิตขั้นตอนการลงทะเบียนตั้งแต่เริ่มต้นจนยืนยันรายวิชา · จัดทำโดยสำนักทะเบียน
          </p>

          {/* Photo gallery */}
          <div className="grid g3" style={{gap:8, margin:'32px 0'}}>
            {['gallery-1','gallery-2','gallery-3'].map(seed => (
              <div key={seed} style={{aspectRatio:'4/3', borderRadius:'var(--r)', overflow:'hidden', background:'var(--bg-2)'}}>
                <img src={`/assets/img/picsum/${article.id}-${seed}_400x300.jpg`} alt="" loading="lazy"
                  style={{width:'100%', height:'100%', objectFit:'cover'}}/>
              </div>
            ))}
          </div>

          <p>กรณีมีข้อสงสัย ติดต่อ <a style={{color:'var(--accent-2)', borderBottom:'1px solid var(--accent-2)'}}>registrar@aksaraphat.example.ac.th</a> หรือโทร <span className="mono">02-555-0144</span> ในวันจันทร์-ศุกร์ เวลา 08:30-16:30 น.</p>
        </article>

        {/* Comments */}
        <div style={{maxWidth:720, margin:'0 auto', padding:'0 32px 56px'}}>
          <h3 className="serif" style={{fontSize:22, margin:'24px 0 14px', fontWeight:600}}>ความคิดเห็นจากนักศึกษา ({comments.length})</h3>
          <form className="panel" style={{padding:18, marginBottom:20}} onSubmit={submitComment}>
            <div className="field"><label>ชื่อ</label>
              <input value={cName} onChange={e=>setCName(e.target.value)} placeholder="ชื่อของท่าน"/></div>
            <div className="field"><label>ความคิดเห็น</label>
              <textarea value={cBody} onChange={e=>setCBody(e.target.value)} rows="3" placeholder="แสดงความคิดเห็นของท่าน…"/></div>
            {cErr && <div className="notice" style={{borderLeftColor:'var(--bad)', marginBottom:12, fontSize:13}}>{cErr}</div>}
            <button className="btn sm" type="submit" disabled={cBusy}>{cBusy ? 'กำลังส่ง…' : 'ส่งความคิดเห็น'}</button>
          </form>
          {comments.length === 0 && (
            <p style={{color:'var(--ink-3)', fontSize:14, padding:'4px 0'}}>ยังไม่มีความคิดเห็น · เป็นคนแรกที่แสดงความคิดเห็น</p>
          )}
          {comments.map(c => (
            <div key={c._id} style={{padding:'14px 0', borderBottom:'1px solid var(--line)'}}>
              <div className="between" style={{marginBottom:6}}>
                <b style={{fontSize:13}}>{c.author}</b>
                <span style={{fontSize:11.5, color:'var(--ink-3)'}}>{timeAgo(c.createdAt)}</span>
              </div>
              <p style={{margin:0, fontSize:14, color:'var(--ink-2)', whiteSpace:'pre-wrap'}}>{c.body}</p>
            </div>
          ))}
        </div>
      </div>
    );
  }

  const list = cat === 'all' ? NEWS : NEWS.filter(n => n.cat === cat);

  return (
    <div className="wrap">
      <div className="crumbs">
        <a onClick={()=>go('home')}>หน้าแรก</a><span className="sep">/</span>
        <span className="here">ประกาศและกิจกรรม</span>
      </div>

      <div style={{padding:'16px 0 40px', borderBottom:'1px solid var(--line)', marginBottom:40}}>
        <div className="label" style={{fontSize:11.5, letterSpacing:'.2em', textTransform:'uppercase', color:'var(--accent-2)', fontWeight:600, marginBottom:10}}>
          ศูนย์ข่าวสารและประชาสัมพันธ์
        </div>
        <h1 className="serif" style={{fontSize:'clamp(40px, 5.6vw, 64px)', margin:0, fontWeight:600, lineHeight:1.05, letterSpacing:'-.005em'}}>
          ประกาศและกิจกรรม
        </h1>
      </div>

      {/* Filter */}
      <div className="row" style={{gap:8, flexWrap:'wrap', marginBottom:32}}>
        {CATS.map(c => (
          <button key={c} onClick={()=>setCat(c)} className={`tag ${cat===c?'acc':''}`}
            style={{padding:'8px 16px', fontSize:13.5, cursor:'default'}}>
            {c === 'all' ? 'ทั้งหมด' : c}
          </button>
        ))}
      </div>

      {/* Featured */}
      <div style={{display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:48, marginBottom:48, cursor:'default'}} onClick={()=>go('news',{id:list[0].id})}>
        <Placeholder seed={`news-${list[0].id}-hero`} label="ภาพประกอบหลัก" num="A" variant="wide"/>
        <div>
          <div className="row" style={{gap:10, marginBottom:14}}>
            <span className="tag acc">{list[0].cat}</span>
            <span style={{fontSize:13, color:'var(--ink-3)'}}>{list[0].date} {list[0].month} 2569</span>
          </div>
          <h2 className="serif" style={{fontSize:'clamp(28px, 3.6vw, 40px)', margin:'0 0 18px', fontWeight:600, lineHeight:1.2}}>{list[0].title}</h2>
          <p style={{margin:'0 0 22px', color:'var(--ink-2)', fontSize:15.5}}>{list[0].dek}</p>
          <button className="btn link">อ่านต่อ →</button>
        </div>
      </div>

      <div className="grid g3">
        {list.slice(1).map(n => (
          <article key={n.id} onClick={()=>go('news',{id:n.id})} style={{cursor:'default'}}>
            <Placeholder seed={`news-${n.id}`} label={n.cat} num="" variant="wide"/>
            <div className="row" style={{gap:10, margin:'14px 0 8px'}}>
              <span className="tag">{n.cat}</span>
              <span style={{fontSize:12, color:'var(--ink-3)'}}>{n.date} {n.month}</span>
            </div>
            <h3 className="serif" style={{fontSize:20, margin:'0 0 8px', fontWeight:600, lineHeight:1.3}}>{n.title}</h3>
            <p style={{margin:0, color:'var(--ink-2)', fontSize:13.5}}>{n.dek}</p>
          </article>
        ))}
      </div>
    </div>
  );
}
window.NewsPage = NewsPage;
