/* ============ JE BAR — จัดหมวดรูปเค้กแบบเร็ว ============
 *
 * 🔴 10/09/2026 เจ้าของร้าน: "เลิกสนใจชื่อไปเลย ใช้หมวดแทน · เอาตามแผน"
 *
 * ของจริงที่ตรวจเจอ: รูปเค้ก 484 ใบถูกอัปโหลดไว้ครบแล้ว แต่ **466 ใบยังไม่มีหมวด**
 * และ 480 ใบยังชื่อ "เค้กใหม่" ⇒ งานที่เหลือไม่ใช่ "ตั้งชื่อ 480 ครั้ง"
 * แต่คือ "จัดหมวด 466 ใบ" ซึ่งถ้าทำทีละใบก็ยังเป็นงาน 466 รอบอยู่ดี
 *
 * ⭐ หน้านี้จึงออกแบบให้ทำเป็นชุด: กดเลือกรูปหลาย ๆ ใบ → กดหมวดเดียว → จบ
 * ไม่มีช่องให้พิมพ์อะไรเลยสักช่อง เพราะการพิมพ์คือสิ่งที่ทำให้งานนี้ไม่มีวันเสร็จ
 *
 * ⚠️ ขึ้นรูปที่ "ยังไม่จัดหมวด" ก่อนเสมอ — งานที่เหลือต้องมองเห็นได้ในหน้าจอเดียว
 * ไม่ใช่ให้เจ้าของร้านไล่หาเองว่าอันไหนยังไม่ได้ทำ
 *
 * 🤖 26/10/2026 เจ้าของเลือก "ให้ AI แนะนำหมวด" — AI แค่ "จัดกอง" ให้ คนเป็นคนกดบันทึก
 * กดแนะนำ → รูปที่ยังไม่จัดถูกแยกเป็นกองตามหมวดที่ AI เดา (กองละแท็บ สีม่วง)
 * เปิดกอง = รูปทั้งกองถูกเลือกไว้แล้ว · แตะรูปที่ผิดเอาออก · กด "บันทึกเข้าหมวด …"
 * รูปที่แตะออก / AI ไม่แน่ใจ (มั่นใจต่ำกว่าครึ่ง) ไปกอง "AI ไม่แน่ใจ" ให้จัดเองด้วยปุ่มหมวดข้างล่าง
 * ผลแนะนำเก็บในเครื่องนี้ (โหลดหน้าใหม่ไม่ต้องเสียค่า AI ซ้ำ)
 */
