// AdminScreens.jsx — 登入、帳號管理、歷史紀錄
const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA } = React;

// ────────── 登入畫面 ──────────
function LoginScreen({ theme, onLoggedIn }) {
  const [u, setU] = useStateA('');
  const [p, setP] = useStateA('');
  const [err, setErr] = useStateA('');
  const [busy, setBusy] = useStateA(false);

  const submit = async () => {
    if (!u || !p) { setErr('請輸入帳號與密碼'); return; }
    setBusy(true); setErr('');
    try {
      const session = await api.login(u.trim(), p);
      onLoggedIn(session);
    } catch (e) {
      setErr(e.message || '登入失敗');
    } finally { setBusy(false); }
  };

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      justifyContent: 'center', padding: '40px 28px',
    }}>
      <div style={{
        fontSize: 12 * theme.scale, letterSpacing: 3, color: theme.inkMute,
        fontWeight: 700, marginBottom: 8,
      }}>CELEBREAD · 2026</div>
      <h1 style={{
        margin: 0, marginBottom: 32,
        fontSize: 38 * theme.scale, color: theme.ink,
        fontWeight: theme.titleWeight, letterSpacing: -0.5,
      }}>登入</h1>

      <div style={{ marginBottom: 16 }}>
        <div style={{ fontSize: 12 * theme.scale, color: theme.inkMute, letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 8 }}>帳號</div>
        <input value={u} onChange={e => setU(e.target.value)} autoCapitalize="none" autoCorrect="off"
          style={{
            width: '100%', padding: '16px 18px', fontSize: 20 * theme.scale,
            background: theme.surface, color: theme.ink, border: 'none',
            borderRadius: theme.cardRadius, fontFamily: 'inherit',
            outline: `2px solid transparent`, transition: 'outline .15s',
          }}
          onFocus={e => e.target.style.outline = `2px solid ${theme.accent}`}
          onBlur={e => e.target.style.outline = `2px solid transparent`}
        />
      </div>
      <div style={{ marginBottom: 24 }}>
        <div style={{ fontSize: 12 * theme.scale, color: theme.inkMute, letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 8 }}>密碼</div>
        <input value={p} onChange={e => setP(e.target.value)} type="password"
          onKeyDown={e => e.key === 'Enter' && submit()}
          style={{
            width: '100%', padding: '16px 18px', fontSize: 20 * theme.scale,
            background: theme.surface, color: theme.ink, border: 'none',
            borderRadius: theme.cardRadius, fontFamily: 'inherit',
            outline: `2px solid transparent`,
          }}
          onFocus={e => e.target.style.outline = `2px solid ${theme.accent}`}
          onBlur={e => e.target.style.outline = `2px solid transparent`}
        />
      </div>

      {err && <div style={{
        padding: '10px 14px', marginBottom: 16, borderRadius: 8,
        background: '#5a1a1a', color: '#ffb3b3', fontSize: 14 * theme.scale,
      }}>{err}</div>}

      <PillButton theme={theme} onClick={submit} disabled={busy}>
        {busy ? '登入中…' : '登入'}
      </PillButton>

    </div>
  );
}