const AI_SUGGEST_KEY = 'jebar_cake_ai_suggest_v1';
const AI_BATCH = 12;
const AI_MIN_CONF = 0.5;
function loadAiSuggest() {
  try { return JSON.parse(localStorage.getItem(AI_SUGGEST_KEY) || '{}') || {}; } catch (e) { return {}; }
}
function saveAiSuggest(map) {
  try { localStorage.setItem(AI_SUGGEST_KEY, JSON.stringify(map)); } catch (e) { /* เครื่องเก็บไม่ได้ ไม่เป็นไร */ }
}
function AdminSort() {
  const [cakes, setCakes] = React.useState([]);
  const [cats, setCats] = React.useState([]);
  const [sel, setSel] = React.useState(() => new Set());
  const [filter, setFilter] = React.useState('todo');  // todo | all | <cat id>
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState('');
  const [err, setErr] = React.useState('');
  // ผล AI: { [cakeId]: catId | '' }  ('' = AI ไม่แน่ใจ)
  const [ai, setAi] = React.useState(loadAiSuggest);
  const [aiRun, setAiRun] = React.useState(null); // { done, total } ระหว่างรัน
  const aiStop = React.useRef(false);
  React.useEffect(() => { saveAiSuggest(ai); }, [ai]);

  const load = React.useCallback(() => {
    window.JEAPI.listCatalog()
      .then(({ cakes, categories }) => { setCakes(cakes); setCats(categories); setErr(''); })
      .catch(e => setErr('โหลดแคตตาล็อกไม่สำเร็จ: ' + e.message));
  }, []);
  React.useEffect(load, [load]);

  const todo = cakes.filter(c => !c.cat);
  // กองที่ AI แนะนำ — เฉพาะรูปที่ยังไม่จัดหมวด (จัดแล้ว = หลุดจากกองเอง)
  const aiPile = key => todo.filter(c => (c.id in ai) && ai[c.id] === key);
  const aiNotRun = todo.filter(c => !(c.id in ai));
  const isAiFilter = String(filter).startsWith('ai:');
  const aiKey = isAiFilter ? String(filter).slice(3) : null;
  const shown = filter === 'todo' ? todo : filter === 'all' ? cakes : isAiFilter ? aiPile(aiKey) : cakes.filter(c => c.cat === filter);
  const catName = id => (cats.find(c => c.id === id) || {}).name || '';

  /** เปิดกองของ AI = เลือกรูปทั้งกองไว้ให้เลย เจ้าของแค่แตะตัวที่ผิดออก */
  function openAiPile(key) {
    setFilter('ai:' + key);
    setSel(new Set(aiPile(key).map(c => c.id)));
    setMsg(''); setErr('');
  }

  async function runAi() {
    if (aiRun || !aiNotRun.length) return;
    aiStop.current = false;
    const ids = aiNotRun.map(c => c.id);
    let done = 0, failed = 0;
    setAiRun({ done: 0, total: ids.length }); setErr(''); setMsg('');
    for (let i = 0; i < ids.length; i += AI_BATCH) {
      if (aiStop.current) break;
      const chunk = ids.slice(i, i + AI_BATCH);
      try {
        const rows = await window.JEAPI.suggestCategories(chunk);
        setAi(prev => {
          const n = { ...prev };
          for (const r of rows) n[r.id] = r.category_id && r.confidence >= AI_MIN_CONF ? r.category_id : '';
          return n;
        });
      } catch (e) {
        failed += chunk.length;
        setErr('บางชุด AI แนะนำไม่สำเร็จ (' + failed + ' รูป) — กดแนะนำอีกครั้งเพื่อทำเฉพาะที่เหลือ · ' + e.message);
      }
      done += chunk.length;
      setAiRun({ done, total: ids.length });
    }
    setAiRun(null);
    setMsg('AI จัดกองเสร็จแล้ว — เปิดกองสีม่วงทีละกอง ตรวจแล้วกดบันทึก');
  }

  function toggle(id) {
    setSel(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  }
  function selectAllShown() { setSel(new Set(shown.map(c => c.id))); }
  function clearSel() { setSel(new Set()); }

  /** ย้ายรูปที่เลือกไปหมวดเดียว — catId เป็น null คือ "เอาออกจากหมวด" */
  async function assign(catId) {
    if (!sel.size || busy) return;
    setBusy(true); setMsg(''); setErr('');
    const ids = [...sel];
    // อยู่ในกองของ AI: รูปที่แตะออกถือว่า AI เดาผิด → ย้ายไปกอง "ไม่แน่ใจ" ให้จัดเอง
    const rejected = isAiFilter ? shown.filter(c => !sel.has(c.id)).map(c => c.id) : [];
    try {
      await window.JEAPI.saveCatalogUpdates(ids.map(id => ({ id, category_id: catId })));
      if (rejected.length) setAi(prev => { const n = { ...prev }; rejected.forEach(id => { n[id] = ''; }); return n; });
      // อัปเดตในจอทันที ไม่ต้องรอโหลดใหม่ — 484 ใบโหลดใหม่ทุกครั้งคือการรอที่ไม่จำเป็น
      setCakes(prev => prev.map(c => (sel.has(c.id) ? { ...c, cat: catId || '' } : c)));
      clearSel();
      setMsg('ย้าย ' + ids.length + ' ใบไปหมวด "' + (catId ? catName(catId) : 'ยังไม่จัดหมวด') + '" แล้ว');
    } catch (e) {
      setErr('บันทึกไม่สำเร็จ: ' + e.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="card" style={{ padding: 16 }}>
      <h2 style={{ margin: '0 0 4px' }}>จัดหมวดรูปเค้ก</h2>
      <p style={{ margin: '0 0 12px', color: 'var(--muted)', fontSize: 13.5 }}>
        แตะรูปเพื่อเลือก (เลือกได้หลายใบ) แล้วกดหมวดด้านล่าง · ไม่ต้องพิมพ์ชื่อ
      </p>

      <div style={{ border: '1px solid #C9B6E4', background: '#F7F2FC', borderRadius: 12, padding: 12, marginBottom: 12 }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <strong style={{ color: '#5B3A8C' }}>ให้ AI ช่วยจัดกอง</strong>
          {aiRun ? (
            <>
              <span>กำลังดูรูป {aiRun.done}/{aiRun.total}</span>
              <button className="btn btn--ghost" onClick={() => { aiStop.current = true; }}>หยุด</button>
            </>
          ) : (
            <button className="btn" disabled={!aiNotRun.length || busy} onClick={runAi}>
              {aiNotRun.length ? 'ให้ AI แนะนำหมวด (' + aiNotRun.length + ' รูปที่ยังไม่จัด)' : 'AI ดูครบทุกรูปที่ยังไม่จัดแล้ว'}
            </button>
          )}
        </div>
        {aiRun ? (
          <div style={{ height: 6, background: '#E4D8F2', borderRadius: 99, marginTop: 8, overflow: 'hidden' }}>
            <div style={{ width: Math.round(aiRun.done / Math.max(1, aiRun.total) * 100) + '%', height: '100%', background: '#7A52B3' }} />
          </div>
        ) : null}
        {Object.keys(ai).length ? (
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
            {cats.map(c => {
              const n = aiPile(c.id).length;
              return n ? (
                <button key={c.id} className={'tab' + (filter === 'ai:' + c.id ? ' on' : '')} style={{ borderColor: '#7A52B3' }} onClick={() => openAiPile(c.id)}>
                  AI ว่า {c.name} ({n})
                </button>
              ) : null;
            })}
            {aiPile('').length ? (
              <button className={'tab' + (filter === 'ai:' ? ' on' : '')} onClick={() => openAiPile('')}>
                AI ไม่แน่ใจ ({aiPile('').length})
              </button>
            ) : null}
          </div>
        ) : null}
        <p style={{ margin: '8px 0 0', color: 'var(--muted)', fontSize: 12.5 }}>
          AI ไม่บันทึกเอง — เปิดกองแล้วรูปทั้งกองจะถูกเลือกไว้ แตะรูปที่ผิดเอาออก แล้วกดบันทึก
        </p>
      </div>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 12 }}>
        <button className={'tab' + (filter === 'todo' ? ' on' : '')} onClick={() => { setFilter('todo'); clearSel(); }}>
          ยังไม่จัดหมวด ({todo.length})
        </button>
        <button className={'tab' + (filter === 'all' ? ' on' : '')} onClick={() => { setFilter('all'); clearSel(); }}>
          ทั้งหมด ({cakes.length})
        </button>
        {cats.map(c => (
          <button key={c.id} className={'tab' + (filter === c.id ? ' on' : '')} onClick={() => { setFilter(c.id); clearSel(); }}>
            {c.name} ({cakes.filter(x => x.cat === c.id).length})
          </button>
        ))}
      </div>

      {err ? <p style={{ color: '#B25543', fontWeight: 600 }}>{err}</p> : null}
      {msg ? <p style={{ color: '#2E7D5B', fontWeight: 600 }}>{msg}</p> : null}

      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 10, flexWrap: 'wrap' }}>
        <button className="btn btn--ghost" onClick={selectAllShown} disabled={!shown.length}>เลือกทั้งหน้า ({shown.length})</button>
        <button className="btn btn--ghost" onClick={clearSel} disabled={!sel.size}>ล้างที่เลือก</button>
        <strong style={{ marginLeft: 'auto' }}>{sel.size ? 'เลือกไว้ ' + sel.size + ' ใบ' : 'ยังไม่ได้เลือกรูป'}</strong>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(120px,1fr))', gap: 8, maxHeight: '52vh', overflowY: 'auto', padding: 2 }}>
        {shown.map(c => {
          const on = sel.has(c.id);
          return (
            <button key={c.id} onClick={() => toggle(c.id)} title={c.cat ? catName(c.cat) : 'ยังไม่จัดหมวด'}
              style={{
                position: 'relative', padding: 0, border: on ? '3px solid var(--primary)' : '1px solid var(--line)',
                borderRadius: 10, overflow: 'hidden', background: '#fff', cursor: 'pointer', aspectRatio: '1/1',
              }}>
              {c.image_url
                ? <img src={c.image_url} alt="" loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', opacity: on ? .75 : 1 }} />
                : <span style={{ fontSize: 11, color: 'var(--muted)' }}>ไม่มีรูป</span>}
              {on ? <span style={{ position: 'absolute', top: 4, right: 4, background: 'var(--primary)', color: '#fff', borderRadius: 999, width: 22, height: 22, display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 13 }}>✓</span> : null}
              {c.cat ? <span style={{ position: 'absolute', left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,.55)', color: '#fff', fontSize: 10, padding: '2px 4px' }}>{catName(c.cat)}</span> : null}
            </button>
          );
        })}
        {!shown.length ? <p style={{ color: 'var(--muted)' }}>ไม่มีรูปในกลุ่มนี้</p> : null}
      </div>

      <div style={{ marginTop: 14, borderTop: '1px solid var(--line)', paddingTop: 12 }}>
        {isAiFilter && aiKey ? (
          <button className="btn" style={{ width: '100%', marginBottom: 10, background: '#7A52B3', borderColor: '#7A52B3' }}
            disabled={!sel.size || busy} onClick={() => assign(aiKey)}>
            บันทึก {sel.size} รูปเข้าหมวด "{catName(aiKey)}"
          </button>
        ) : null}
        <p style={{ margin: '0 0 8px', fontWeight: 700 }}>ย้ายรูปที่เลือกไปหมวด</p>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {cats.map(c => (
            <button key={c.id} className="btn" disabled={!sel.size || busy} onClick={() => assign(c.id)}>{c.name}</button>
          ))}
          <button className="btn btn--ghost" disabled={!sel.size || busy} onClick={() => assign(null)}>เอาออกจากหมวด</button>
        </div>
        {busy ? <p style={{ color: 'var(--muted)', marginTop: 8 }}>กำลังบันทึก…</p> : null}
      </div>
    </div>
  );
}

Object.assign(window, { AdminSort });