// ────────── 帳號管理 ──────────
function UsersScreen({ theme, session, onBack }) {
  const [users, setUsers] = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [showAdd, setShowAdd] = useStateA(false);
  const [changePwUser, setChangePwUser] = useStateA(null);
  const [err, setErr] = useStateA('');

  const refresh = async () => {
    try {
      const list = await api.listUsers();
      setUsers(list);
    } catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  };
  useEffectA(() => { refresh(); }, []);

  const remove = async (u) => {
    if (u.username === session.username) { alert('不能刪除自己'); return; }
    if (!confirm(`確定刪除「${u.display_name}」(${u.username})？`)) return;
    try { await api.deleteUser(u.id); refresh(); } catch (e) { alert(e.message); }
  };

  return (
    <>
      <TopBar
        theme={theme} title="帳號管理"
        leading={<IconBtn theme={theme} onClick={onBack}><IconBack color={theme.ink}/></IconBtn>}
        trailing={<IconBtn theme={theme} onClick={() => setShowAdd(true)}><IconPlus color={theme.ink}/></IconBtn>}
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px 20px' }}>
        {loading && <div style={{ padding: 30, textAlign: 'center', color: theme.inkMute }}>讀取中…</div>}
        {err && <div style={{ padding: 16, color: '#ffb3b3', background: '#5a1a1a', borderRadius: 8, margin: 16 }}>{err}</div>}

        <div style={{
          background: theme.surface, borderRadius: theme.cardRadius, overflow: 'hidden',
        }}>
          {users.map((u, idx) => (
            <div key={u.id} style={{
              padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12,
              borderBottom: idx < users.length - 1 ? `1px solid ${theme.divider}` : 'none',
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 20,
                background: u.role === 'admin' ? theme.accent : theme.surfaceAlt,
                color: u.role === 'admin' ? '#1A1A1A' : theme.ink,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontWeight: 800, fontSize: 16 * theme.scale,
              }}>{(u.display_name || u.username)[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontSize: 17 * theme.scale, fontWeight: 700, color: theme.ink,
                }}>{u.display_name}
                  {u.role === 'admin' && <span style={{
                    marginLeft: 8, fontSize: 11 * theme.scale, padding: '2px 8px',
                    background: theme.accent, color: '#1A1A1A', borderRadius: 999, fontWeight: 800,
                  }}>ADMIN</span>}
                </div>
                <div style={{ fontSize: 13 * theme.scale, color: theme.inkMute }}>@{u.username}</div>
              </div>
              <div style={{ display: 'flex', gap: 4 }}>
                <button onClick={() => setChangePwUser(u)} style={{
                  border: 'none', background: 'none', color: theme.accent,
                  fontSize: 14 * theme.scale, cursor: 'pointer', padding: 8, fontWeight: 700,
                }}>改密碼</button>
                {u.username !== session.username && (
                  <button onClick={() => remove(u)} style={{
                    border: 'none', background: 'none', color: '#ff6b6b',
                    fontSize: 14 * theme.scale, cursor: 'pointer', padding: 8,
                  }}>刪除</button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      {showAdd && <AddUserModal theme={theme} onClose={() => setShowAdd(false)} onAdded={() => { setShowAdd(false); refresh(); }}/>}
      {changePwUser && <ChangePasswordModal theme={theme} user={changePwUser} onClose={() => setChangePwUser(null)} onDone={() => { setChangePwUser(null); }}/>}
    </>
  );
}

function AddUserModal({ theme, onClose, onAdded }) {
  const [username, setUsername] = useStateA('');
  const [displayName, setDisplayName] = useStateA('');
  const [password, setPassword] = useStateA('');
  const [role, setRole] = useStateA('baker');
  const [busy, setBusy] = useStateA(false);
  const [err, setErr] = useStateA('');

  const submit = async () => {
    if (!username || !displayName || !password) { setErr('請填完所有欄位'); return; }
    setBusy(true); setErr('');
    try {
      await api.createUser({ username: username.trim(), password, display_name: displayName.trim(), role });
      onAdded();
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const inputStyle = {
    width: '100%', padding: '14px 16px', fontSize: 17 * theme.scale,
    background: theme.surfaceAlt, color: theme.ink, border: 'none',
    borderRadius: theme.cardRadius - 4, fontFamily: 'inherit',
    marginBottom: 12, boxSizing: 'border-box',
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.7)',
      display: 'flex', alignItems: 'flex-end', zIndex: 100,
    }}>
      <div style={{
        background: theme.surface, width: '100%',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        padding: '24px 20px 32px', maxHeight: '80%', overflowY: 'auto',
      }}>
        <h2 style={{ margin: '0 0 20px', fontSize: 22 * theme.scale, color: theme.ink, fontWeight: theme.titleWeight }}>新增帳號</h2>

        <Label theme={theme}>帳號 (登入用)</Label>
        <input value={username} onChange={e => setUsername(e.target.value)} autoCapitalize="none" placeholder="例如 wendy" style={inputStyle}/>

        <Label theme={theme}>顯示名稱</Label>
        <input value={displayName} onChange={e => setDisplayName(e.target.value)} placeholder="例如 阿強師傅" style={inputStyle}/>

        <Label theme={theme}>密碼</Label>
        <input value={password} onChange={e => setPassword(e.target.value)} type="text" style={inputStyle}/>

        <Label theme={theme}>角色</Label>
        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          {[['baker','一般師傅'],['admin','管理員']].map(([k,l]) => (
            <button key={k} onClick={() => setRole(k)} style={{
              flex: 1, padding: '14px', borderRadius: theme.cardRadius - 4, border: 'none',
              background: role === k ? theme.accent : theme.surfaceAlt,
              color: role === k ? '#1A1A1A' : theme.ink,
              fontSize: 15 * theme.scale, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
            }}>{l}</button>
          ))}
        </div>

        {err && <div style={{ padding: 10, marginBottom: 12, background: '#5a1a1a', color: '#ffb3b3', borderRadius: 8, fontSize: 13 * theme.scale }}>{err}</div>}

        <div style={{ display: 'flex', gap: 10 }}>
          <button onClick={onClose} style={{
            flex: 1, padding: '16px', borderRadius: theme.cardRadius, border: 'none',
            background: theme.surfaceAlt, color: theme.ink, fontSize: 16 * theme.scale, fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
          }}>取消</button>
          <button onClick={submit} disabled={busy} style={{
            flex: 1, padding: '16px', borderRadius: theme.cardRadius, border: 'none',
            background: theme.accent, color: '#1A1A1A', fontSize: 16 * theme.scale, fontWeight: 800, fontFamily: 'inherit', cursor: 'pointer',
          }}>{busy ? '建立中…' : '建立'}</button>
        </div>
      </div>
    </div>
  );
}

function ChangePasswordModal({ theme, user, onClose, onDone }) {
  const [password, setPassword] = useStateA('');
  const [busy, setBusy] = useStateA(false);
  const [err, setErr] = useStateA('');

  const submit = async () => {
    if (!password) { setErr('請輸入新密碼'); return; }
    setBusy(true); setErr('');
    try {
      await api.updatePassword(user.id, password);
      onDone();
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const inputStyle = {
    width: '100%', padding: '14px 16px', fontSize: 17 * theme.scale,
    background: theme.surfaceAlt, color: theme.ink, border: 'none',
    borderRadius: theme.cardRadius - 4, fontFamily: 'inherit',
    marginBottom: 12, boxSizing: 'border-box',
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.7)',
      display: 'flex', alignItems: 'flex-end', zIndex: 100,
    }}>
      <div style={{
        background: theme.surface, width: '100%',
        borderTopLeftRadius: 24, borderTopRightRadius: 24,
        padding: '24px 20px 32px',
      }}>
        <h2 style={{ margin: '0 0 6px', fontSize: 22 * theme.scale, color: theme.ink, fontWeight: theme.titleWeight }}>修改密碼</h2>
        <div style={{ fontSize: 14 * theme.scale, color: theme.inkMute, marginBottom: 20 }}>
          {user.display_name} <span style={{ opacity: 0.6 }}>@{user.username}</span>
        </div>

        <Label theme={theme}>新密碼</Label>
        <input value={password} onChange={e => setPassword(e.target.value)} type="text"
          placeholder="輸入新密碼" style={inputStyle}
          onKeyDown={e => e.key === 'Enter' && submit()}
        />

        {err && <div style={{ padding: 10, marginBottom: 12, background: '#5a1a1a', color: '#ffb3b3', borderRadius: 8, fontSize: 13 * theme.scale }}>{err}</div>}

        <div style={{ display: 'flex', gap: 10 }}>
          <button onClick={onClose} style={{
            flex: 1, padding: '16px', borderRadius: theme.cardRadius, border: 'none',
            background: theme.surfaceAlt, color: theme.ink, fontSize: 16 * theme.scale,
            fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
          }}>取消</button>
          <button onClick={submit} disabled={busy} style={{
            flex: 1, padding: '16px', borderRadius: theme.cardRadius, border: 'none',
            background: theme.accent, color: '#1A1A1A', fontSize: 16 * theme.scale,
            fontWeight: 800, fontFamily: 'inherit', cursor: 'pointer',
          }}>{busy ? '更新中…' : '確認修改'}</button>
        </div>
      </div>
    </div>
  );
}

// ────────── 歷史紀錄 ──────────
function HistoryScreen({ theme, session, onBack }) {
  const [logs, setLogs] = useStateA([]);
  const [loading, setLoading] = useStateA(true);
  const [err, setErr] = useStateA('');
  const [openId, setOpenId] = useStateA(null);
  const [openDates, setOpenDates] = useStateA({});
  const toggleDate = (date) => setOpenDates(prev => ({ ...prev, [date]: !prev[date] }));

  const refresh = async () => {
    try { setLogs(await api.listLogs({ limit: 500 })); }
    catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  };
  useEffectA(() => { refresh(); }, []);

  const grouped = useMemoA(() => {
    const g = {};
    for (const l of logs) {
      const d = new Date(l.created_at);
      const k = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
      (g[k] = g[k] || []).push(l);
    }
    return g;
  }, [logs]);

  const exportCSV = () => {
    const rows = [['時間','操作者','麵包','顆數','總粉量(g)','材料明細']];
    for (const l of logs) {
      const items = (l.recipe_payload?.sections || []).flatMap(s =>
        s.items.map(i => `${i.name}:${i.precise ? Math.round(i.amount*10)/10 : Math.round(i.amount)}g`)
      ).join(' | ');
      rows.push([
        new Date(l.created_at).toLocaleString('zh-TW'),
        `${l.display_name || ''}(@${l.username})`,
        (l.recipe_names || []).join('+'),
        l.total_pieces,
        Math.round(l.total_flour || 0),
        items,
      ]);
    }
    const csv = '\ufeff' + rows.map(r => r.map(c => `"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
    const a = document.createElement('a');
    a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' }));
    a.download = `celebread-history-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
  };

  const removeLog = async (id) => {
    if (!confirm('刪除這筆紀錄？')) return;
    try { await api.deleteLog(id); refresh(); } catch (e) { alert(e.message); }
  };

  return (
    <>
      <TopBar
        theme={theme} title="生產紀錄"
        leading={<IconBtn theme={theme} onClick={onBack}><IconBack color={theme.ink}/></IconBtn>}
        trailing={
          <button onClick={exportCSV} style={{
            border: 'none', background: theme.surface, color: theme.ink,
            padding: '8px 14px', borderRadius: 999,
            fontSize: 13 * theme.scale, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
          }}>CSV</button>
        }
      />
      <div style={{ flex: 1, overflowY: 'auto', padding: '0 16px 20px' }}>
        {loading && <div style={{ padding: 30, textAlign: 'center', color: theme.inkMute }}>讀取中…</div>}
        {err && <div style={{ padding: 16, color: '#ffb3b3', background: '#5a1a1a', borderRadius: 8, margin: 16 }}>{err}</div>}
        {!loading && !logs.length && <div style={{ padding: 40, textAlign: 'center', color: theme.inkMute }}>還沒有任何紀錄</div>}

        {Object.entries(grouped).map(([date, dayLogs]) => {
          const dateOpen = !!openDates[date];
          const totalPieces = dayLogs.reduce((s, l) => s + (l.total_pieces || 0), 0);
          const totalFlour = dayLogs.reduce((s, l) => s + (l.total_flour || 0), 0);
          return (
          <div key={date} style={{ marginBottom: 12 }}>
            <button onClick={() => toggleDate(date)} style={{
              width: '100%', padding: '14px 16px', textAlign: 'left',
              background: theme.surface, border: 'none', borderRadius: dateOpen ? `${theme.cardRadius}px ${theme.cardRadius}px 0 0` : theme.cardRadius,
              cursor: 'pointer', fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <div>
                <div style={{ fontSize: 15 * theme.scale, fontWeight: 800, color: theme.ink, letterSpacing: 0.5 }}>{date}</div>
                <div style={{ fontSize: 12 * theme.scale, color: theme.inkMute, marginTop: 2 }}>
                  {dayLogs.length} 筆 · {totalPieces} 顆 · {Math.round(totalFlour)}g 粉
                </div>
              </div>
              <span style={{ color: theme.inkMute, fontSize: 18 }}>{dateOpen ? '▴' : '▾'}</span>
            </button>
            {dateOpen && <div style={{ background: theme.surface, borderRadius: `0 0 ${theme.cardRadius}px ${theme.cardRadius}px`, overflow: 'hidden', borderTop: `1px solid ${theme.divider}` }}>
              {dayLogs.map((l, idx) => {
                const open = openId === l.id;
                const time = new Date(l.created_at).toLocaleTimeString('zh-TW', { hour: '2-digit', minute: '2-digit' });
                return (
                  <div key={l.id} style={{
                    borderBottom: idx < dayLogs.length - 1 ? `1px solid ${theme.divider}` : 'none',
                  }}>
                    <button onClick={() => setOpenId(open ? null : l.id)} style={{
                      width: '100%', padding: '14px 18px', textAlign: 'left',
                      background: 'none', border: 'none', cursor: 'pointer',
                      display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'inherit',
                    }}>
                      <div style={{
                        fontSize: 13 * theme.scale, color: theme.inkMute,
                        fontFamily: theme.fontFamilyNum, minWidth: 50,
                      }}>{time}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 16 * theme.scale, fontWeight: 700, color: theme.ink }}>
                          {(l.recipe_names || []).join(' + ')}
                        </div>
                        <div style={{ fontSize: 12 * theme.scale, color: theme.inkMute, marginTop: 2 }}>
                          {l.display_name || l.username} · {l.total_pieces} 顆 · {Math.round(l.total_flour || 0)}g 粉
                        </div>
                      </div>
                      <span style={{ color: theme.inkMute, fontSize: 18 }}>{open ? '▴' : '▾'}</span>
                    </button>
                    {open && (
                      <div style={{ padding: '0 18px 14px', fontSize: 13 * theme.scale, color: theme.inkSoft }}>
                        {(l.recipe_payload?.sections || []).map(s => (
                          <div key={s.title} style={{ marginTop: 8 }}>
                            <div style={{ fontWeight: 700, color: theme.ink, marginBottom: 4 }}>{s.title}</div>
                            {s.items.map(i => (
                              <div key={i.name} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>
                                <span>{i.name}</span>
                                <span style={{ fontFamily: theme.fontFamilyNum }}>
                                  {i.precise ? (Math.round(i.amount*10)/10).toFixed(1) : Math.round(i.amount)}{i.unit || 'g'}
                                </span>
                              </div>
                            ))}
                          </div>
                        ))}
                        {session.role === 'admin' && (
                          <button onClick={() => removeLog(l.id)} style={{
                            marginTop: 12, padding: '8px 14px', borderRadius: 8, border: 'none',
                            background: 'transparent', color: '#ff6b6b', fontSize: 12 * theme.scale,
                            cursor: 'pointer', fontFamily: 'inherit',
                          }}>刪除這筆</button>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>}
          </div>
          );
        })}
      </div>
    </>
  );
}

// ────────── 抽屜選單 ──────────
function MenuDrawer({ theme, session, onClose, onLogout, onUsers, onHistory }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 90,
      background: 'rgba(0,0,0,0.6)', display: 'flex',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '78%', maxWidth: 320, background: theme.surface,
        display: 'flex', flexDirection: 'column', padding: '40px 0 24px',
      }}>
        <div style={{ padding: '0 24px 24px', borderBottom: `1px solid ${theme.divider}` }}>
          <div style={{ fontSize: 12 * theme.scale, color: theme.inkMute, letterSpacing: 1.5 }}>已登入</div>
          <div style={{ fontSize: 22 * theme.scale, color: theme.ink, fontWeight: theme.titleWeight, marginTop: 4 }}>{session.display_name}</div>
          <div style={{ fontSize: 13 * theme.scale, color: theme.inkSoft }}>@{session.username} · {session.role === 'admin' ? '管理員' : '師傅'}</div>
        </div>
        <div style={{ flex: 1, padding: '12px 0' }}>
          {session.role === 'admin' && (
            <>
              <MenuItem theme={theme} onClick={onHistory}>📋  生產紀錄</MenuItem>
              <MenuItem theme={theme} onClick={onUsers}>👥  帳號管理</MenuItem>
            </>
          )}
        </div>
        <div style={{ padding: '0 16px' }}>
          <button onClick={onLogout} style={{
            width: '100%', padding: '14px', borderRadius: theme.cardRadius, border: 'none',
            background: theme.surfaceAlt, color: theme.ink, fontSize: 15 * theme.scale,
            fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer',
          }}>登出</button>
        </div>
      </div>
    </div>
  );
}
function MenuItem({ theme, onClick, children }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '16px 24px', textAlign: 'left',
      background: 'none', border: 'none', cursor: 'pointer',
      fontSize: 17 * theme.scale, color: theme.ink, fontFamily: 'inherit', fontWeight: 600,
    }}>{children}</button>
  );
}

function Label({ theme, children }) {
  return <div style={{
    fontSize: 11 * theme.scale, color: theme.inkMute, letterSpacing: 1.5,
    textTransform: 'uppercase', marginBottom: 6, marginTop: 4, fontWeight: 700,
  }}>{children}</div>;
}
function IconBtn({ theme, onClick, children }) {
  return <button onClick={onClick} style={{
    width: 44, height: 44, borderRadius: 22, border: 'none',
    background: theme.surface, cursor: 'pointer',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  }}>{children}</button>;
}
function IconMenu({ color }) {
  return <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
    <path d="M4 7h16M4 12h16M4 17h16" stroke={color} strokeWidth="2.4" strokeLinecap="round"/>
  </svg>;
}

Object.assign(window, {
  LoginScreen, UsersScreen, HistoryScreen, MenuDrawer, IconBtn, IconMenu, Label,
});
